text:
Q: I'm being warned that the Monoid I'm creating is an Orphan Instance. Is there a better way to write this functionality in? type PromptSegment = IO (Maybe String)

instance Monoid a => Monoid (IO a) where
  mempty = return mempty
  mappend = liftA2 (<>)

This behaves exactly how I want for my purposes.
For example:
ghci> let a = return $ Just "hello" :: IO Maybe String
ghci> let b = return $ Just " world" :: IO Maybe String
ghci> let c = return $ Nothing :: IO Maybe String
ghci> a `mappend` b `mappend` c
Just "hello world"

However, I'm pretty aware that maybe, for a different Monoid a => Monoid (IO a) instance other than a PromptSegment, maybe I wouldn't want mappend to behave the same way??  I feel like there's better way to do this than creating the orphan monoid instance above.
Current API design
currentDirectory :: PromptSegment
currentDirectory = Just <$> getCurrentDirectory

main :: IO ()
main = buildMainPrompt
         [ bold . fgColor skyBlue <$> currentDirectory
         ,  (fgColor deepSkyBlue3 . underline . bold <$> gitCurrentBranch)
           <> (fgColor defaultDarkGreen . bold <$> gitRepositorySymbol "±")
           <> gitStatusSegment
         ]
         (fgColor red0 . bold <$> makePromptSegment " ➢ ")
         (fgColor slateBlue0 . bold <$> makePromptSegment " λ» ")

gitStatusSegment :: PromptSegment
gitStatusSegment =
  let unstagedSymbol = fgColor gold1 <$> gitUnstagedSymbol "✚"
      stagedSymbol   = fgColor orange <$> gitStagedSymbol "✎"
      pushSymbol     = fgColor red1 . bold <$> gitPushSymbol "↑"
  in prependSpace <$> unstagedSymbol <> stagedSymbol <> pushSymbol

This is, of course, a work in progress, but the aim of the program is to create a DSL for defining cli prompt themes (starting with ZSH).This last code sample is mostly to serve the purpose of providing context to the question for why I would want to make IO (Maybe String) a Monoid.  I'm wide open to harsh criticism - especially since this is my first attempt at writing a 'real' program in Haskell.

A: There is are reasons behind warning again orphan instances. In particular: If we start using orphan instances, modules can become mutually incompatible: What if two modules define two different instances Monoid (IO a)? There is no good way to tell which one should be preferred.
Furthermore using orphan instances often leads to bad program design. If you add an orphan instance to a data type, you're adding some functionality to the data type. And sooner or later you'll also need to modify the functionality, which isn't (by design) possible with Haskell type classes. At this point you either have to refactor your program or start bending the rules add mess up your design. (This is different from the OO world where subclasses are meant to modify some of the functionality of their parents.)
Therefore I'd strongly suggest to create a new data type for your use case. You'll pay a small one-time price for creating aliases for functions you'll use in your project (most likely in a dedicated module), like
import qualified System.Directory as D
getCurrentDirectory :: MyDSL FilePath
getCurrentDirectory = --  something wraping D.getCurrentDirectory

or more generally define instance MonadIO MyDSL and then
getCurrentDirectory :: MonadIO FilePath
getCurrentDirectory = liftIO D.getCurrentDirectory

But then  your implementation will be completely independent and as your project evolves, nothing will limit you to make the internals of MyDSL more complex or add functionality. Moreover, it'll be safe to use as a library in other projects, without the risk of getting conflicting instances.
Such separation is even more important when you're creating a DSL, because in this case you strongly want to separate the language from its internal implementation. Using an existing data type for a DSL is very likely to cause problems, either when implementing it or due to improper usage by its users.


text:
Q: Hausdorff dimension of product omega-languages In this question I will refer to Hausdorff dimension and measure of regular $\omega$-languages as defined here. Hereby I give a quick recap of the definitions before diving into the question.
Recap
An $\omega$-language $F \subseteq \Sigma^\omega$ is any set of infinite sequences of symbols from the finite alphabet $\Sigma$ of size $r = |\Sigma|$. We call a cover of F a set $W \subseteq \Sigma^*$ of finite sequences of symbols in the same alphabet such that $W \cdot \Sigma^\omega \supseteq F$ (where $W \cdot \Sigma^\omega$ denotes the set of all the infinite sequences obtained by concatenating a sequence in $W$ with an infinite sequence in $F$). We denote by $\mathcal{L}_l$ the set of all $W$s whose sequences have length at least $l$.
The $\alpha$-dimensional Hausdorff measure of $F$ is defined as
$$m_\alpha(F) = \lim_{n \rightarrow \infty} \inf_{W \in \mathcal{L}_l} \sum_{w \in W} r^{-\alpha |w|}\;.$$
The Hausdorff dimension of $F$ is the unique number
$$\dim(F) = d = \sup \{\alpha|m_\alpha(F)=\infty\} = \inf \{\alpha|m_\alpha(F)=0\} \;.$$
Question
I am interested in computing the Hausdorff dimension of the product of two $\omega$-languages $F_1$ and $F_2$ over disjoint alphabets $\Sigma_1$ and $\Sigma_2$.
Let $\Sigma = \Sigma_1 \times \Sigma_2$ of sizes $r_1$ and $r_2$ respectively, and two languages $F_1$ and $F_2$ such that $\dim(F_1) = d_1$ and $\dim(F_2)=d_2$ (where the measures are computed using $r_1$ and $r_2$ respectively). Let
$$F=\{f=(f_{11},f_{12})(f_{21},f_{22})(f_{31}f_{32})\dots|f_{11}f_{21}f_{31}\dots\in F_1 \land f_{12}f_{22}f_{32}\dots\in F_2\} \;.$$
What is the Hausdorff dimension of $F$ as an $\omega$-language with alphabet $\Sigma$?
My reasoning so far I think I should reason by considering the Hausdorff measure of $F$ as the product measure of the Hausdorff measures of $F_1$ and $F_2$. But is it true that
$$m_d(F) = m_{d_1}(F_1)m_{d_2}(F_2)$$
(considering also $r_1$ and $r_2$ as hidden parameters of $m_{d_1}$ and $m_{d_2}$) for some $d$? If so, for which $d$?
I regret I do not have an education in measure theory and I may be missing something, but indeed it vaguely looks to me that the measure of F can be seen as a joint probability of independent events (picking $f_{11}f_{21}\dots$ from $F_1$ and $f_{12}f_{22}\dots$ from $F_2$), and I know $m_d$ is a measure function. So it may be the case that it factorizes over the measures of $F_1$ and $F_2$. But I would not know how to simplify the product of the two $\lim \inf$. Just by means of changing the bases $r_1$ and $r_2$ into $r$ and by the fact that $d$ is in the exponent of the definition, it seems to me the answer may be
$$\dim(F) = d_1 \log_r r_1 + d_2 \log_r r_2 \;.$$
If anyone had some pointers on how to address this question, I would be very grateful.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Oracle provider for Oledb missing in VS 2015 Shell I am migrating to SSIS  2016 version. I am trying to use the Oracle provider for Oledb in connections.
However, this option does not show. I have installed the Oracle client 12.2 and I am able to do UDL file testing, where in I can see the Oracle provider and able to test connection.
But when I try in VS 2015, the option is not shown.
The issue is described here  - https://jorgklein.com/2011/06/02/ssis-connect-to-oracle-on-a-64-bit-machine-updated-for-ssis-2008-r2/  and based on this I have installed the 64 bit client . But when trying to use the connection manager, the oracle provider is not shown.
How to fix this?

A: The recommended way to connect to Oracle from SSIS is using Attunity Connectors with guarantee high performance and are easy to use. If you choose to work with Oracle Provider for OLEDB than you should download Oracle Data Access Components (ODAC) and the Oracle Visual Studio Tools.
In this answer i will provide detailed information about how to connect to Oracle from SSIS and i will provide some links to the solution for your issue

There are many way to connect to oracle from SSIS:
(1) Oracle Provider for OLEDB
Which is a part of the Oracle Data Access Components (ODAC)

*

*Oracle - Visual Studio Tools

*32-bit Oracle Data Access Components (ODAC) and NuGet Downloads

*Oracle Provider for OLEDB
The following link contains a similar issue:

*

*Oracle OLE DB Provider not Listed in SSIS
(2) Microsoft OLEDB Provider for Oracle
Which is a part from Microsoft Data Access Components (MDAC)

This feature will be removed in a future version of Windows. Avoid using this feature in new development work, and plan to modify applications that currently use this feature. Instead, use Oracle's OLE DB provider.

*

*Microsoft OLE DB Provider for Oracle Overview
(3) Oracle Attunity connectors

Attunity's high speed connectors for Oracle and Teradata have been selected by Microsoft to be included with SQL Server Integration Services (SSIS).

*

*Microsoft Connectors for Oracle and Teradata by Attunity for Integration Services (SSIS)

*Microsoft Connectors by Attunity

Discussion

*

*SSIS Connectors for Oracle by Attunity vs Oracle provider for OLE DB performances

*Oracle Client DataProvider VS Oracle Provider for OLEDB

Other helpful links

*

*Importing From Oracle In SSIS (from Oracle client installation to data import)

*Microsoft OLE DB Provider for Oracle (MSDAORA) for 64 bit?

*SSIS with Oracle Connectors


text:
Q: compare 2 spark RDD to make sure that value from first is in the range of the second RDD there are 2  very large RDD(each has more than milion records), the first is :
rdd1.txt(name,value):
chr1    10016
chr1    10017
chr1    10018
chr1    20026
chr1    20036
chr1    25016
chr1    26026
chr2    40016
chr2    40116
chr2    50016
chr3    70016

rdd2.txt(name,min,max):
chr1     10000  20000
chr1     20000  30000
chr2     40000  50000
chr2     50000  60000
chr3     70000  80000
chr3    810001  910000
chr3    860001  960000
chr3    910001  1010000

the value is valid only when it's in the range  between the Min and Max of the second RDD , the count of  the name's occurs will plus 1 if its valid
Take the above as an example,   the chr1's  occurs 7.
how can i get the result in scala with spark?
many thanks

A: Try:
val rdd1 = sc.parallelize(Seq(
  ("chr1", 10016 ), ("chr1", 10017), ("chr1", 10018)))
val rdd2 = sc.parallelize(Seq(
   ("chr1", 10000, 20000), ("chr1",20000, 30000)))

rdd1.toDF("name", "value").join(rdd2.toDF("name", "min", "max"), Seq("name"))
 .where($"value".between($"min", $"max"))

A: As I understand , you want values from rdd1 that fall between min and max in rdd2. Please see if the below works
val rdd1 = sc.parallelize(Seq(("chr1", 10016 ), ("chr1", 10017), ("chr1", 10018)))
val rdd2 = sc.parallelize(Seq(("chr1", 10000, 20000), ("chr1",20000, 30000)))
rdd1.toDF("name", "value").join(rdd2.toDF("name", "min", "max"), Seq("name")).where($"value".between($"min", $"max")).groupBy($"name").count().show()

scala> val rdd1=sc.parallelize(Seq(("chr1",    10016 ),("chr1",    10017 ),("chr1",    10018 ),("chr1",    20026 ),("chr1",    20036 ),("chr1",    25016 ),("chr1",    26026),("chr2",    40016 ),("chr2",    40116 ),("chr2",    50016 ),("chr3",    70016 )))
rdd1: org.apache.spark.rdd.RDD[(String, Int)] = ParallelCollectionRDD[33] at parallelize at <console>:24

scala> val rdd2=sc.parallelize(Seq(("chr1",     10000,  20000),("chr1",     20000 , 30000),("chr2",     40000  ,50000),("chr2",     50000  ,60000),("chr3",     70000  ,80000),("chr3",    810001  ,910000),("chr3",    860001  ,960000),("chr3",    910001  ,1010000)))
rdd2: org.apache.spark.rdd.RDD[(String, Int, Int)] = ParallelCollectionRDD[34] at parallelize at <console>:24

scala> rdd1.toDF("name", "value").join(rdd2.toDF("name", "min", "max"), Seq("name")).where($"value".between($"min", $"max")).groupBy($"name").count().show()
+----+-----+
|name|count|
+----+-----+
|chr3|    1|
|chr1|    7|
|chr2|    3|
+----+-----+

Edits
If you are reading from a file , i would use the following
import org.apache.spark.sql.SQLContext
import org.apache.spark.sql.types.{StructType, StructField, StringType, IntegerType};

val sqlContext = new SQLContext(sc)
val nameValueSchema = StructType(Array(StructField("name", StringType, true),StructField("value", IntegerType, true)))
val nameMinMaxSchema = StructType(Array(StructField("name", StringType, true),StructField("min", IntegerType, true),StructField("max", IntegerType, true)))
val rdd1 = sqlContext.read.format("com.databricks.spark.csv").option("header", "false").schema(nameValueSchema).load("rdd1.csv")
val rdd2 = sqlContext.read.format("com.databricks.spark.csv").option("header", "false").schema(nameMinMaxSchema).load("rdd2.csv")
rdd1.toDF("name", "value").join(rdd2.toDF("name", "min", "max"), Seq("name")).where($"value".between($"min", $"max")).groupBy($"name").count().show()

This will run on all nodes and there is no need of parallelize call. Quoting the documentation here

def parallelize[T](seq: Seq[T], numSlices: Int =
  defaultParallelism)(implicit arg0: ClassTag[T]): RDD[T]  Permalink
  Distribute a local Scala collection to form an RDD.


text:
Q: ActiveRecord condition with count less than for association I have a User that has_many messages.
I need a create a query that will
'Get me all users who's (message.opened == false) count < 3'
Right now, I am using User.all, iterating through all users, and counting manually. I understand that this isn't very efficient and it can be all done in one query, but I am new to SQL/ActiveRecord so need some help here.
Thanks

A: Try this
User.includes(:messages).group('users.id').having('SUM(IFNULL(messages.opened = 0, 1)) < 3')

It works at least on MySQL, AND assuming your boolean true are 1 in database.
EDIT I had reversed the condition
PS IFNULL is there to handle if messages.opened can be NULL

A: Assuming Rails 3 syntax. You can do something like:
User.joins(:messages).where(:messages => {:opened => false}).group(:user_id).having("COUNT(messages.id) < 3)

A: This should work:
User.includes(:messages).group("users.id").where("messages.opened = 0").having("count(messages.id) < 3")

This will create two queries, one for the grouped query, and one for eager loading the resulting users and messages with a join.

A: Here is solution to your problem
User.includes(:messages).group("users.id").where("messages.opened = 0").having("count(messages.id) < 3")

but what else you can do is to create a scope for this
scope :not_opened_less_three_count, includes(:messages).group("users.id").where("messages.opened = 0").having("count(messages.id) < 3")

And then you can use it anywhere you needed as follow
User.not_opened_less_three_count


text:
Q: Is it a known phenomenon for the variance of a component (GMM) to increase without stopping? I know it can happen for it to decrease dramatically as it overfits on a single datapoint. But I've never read about a component "taking everything over". See the following images (circles are stddevs). Could this be (relatively) normal behaviour?
edit: For some reason changing my gaussian function made the behaviour sane, note both return the same output for given inputs:

iter 300!

A: I think what is happening is that in the event of a component stepping towards the center of all the datapoints while already having the largest variance(s), as the posteriors/responsibilities of all the datapoints will increase (as its coming close to the center), the variance will get larger, which will make it take another step towards the center and so on.
At the same time, it seems something is wrong with my implementation as the component that is getting "swallowed" should not be staying still, as the culprit gets the larger variance and moves closer, the posteriors/responsibilities of the swallowed one should make it move away, yet it barely budges. So it seems to just be a bug of my code.
edit: Don't think there's a mistake anymore. The large variance makes the density quite low and so the responsibilities of the swallowed cluster one barely decrease.


text:
Q: Compare 2d numpy array to itself to form 3d array I've got a simple 2d numpy array like this
array([[1, 0, 1],
       [1, 1, 0],
       [0, 1, 1],
       [0, 0, 0],
       [1, 0, 0]])

What I'm trying to do is multiply each row of the array by itself to form a 3d array, (so that 1*1 = 1 and anything else will be 0, essentailly an and function):
array([[[1,0,1],[1,0,0],[0,0,1],[0,0,0],[1,0,0]],
       [[1,0,0],[1,1,0],[0,1,0],[0,0,0],[1,0,0]],
       ...,
       ...,
       ...])

A: Turns out the answer is pretty simple. If the array is x:
x[np.newaxis,:,:]*x[:,np.newaxis,:]

And this works with things such as logical expressions, if you want to just compare on identical elements in each row, you could do something like:
np.logical_not(np.logical_xor(x[np.newaxis,:,:], x[:,np.newaxis,:]))

Which would return:
array([[[ True,  True,  True],
        [ True, False, False],
        [False, False,  True],
        [False,  True, False],
        [ True,  True, False]],

       [[ True, False, False],
        [ True,  True,  True],
        [False,  True, False],
        [False, False,  True],
        [ True, False,  True]],

       ...,
       ...,
       ...], dtype=bool)


text:
Q: Pumping lemma for $a^n b^{2n}$ I have this question and i am not sure and trying to solve in both way  that is through diagram and expression:
Question : Prove that $a^nb^{2n}$  is not regular.
contradiction:
 Assume language is regular
----->()------>()------>(o)
      x         y        z

     x y^i z

 through diagram:  abb    when y^0
                   aabb      , y^1
                   aaabbb       y=2
so given language is not regular.

Is it correct?? Thanks


text:
Q: Weird cursor behavior: Almost always the resize cursor. (win32 api) I'm working with the win32 API, and am using it to make a window. This window works, but when I open it, the cursor is a loading cursor, and every time I bring my cursor to the edge to resize it, the cursor gets 'stuck' as that resizing cursor, it doesn't go back to normal. Here's a video to explain what I'm talking about:

Here's the reproducible example (compile with g++ reproducible_example.cpp -mwindows -O3 -o reproducible_example.exe):
#undef UNICODE
#undef _UNICODE
#define WIN32_LEAN_AND_MEAN
#include <windows.h>

bool isRunning = true;

void *buffer;   // buffer memory
BITMAPINFO bmi; // bit map information, needed for rendering

int width, height; // main window's width and height

LRESULT __stdcall WindowProc(HWND, UINT, WPARAM, LPARAM);

int __stdcall WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
                      LPSTR pCmdLine, int nCmdShow) {
  LPCSTR CLASS_NAME = "Class Name";

  WNDCLASS wc = {};

  wc.lpfnWndProc = WindowProc;
  wc.hInstance = hInstance;
  wc.lpszClassName = CLASS_NAME;

  RegisterClass(&wc);

  // Create the window.

  HWND hwnd = CreateWindowExA(0,                   // Optional window styles.
                              "Class Name",        // Window class
                              "Window",            // Window text
                              WS_OVERLAPPEDWINDOW, // Window style

                              // Size and position
                              CW_USEDEFAULT, CW_USEDEFAULT, 1280, 720,

                              NULL,      // Parent window
                              NULL,      // Menu
                              hInstance, // Instance handle
                              NULL       // Additional application data
  );

  if (hwnd == NULL)
    return 0;

  ShowWindow(hwnd, nCmdShow);

  bmi.bmiHeader.biSize = sizeof(bmi.bmiHeader);
  bmi.bmiHeader.biPlanes = 1;
  bmi.bmiHeader.biBitCount = 32;
  bmi.bmiHeader.biCompression = BI_RGB;

  // Run the message loop.
  HDC hdc = GetDC(hwnd);
  while (isRunning) {
    MSG msg;
    if (PeekMessage(&msg, hwnd, 0, 0, PM_REMOVE) > 0) {
      TranslateMessage(&msg);
      DispatchMessage(&msg);
    }

    StretchDIBits(hdc, 0, 0, width, height, 0, 0, width, height, buffer, &bmi,
                  DIB_RGB_COLORS, SRCCOPY);
  }
  ReleaseDC(hwnd, hdc);
  return 0;
}

LRESULT __stdcall WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam,
                             LPARAM lParam) {
  switch (uMsg) {
  case WM_DESTROY:
    isRunning = false;
    return 0;
  case WM_SIZE: {
    // Calculate window height and width
    width = LOWORD(lParam);
    height = HIWORD(lParam);

    if (buffer) // If memory already exists
                // free it
      VirtualFree(buffer, 0, MEM_RELEASE);

    // Allocate buffer memory
    buffer = VirtualAlloc(0, width * height * sizeof(unsigned int),
                          MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);

    bmi.bmiHeader.biWidth = width;
    bmi.bmiHeader.biHeight = height;
  }
    return 0;
  }
  return DefWindowProc(hwnd, uMsg, wParam, lParam);
}

Now, I know this isn't some weird windows bug and is definitely something with my code, because it doesn't happen in other apps which I open, and it also didn't happen when I made an equivalent window with SFML (probably because the windows api and SFML are entirely different things). Code for that window:
#include <SFML/Graphics.hpp>

int main() {
  sf::RenderWindow window(sf::VideoMode(1280, 720), "Window");
  while (window.isOpen()) {
    sf::Event event;
    while (window.pollEvent(event)) {
      if (event.type == sf::Event::Closed) {
        window.close();
      }

      if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape)) {
        window.close();
      }
    }
    window.clear();
    window.display();
  }
}

I want the first window to act like the second window, but the cursor is the one discrepancy I can find. I've tried googling this, but to no avail. I followed a youtube tutorial series for the window I'm having problems with. Also, on downloading the tutorial's source code and removing some code which makes it full screen and hides the cursor, it has the same problem. How do I fix this? Thank you in advance.

A: Set wc.hCursor to something other than null. If it's null, the operating system will leave the cursor alone when it enters your window, and you're supposed to set it to the cursor you want.
Most likely you want the boring old arrow cursor. You can get that cursor by calling LoadCursor(NULL, IDC_ARROW).


text:
Q: Simultaneous congruences to different moduli For some natural numbers $a,b$, let it be known that $b\leq 8$:
$$b\cdot 99a = x68y - 8$$
where we read $x68y$ as x-thousand sixhundred and eighty-y.
What I have established is:
$$\begin{cases}b\mid (x68y-8)&\Longleftrightarrow x68y\equiv 8\pmod{b}\\
 99a\mid (x68y-8)&\Longleftrightarrow x68y\equiv 8\pmod{99a}\end{cases} $$
The objective is to determine $a,b$ and for that I thought I would check all possibilities for $b: 8,7,6,5,4,3,2,1$ and see whether 99 divides any of the numbers produced in each case. This turns out to be quite tedious.
What can I do to optimize my work?

A: The answer is $b=3$ and $a=9$. Also $x=2, y=1$.
On a hunch I checked whether $b=3$ that means $x68y\equiv 2\pmod{3}$ i.e $3\mid (x68y-2)$ which is the same as $3\mid (x+y+14-2)$ (sum of digits). Since it seems unlikely that $y$ is even I took $y=1$ that leaves $x\in\{2,5,8\}$ and on my first attempt, indeed $99\mid (2681-8)$ as required.
$99\mid (x68y-8)$ is the key. Makes this problem 99 times easier.
Doesn't have to be only this solution, though. $b=1, a=27$ is also a possibility unless I'm missing something.


text:
Q: select uncommon records between two tables - mysql I have two tables, table A and table B with the same column names. I want to fetch those records which are not present in table A but present in table B.
Thanks in advance.

A: Use a left join
Select * from tableb left join tablea on tableb.column = tablea.coulmn where tablea.column is null

A: Some databases support except or minus.  But not MySQL.  I would recommend not exists:
select b.*
from b
where not exists (select 1
                  from a
                  where a.col1 = b.col1 and a.col2 = b.col2 and . . .
                 );

Note that this will not work if any columns have NULL values.
If you need to handle NULLs, you could use (not a.col1 <=> b.col1) and (not a.col2 <=> b.col2) . . ..  Or, you could use aggregation:
select col1, col2, . . .
from ((select a.*, 1 as is_a, 0 as is_b
       from a
      ) union all
      (select b.*, 0, 1
       from b
      )
     ) ab
group by col1, col2, . . .
having max(is_a) = 0 and max(is_b) = 1;

A: Suppose the rows are same if their primary keys are same (for example, id field). Than you can:
select id from b where id not in (select id from a)

If your tables has no primary keys or they do not match - you can alter the query to your tables structure.


text:
Q: one to one mapping on different column names I have two different tables, Person table and Employee table. I need a one-to-one mapping between these two. Employee table's emp_id references Person table's id. I need some help in writing the mapping xml.
person.hbm.xml:
<hibernate-mapping>
  <class name="Persons" table="Persons">
    <id name="id" column="id" type="java.lang.Integer">
      <generator class="native"></generator>
    </id>
    <property name="firstName" column="FIRST_NAME" type="java.lang.String">
    </property>
    <one-to-many name="employee" column="per_id" unique="true" class="Persons"
      not-null="true"/>
  </class>
</hibernate-mapping>

employee.hbm.xml
<hibernate-mapping>
  <class name="Employee" table="Employee">
    <id name="id" column="id" type="java.lang.Integer">
      <generator class="native"></generator>
    </id>
    <property name="name_id" column="NAME_ID" type="java.lang.String">
    </property>
    <property name="emp_id" column="emp_ID" type="java.lang.String">
    </property>
  </class>
</hibernate-mapping>

How do I write the mapping taking emp_id of Employee table and id from Persons table?
Note: id of Persons table is the primary key

A: In employee.hbm.xml :
<many-to-one name="person" class="Persons" column="emp_ID" />

To make the relationship bidirectional you can add the following in person.hbm.xml:
<one-to-one name="employee" class="Employee" property-ref="person"/>

It will be more understandable and not confusing to others, if you could modify the emp_ID column(foriegn key column) in employee table that refers persons table "id" column to person_id
Employee Table:
Rename emp_ID --> person_id


text:
Q: Website doesn't display properly The website I'm developing suddenly stopped working properly. The images on my Homepage appear sliced and in weird places (however when inspecting source and hovering over certain elements, the highlighted content seems to be in the right place), some hover on effects don't work and some text doesn't render.
Everything works properly in all other browsers except for Google Chrome. I cannot think of any other thing I've updated in the source code than executing svginjection plugin.
I uploaded my backed up files that used to work before, but the problem still occurs. It doesn't show up on every single computer, just on some (and I've checked it on multiple machines, both - Mac and Windows).
Just to clarify, I did clear the cache, I did check in the Incognito mode, I did restart my computer. None of these helped. I'm also 80% sure that problem only occurs on computers, on which this website was previously opened (the pattern I noticed after making around 10 tests at work).
Thanks for any help

A: Aight, so after going through all my files, trying to disable multiple options, etc... Everything is fixed now. If you do have similar problem, go through your css files and disable all webkit powered transforms and transitions, cause apparently enough is enough and if you have too many, Chrome just won't handle it. I managed to still reuse some of them, so... Must have caused some glitch in the matrix and that's why it all got messed up. For weirdly positioned images check z-index of parent container.


text:
Q: Radio Buttons not Pre-populating if there is an Existing Record This is a simple application with a form with 3 questions. Each question has 2 options. If a user has previously submitted answers, then the form should pre-populate, but for some reason, it is not.
Here's the code. Any help or guidance is GREATLY appreciated.
<?php

    $user_id = $_SESSION['user_id'];
    $anthem1 = '';
    $cointoss2 = '';
    $firstscore3 = '';

    if (isset($_POST['submit'])) {

        if (isset($_POST['anthem1'])) {

            $anthem1 = mysqli_real_escape_string($connection, $_POST['anthem1']);
        }

        if (isset($_POST['cointoss2'])) {
             $cointoss2 = mysqli_real_escape_string($connection, $_POST['cointoss2']);
        }

        if (isset($_POST['firstscore3'])) {
             $firstscore3 = mysqli_real_escape_string($connection, $_POST['firstscore3']);
        }

        $query = "INSERT INTO mypicks (user_id, anthem1, cointoss2, firstscore3)
                      VALUES ('{$user_id}','{$anthem1}','{$cointoss2}','{$firstscore3}')
                      ON DUPLICATE KEY UPDATE anthem1 = '{$anthem1}',
                      cointoss2 = '{$cointoss2}',
                      firstscore3 = '{$firstscore3}'";

        $result = mysqli_query($connection, $query);
    }

    $query = "SELECT * FROM mypicks WHERE user_id = {$user_id}";
    $result = mysqli_query($connection, $query);
    if($result->num_rows == 1) {

        $user_picks = mysqli_fetch_row($result);
        $anthem1 = $user_picks['anthem1'];
        $cointoss2 = $user_picks['cointoss2'];
        $firstscore3 = $user_picks['firstscore3'];
    }

?>

Here's the form (one question from it):
<form action="Game1_MyPicks.php" method="post">

Will the National Anthem be over 3 mins and 15 secs?

Over  <input type="radio" name="anthem1" value="Over" <?php if ($anthem1=="Over") print('checked="checked"') ?>/>

Under <input type="radio" name="anthem1" value="Under" <?php if ($anthem1=="Under") print('checked="checked"') ?>/>

</form>

A: <input type="radio" name= "anthem1" value="" <?php if ($anthem1) echo "checked";?>>

A:     <form action="Game1_MyPicks.php" method="post">

Will the National Anthem be over 3 mins and 15 secs?

Over  <input type="radio" name="anthem1" value="Over" <?php if ($anthem1=="Over") print("checked"); ?>/>

Under <input type="radio" name="anthem1" value="Under" <?php if ($anthem1=="Under") print("checked"); ?>/>

</form>


text:
Q: ETL script - 'object' does not contain a definition of 'Value' in Microsoft.Office.Interop I have a .net 4.5 project getting data from an Excel file and saving some of it to files. It runs perfectly.
However, I decided to make an ETL process of running this script and then uploading it to a database. In the script task of the ETL process I simply paste the same code to the window, add the same references etc and get a bug: 'object' does not contain a definition of 'Value'.
Here's the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop;
using Excel = Microsoft.Office.Interop.Excel;

namespace etl.csproj
{
        public void Main()
        {
            process();
            Dts.TaskResult = (int)ScriptResults.Success;
        }

        static void process()
        {
            string mySheet = @"C:\\pathToMyExcelFile";
            System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\my file.txt");
            Excel.Application excelApp = new Excel.Application();
            Excel.Workbook xlWorkBook = excelApp.Workbooks.Open(mySheet, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
            Excel.Sheets sheets = xlWorkBook.Worksheets;
            Excel.Worksheet worksheet;

            for (int i = 1; i < sheets.Count; ++i)
            {
                worksheet = (Excel.Worksheet)sheets.get_Item(i);
                for (int j = 5; j <= 9; ++j)
                {
                    for (int k = 68; k <= 72; k++)
                    {

                        if (worksheet.Cells[k, j].Value2 != null) //HERE IS THE ERROR
                        {
                            file.WriteLine(worksheet.Name + "|" + (string)(worksheet.Cells[k, 2] as Excel.Range).Value /*ERROR HERE*/ + "|" + (j - 4).ToString() + "|" + worksheet.Cells[k, j].Text/*ERROR HERE*/);
                        }
                    }

                }

            }
            file.Close();
        }

    }
}

The only change in those two projects' metadata is that the latter is built in .NET 3.5, not 4.5 (I cannot change the version).
I would be grateful for any help!


text:
Q: Emacs 24.3 for windows, Tramp byte-code: Couldn't find a proper `ls' command 24.2 works well, but 24.3 bounded tramp got following error when open remote Linux system files or directories:
"byte-code: Couldn't find a proper `ls' command"

I open tramp trace and find that, all remote search path and file path are extend by something, adding a extra "c:" at the beginning. The results is that tramp can find neither command nor file I want to open.
16:04:51.768000 tramp-get-connection-property (7) # process-buffer nil
16:04:51.769000 tramp-set-file-property (8) # c:/bin file-directory-p nil
16:04:51.770000 tramp-get-file-property (8) # c:/usr/bin file-directory-p undef
...
16:04:59.531000 tramp-sh-handle-file-truename (5) # Check /c:
16:04:59.532000 tramp-get-file-property (8) # c:/c: file-attributes-integer undef
...
16:04:51.773000 tramp-get-connection-property (7) # process-name nil
16:04:51.773000 tramp-get-connection-property (7) # chunksize 0
16:04:51.773000 tramp-set-connection-property (7) # last-cmd-time (20809 28067 773000 0)
16:04:51.774000 tramp-send-string (10) # test -d c\:/usr/bin 2>/dev/null; echo tramp_exit_status $?

Anyone know something about this? Thanks in advance.

A: It seems this is a bug in tramp but you don't need to upgrade tramp, all you have to do is recompile tramp-sh.el on a Windows box. See the bug report here for more information.
Enter this on the scratch buffer:
(byte-compile-file "C:/Program Files/emacs/lisp/net/tramp-sh.el")

adjusting the path to match your install, then type Ctrl-Meta-x to recompile the file. If it complains about permissions you might need to restart emacs using the "run as administrator" option in Windows.
Once the file is recompiled type M-x tramp-cleanup-all-connections in order to reset the tramp connection cache. This will close any tramp connections you have open.

A: I had the same problem after switching to Emacs 24.3. The solution was to upgrade to the latest Tramp 2.2.7. Here is what I did:

*

*downloaded http://ftp.gnu.org/gnu/tramp/tramp-2.2.7.tar.gz

*unpacked the archive to my ~/.emacs.d/src. I am using emacs-starter-kit which adds this directory and all its subdirectories to the load-path. Otherwise follow the instructions in the Tramp's INSTALL file.

*used Cygwin bash to configure and compile the files. I don't use Cygwin's Emacs normally but it is convenient to have it for occasions like this.

*deleted the old tramp's el and elc files in my emacs/lisp/net for safety.

*restarted Emacs of course.

Do M-x tramp-version to make sure it is installed correctly. Now tramp works everywhere (dired, eshell, shell, etc).

A: Using eval-expression with (byte-compile-file ..) didn't work for me, but the following did:

*

*Open emacs as administrator (right click on emacs button on taskbar, right click on emacs icon in resulting popup, click 'Run as Administrator')

*Use Alt-X to do the compilation rather than eval-expression: M-x byte-compile-file: c:/Program Files/emacs-24.3/lisp/net/tramp-sh.el

*Enter tramp-cleanup-all-connections in original emacs window, then try opening your remote file again.

A: Merging the answer by @AlanThird and the comment by @uscjeremy, here is what worked for me (GNU Emacs 24.3.1 (i386-mingw-nt5.1.2600) of 2013-03-17 on MARVIN, Windows XP/SP3/32):

*

*Byte compile tramp-sh.el (adapt path accordingly):
(byte-compile-file "C:/Program Files (X86)/emacs/lisp/net/tramp-sh.el")

*Exit Emacs.

*Delete Tramp cache: ~/.emacs.d/tramp

*Start Emacs.
See also bug report #14030 on gnu.org.


text:
Q: Netbeans External Console error I'm trying to compile a simple hello world program in c++ using netbeans(in windows 10), however I'm getting the following error:
sh:/cygdrive/c/Users/myuser~1/AppData/local/Temp/dlight_-2128187438/8c9e2533/dlight5897405347450711582termexec.sh: No such file or directory
Press [Enter] to close terminal ...
If I use the inetrnal terminal I can actually run the program but when I change to external I recieve this error. I don't know if its a cygwin problem or a configuration problem. Thanks in advance for any help.

A: Quite an old question... just in case it is still active:
For me, it worked to switch the External Terminal Type (Project Properties → Run) from Default to Command Window.


text:
Q: Definition of a "n-"simplex I have a simple question about the definition of a simplex. In this paper by  Jonathan Huang he notes that every point on the simplex can be expresed as a linear combination
$$x=\sum\limits_{i=0}^n \alpha_i p_i$$
with $\sum\limits_{i=0}^n \alpha_i \leq 1$ and $\alpha_i\geq 0$. However,  on Hatcher's book (page 7) or on Wikipedia, for example, it is defined with $\sum\limits_{i=0}^n \alpha_i =1$.
What's the most accepted definition?


text:
Q: Variadic template class containing array of another template class I'm creating my own RDBMS to practice C++. I came up with a solution where each column can have a type and is a template. This is what a row looks like, but it doesn't work
template <typename... col_types>
struct row {
  row(std::tuple<std::function<bool(col_types)>, bool, col_types>...col_data){
    int i = 0;
    ([&]{
        columns[i] = std::make_unique<column_impl<decltype(std::get<2>(col_data))>>(std::get<0>(col_data), std::get<1>(col_data), std::get<2>(col_data));
        i++;
    }(), ...);
  }
  std::array<std::unique_ptr<column_impl<col_types>>, sizeof...(col_types)> columns;
};

And here is a column_impl
template <typename data_t>
struct column_impl {
  column_impl<data_t>() {}
  column_impl<data_t>(std::function<bool(data_t)> _constraint) : constraint(_constraint) {}
  column_impl<data_t>(std::function<bool(data_t)> _constraint, bool _is_nullable)
      : constraint(_constraint), is_nullable(_is_nullable) {}

  // This constructor requires to validate whether provided data
  // satisfies provided constraint. If constraint isn't satisfied
  // an exception gets thrown. It needs to be handled
  column_impl<data_t>(std::function<bool(data_t)> _constraint, bool _is_nullable, data_t _value)
      : constraint(_constraint), is_nullable(_is_nullable) {
    if (validate_data()) {
      value = _value;
    } else {
      throw std::invalid_argument("Provived data couldn't satisfy column's constraint");
    }
  }

  std::function<bool(data_t)> constraint = [](data_t) { return true; };
  bool is_nullable = false;
  data_t value;
  auto get_column_type_variant() { return std::variant<data_t>(); }

  bool validate_data() { return constraint(value); }

  template <typename T>
  bool validate_type(T) {
    return std::is_nothrow_convertible<T, data_t>();
  }
};

Any ideas how to create a container for columns inside of a row and create a constructor that unpacks tuples into a row? I can't get it working. I know this array is not supposed to work, but I have no idea how to write it better. And also I don't want a vector. I could write a polymorphic wrapper like
struct column{some_type_containing_column_impls column_obj;},
but I have no idea how to do it.
And how to properly unpack those tuples into column_impl obj?

A: Using only non-type template arguments can do the thing.
template<class T>
bool default_constraint(T) {
    return true;
}

template<class T, bool nullable = true, bool(constraint)(T) = default_constraint>
class column {
    T data;
    bool is_null;
public:
    column() : data(), is_null(true) { ///< T must be DefaultConstructable
        if (!validate())
            throw std::invalid_argument("Provided data couldn't satisfy column's constraint");
    }

    column(T data) : data(data), is_null(false) {
        if (!validate())
            throw std::invalid_argument("Provided data couldn't satisfy column's constraint");
    }

    bool validate() {
        return nullable || is_null || constraint(data);
    }

    T get() {
        return data;
    }
};

template<class... C>
struct row {
    std::tuple<C...> columns;

    row(C&&... c) : columns(std::forward<C>(c)...) {}

    template<int index>
    auto get() {
        return std::get<index>(columns).get();
    }
};

bool require_positive(int i) {
    return i >= 0;
}

int main() {
    typedef row<column<int>, column<float>, column<bool>> MyRow;
    MyRow r{1, 2.3f, true};

    using MyRow2 = row<column<int, false, require_positive>, column<float>>;
    MyRow2 r2{-1, 2.5}; ///< exception thrown
}

I know maybe you only want the "idea" of how to implement, but I just post the code here for clarity.


text:
Q: XML file "This page can't be displayed" in System32 I have made a Windows service that uses relative paths.
My windows Service opens a XML document, writes in it, and then saves it and it is in a loop.
When I forced a path to my xml file outside the System32 folder my service can have access to the xml document. However when I use relative paths, because I created a windows service the relative paths is in Windows/System32... So when I put my xml file in Windows/System32 it gives me the "This page can't be displayed' error.
I don't want to be forcing a path to the xml file every single time in my windows Service.
Thanks

A: The answer was quite simple.. I had to add the xml file to SysWow64 .
the exact answer actualy is this : The problem is with the system32 folder being the 64 version and the SysWoW64 folder being the 32 bit version.  When you try to open a file with a 32 bit application from the system32 folder, it gets redirected to the SysWow64 folder.  When you get the above error message, the file does not exist in the SysWOW64 folder.  To show this in action try opening the iexplore64, then opening the file.  Try the same thing with the 32 bit version of iexplore.
Copying the .xml files into the SYSWow64 directory should resolve your issue.
I did not think of this though.. I found the answer here : http://answers.microsoft.com/en-us/windows/forum/windows_7-files/xml-file-located-in-system32-folder-is-not/ae6db3af-ddaa-4e5e-ab63-0515cfe8ca57?page=2


text:
Q: Running chromedriver with selenium in a windows docker image for gitlab job I have SpecFlow tests in a c# project that I would like to get running in a GitLab job. we are doing it with a Windows Docker Image so I don't think we can uses Selenium's standalone chrome.
And I have tried running it with the arguments "--headless" and "--disable-gpu". the docker image should also have 2gb so adding --shm-size="2g" doesn't seem like it will help.
I'm reading that Windows Docker Images makes it difficult to support GUIs.
the error I see is:
System.AggregateException : One or more errors occurred.\r\n---- OpenQA.Selenium.WebDriverException : unknown error: Chrome failed to start: crashed.\n  (chrome not reachable)\n  (The process started from chrome location C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe is no longer running, so ChromeDriver is assuming that Chrome has crashed.)\r\n---- System.NullReferenceException : Object reference not set to an instance of an object.
Edit: the arguments suggested in this post do not work Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed
chromeOptions.AddArgument("--no-sandbox"); chromeOptions.AddArgument("--headless"); chromeOptions.AddArgument("--disable-dev-shm-usage");
The Chrome binary is also installed in the default location and it works locally so that isn't the issue.


text:
Q: How to set default autoincrement value for exponential function I want to set default auto increment value for exponential function. For example, I want mean arrival rate will be incremented from exponential(0.01s) to exponential(1s) with step 0.01?
Would anyone suggest how to code that in OMNet++?
Thank you.


text:
Q: Secret Santa problem I saw this problem on my exams and I just literally wrote down the formula for derangements and derived it but I am not sure if it is the case. This was the problem:
Problem: Let there be $n$ number of people and each one of them buys a gift and places them in a bag. Then each member chooses a gift out of the bag without seeing what they choose. What is the probability that none of the $n$ people chooses their own gift?
I was just wondering isnt this just a restatement of the derangement problem? Where the derangement formula is given by:
$$!n=n!\sum_{i=0}^n\frac{(-1)^i}{i!}$$


text:
Q: Exclude safari browser from Varnish caching Any suggestions how we can exclude devices that use Safari browser from using our Varnish caching? Excluding from varnish.vcl but what code to use?

A: Untested, but something like:
sub vcl_recv {
    if (req.http.User-Agent ~ "Safari") {
        return (pass);
    }
}


text:
Q: Kali Linux lost Ethernet connection My VirtualBox Kali suddenly lost wired connection.
this is what service network-manager status shows
NetworkManager[521]: <warn>  [1587842655.4122] ndisc[0x5568bd5c0200,"eth0"]: failure sending router solicitation: Operation not permitted (1)

and that's what i see when trying to ping 8.8.8.8 for example
ping: sendmsg: Operation not permitted

when i ping my local hosts - it's alright
what should i check or config?

A: It didn't ping becsuse u need to have the sudo privileges. I don't know u were using an account that is added to the sudo group if not you should add, or if you are type in sudo -s and enter your password and try to ping it should work.
When it was said failure sending router solicitation operation not permitted it means that you are not signed in as sudo and you don't have the permissions so do as i said up and it should work.


text:
Q: "completely" usage confusion As I know, verbs are followed by adverbs. So, which is true?
"She stands there completely expressionlessly"
Or "she stands there completely expressionless"
Though I think the second one is likely to be true, I can't find out a satisfactory explanation. Thanks in advance!

A: expressionless is modifing she, not stands, so it should be an adjective, not an adverb. It's equivalent to

She's standing there and is completely expressionless.

An example where you could use an adverb is:

She's standing there completely effortlessly.

The use of the adverb completely is irrelevant. An adverb can modify either an adjective or adverb. Both sentences would be the same with or without it.

A: Adverbs ordinarily precede the adjectives or adverbs they modify, so that is why in your examples "completely" precedes the adjective "expressionless" or the adverb "expressionlessly", which it modifies.  "Completely" can also modify a verb, in which case it can precede the verb it modifies: "They completely missed my point."  However, it can also follow the verb phrase: "They missed my point completely."  This particular type of adverb does not occur at the beginning of a sentence: *"Completely they missed my point."  Nor can it occur before an auxiliary verb: *"They completely have missed my point."  But many other adverbs can occur in the two latter positions.
The position of adverbs depends on what the adverbs modify, but unfortunately not in any simple way.
Both "expressionless" and "expressionlessly" are possible in your example, and "completely" can precede and modify either one, since adverbs can modify both adjectives and other adverbs.

A: "She stands there completely without expression."
Avoids the awkwardness of two -ly words in a row and ensures that "without expression" correctly modifies "stands".


text:
Q: What is client side in Object Oriented Programming? I have been hearing this word "Client Side" whenever I read book or while listening to my trainer when he teaches Object oriented programming concepts. What does exactly it mean? Can anybody help me providing an answer with example?
Answer would be appreciated.

A: "Client side" just means "from the perspective of the user of the object", i.e. the people who are going to be using the interface, as opposed to the implementors.

A: Client-server describes an application architecture in which the client requests an action or service from the provider of service, the server. For e.g. browser is the client of a web server. Now the client and server can be co-located within the same process or within the same computer or they can be running on different computers.

A: Client side vs. server side:
Client side programs/applications are typically "regular" computer programs, like a web browser, a game, a text editor, etc. In network programming, and that's more often, it refers to one of the peer computer programs that communicate with the server.
The counterpart of client side is server side; server applications are typically not directly utilized by the users, and due to this fact, some special considerations shall be made while making server(-side) applications. For example, there are typically some differences in programming languages, such as JavaScript and PHP.


text:
Q: How to justify adding and multiplying relations with big-O? I know that it's valid to add and multiply functions in Big O, although I haven't seen a proof why. As such I think this is a valid starting point. However, I have no idea how to progress and any help would be much appreciated.

A: By definition of big-$O$, we say that $f(x)\in O(g(x))$ if there is a $c,M$ such that for all $x\ge M$, $|f(x)|\le c|g(x)|$. In multiple variables this gets a little more complicated and/or ambiguous since the $M$ now becomes a bounding region instead of just a point, but luckily in this case we will have $|f(x,y)|\le c|g(x,y)|$ for all $x,y$ so we don't have to worry about $M$.
In the context of this problem, $f(x,y)=(x+y)^2$ and $g(x,y)=x^2+y^2$. Since both $f$ and $g$ are positive, we can actually drop the absolute value bars, so that $f(x,y)\in O(g(x,y))$ iff there is a $c$ such that $f(x,y)\le cg(x,y)$ for "large enough" $x,y$, say $x,y\ge M$ for some $M$ (which we can just set to $0$). Then we just need to show this algebraically:
$$f(x,y)=(x+y)^2\le (x+y)^2+(x-y)^2=2x^2+2y^2=2g(x,y),$$
so we are done.
It is very easy to forget the definition of big-$O$ and just apply heuristic rules to it (since that's what it was designed for), but in more complicated cases when the heuristics don't apply directly you should always remind yourself about the definition and how it applies so that you don't lead yourself astray.

A: if $a > b$,
then
$(a+b)^2
<(2a)^2
=4a^2
= O(a^2)
=O(a^2+b^2)
$.


text:
Q: Concordance and homology cobordism If two knots $K_1$ and $K_2$ in $S^3$ are smoothly concordant, then for any rational number $r$, the $r$-surgeries $S^3_r(K_1)$ and $S^3_r(K_2)$ are homology cobordant. Is the converse true? What if $r$ is assumed to be an integer? (Presumably the answer is no in both cases.)
Thanks to Yasui (http://arxiv.org/pdf/1505.02551.pdf), we now know that for any integer $n$, there exists a pair of non-concordant knots whose $n$-surgeries are homeomorphic. Likewise, Cochran-Franklin-Hedden-Horn's construction of non-concordant knots whose $0$-surgeries are homology cobordant can be modified for other integers $n$. However, neither of those constructions produces a single pair of non-concordant knots whose $n$-surgeries are homology cobordant for all $n$.
One way to construct a counterexample would be to exhibit a winding-number-$1$ knot $P$ in the solid torus that is not concordant in $S^1 \times D^2 \times I$ to the core circle, but which has the property that the knot $P(n)$ gotten by an $n$-framed unknotted embedding of $S^1 \times D^2$ in $S^3$ is slice for all $n$. The latter property shows that for any knot $K$, $n$-surgery on the satellite knot $P(K)$ is homology cobordant to $n$-surgery on $K$. It might then be possible to use $\tau$, $s$, or some other invariant to show that $K$ and $P(K)$ are not concordant.


text:
Q: PyAutoGUI not returning correct rgb values I am using python 3.9 with pyautogui==0.9.52 and I am trying to get the rgb value of a certain pixel on my screen. The results are something like, if I have the coordinate of a red pixel it returns the rgb value as (30,30,30).
If I use displayMousePosition(), I first have to run sys.platform = '_' to even get a rgb value in the first place, and even then it is still the wrong rgb value.
If I use pyautogui.pixel(x,y), it also returns the wrong rgb value. Does it have to do with incompatible versions maybe? Anybody know how to fix this?

A: I encountered a similar problem. I couldn't figure out why pyautogui returns (30, 30, 30) for all pixels but I found an alternative for pyautogui to get pixel color.
It is called win32gui pip install win32
def get_pixel_colour(i_x, i_y):
    import win32gui
    i_desktop_window_id = win32gui.GetDesktopWindow()
    i_desktop_window_dc = win32gui.GetWindowDC(i_desktop_window_id)
    long_colour = win32gui.GetPixel(i_desktop_window_dc, i_x, i_y)
    i_colour = int(long_colour)
    win32gui.ReleaseDC(i_desktop_window_id,i_desktop_window_dc)
    return (i_colour & 0xff), ((i_colour >> 8) & 0xff), ((i_colour >> 16) & 0xff)

Source: https://rosettacode.org/wiki/Color_of_a_screen_pixel#Python
It returns accurate results. Example: (0, 127, 237).


text:
Q: JQuery, check for arrow key pressed swith statement I've setup a keydown function and I want to do different things depending on whether the left, right, up or down arrow keys are pressed. That's working using a switch statement, but I'd also like to do something when ANY arrow key is pressed, but can't figure it out. My code:
$(document).keydown(function (e) {

var keyCode = e.keyCode || e.which,
    arrow = {left: 37, up: 38, right: 39, down: 40 },

switch (keyCode) {

    case arrow.left:
        // do something left
    break;

    case arrow.right:
        // do something right
    break;
}

});

I would really just like a line of code where I could check for whether any arrow key is pressed, but can't figure it out, so for example:
case arrow:
    // do something for any arrow keys
break;

Just using "case arrow doesn't seem to work. Could anyone help?
Thanks in advance!
EDIT: Thanks for your help everyone. Here's my final code, for anyone looking:
$(document).keydown(function (e) {

    if (e.which >= 37 && e.which <= 40) {
        $('p.key-notification').fadeOut('slow');
    }

    var keyCode = e.keyCode || e.which,
    arrow = {left: 37, up: 38, right: 39, down: 40 },

    switch (keyCode) {

        case arrow.left:
            // do something left
        break;

        case arrow.right:
            // do something right
        break;
    }

});

A: Why does that also have to be within your switch statement?
Make a separate if statement after your switch:
if (keyCode >= 37 && keyCode <= 40) {
    // run your code here
}

A: A single switch statement isn't able to match on multiple conditions - you can have fall-through, but that doesn't evaluate the expression on subsequent cases and won't achieve your desired effect. I'd do it like this:
if (keyCode >= 37 && keyCode <= 40) {
   // do any processing for _any_ arrow key here if it should happen
   // before individual arrow key processing

   switch (keyCode) {

      case arrow.left:
        // do something left
        break;

      case arrow.right:
        // do something right
        break;
   }

   // do any processing for _any_ arrow key here if it should happen
   // after individual key processing
}

Putting the switch inside the if statement saves evaluating it when none of the cases would've matched. (So obviously if you later wanted the switch to handle other keys you'd need to move it out of the if.)
If you needed to do something similar for keys that didn't have consecutive key codes then obviously you couldn't use a >= && <= condition so you'd do something like this:
if (keyCode === arrow.left || keyCode === arrow.right
   || keyCode === arrow.up || keyCode === arrow.down) {

A: This should work for you needs if I understand you correctly.
Another approach that adds to readability
var  arrow = { left: 37, up: 38, right: 39, down: 40 };

Any of them
switch (evt.keyCode) {
    case arrow.right:
    case arrow.left:
    case arrow.up:
    case arrow.down:
        // Do something
        break;
}

One of
switch (evt.keyCode) {
    case arrow.right:
        // Do right
        break;
    case arrow.left:
        // Do left
        break;
    case arrow.up:
        // Do up
        break;
    case arrow.down:
        // Do down
        break;
}


text:
Q: C# библиотеки для генерации Excel Нужна .net библиотека для генерации Excel файлов и СSV.
Да, ответов в интернете много в частности прекрасные ответы тут
Но датируются они в лучшем случае 2010 годом и многое могло измениться.
Так вот, какую библиотеку посоветуете на сейчас? И подводные камни, которые у вас возникали при генерации Excel файлов.
UPD
Нужна бессплатная библиотека.
UPD2 Нужна бессплатная библиотека с лицензией, совместимой с проприетарным ПО.

A: Для работы с Excel можно использовать сборку Microsoft.Office.Interop.Excel.dll
Пример работы с Excel - тут
Также для работы с файлами Excel можно использовать Open XML SDK 2.5 for Microsoft Office. Примеры можно найти на github Office Developer.
А csv файл - это обычный текстовый файл, который можно создать например, так:
File.AppendAllLines(@"c:\temp\test.csv", new[] { "1,2", "3,4" });

A: EPPlus - очень удобная библиотека для работы с Excel, которая основана на Open XML
Легка в освоении и спасает от использования интеропа.
Имеет так же множество примеров и хорошую документацию.

A: Можно использовать Aspose.Cells, но она платная. Наличие офиса не обязательно.


text:
Q: Nginx(HTTPS) upstream SpringBoot(http) after success logon chrome redirect to HTTP SpringBoot App started on 8080
Nginx incoming request on :443 proxy to :8080
start page is ok on https://site/ but
after login in SpringBoot chrome redirect to http://site/ (not to https://site/) WHY??? how to FIX

Request URL: https://site/login
Request Method: POST
Status Code: 302
Remote Address: 85.26.149.68:443
Referrer Policy: no-referrer-when-downgrade
RESPONSE HEADERS
HTTP/1.1 302
Server: nginx/1.14.0
Date: Mon, 25 Feb 2019 11:40:17 GMT
Content-Length: 0
Connection: keep-alive
Set-Cookie: JSESSIONID=5196D2D1A7A681BBF713BD3AF61F14FF; Path=/; HttpOnly
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Location: http://site/

And Chrome redirect on after login page page http://site/  WHY ?????
upstream spring_boot_srv {
    server localhost:8080 fail_timeout=0;
}
server {
   listen         80;
   server_name    site;
   return         301 https://$server_name$request_uri;
}
server {
    server_name site;
    listen 443;
    ssl on;
    ssl_session_timeout 5m;
    ssl_protocols SSLv2 SSLv3 TLSv1 TLSv1.1 TLSv1.2;

    ssl_certificate_key /media/some.key;
    ssl_certificate /media/some.crt;
    ssl_session_cache shared:SSL:10m;

    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host:$proxy_port;
        proxy_set_header X-Forwarded-Proto https;
        proxy_redirect off;
        proxy_connect_timeout      240;
        proxy_send_timeout         240;
        proxy_read_timeout         240;
        proxy_pass http://spring_boot_srv;
    }
 }

A: Add below entry in your application.properties
server.tomcat.remote_ip_header=x-forwarded-for
server.tomcat.protocol_header=x-forwarded-proto

For more info


text:
Q: MongoMapper save not working No idea why this is not working. It's the first time I am working with Mongo, but from all the docs I have read, this should work? Anyone have any idea what I am missing?
require 'rubygems'
require 'sinatra/base'
require 'mongo_mapper'

  mongo_server = '127.0.0.1'
  mongo_database = 'inone'

  MongoMapper.connection = Mongo::Connection.new(mongo_server)
  MongoMapper.database = mongo_database

  # DB model
  class URLstore
    include MongoMapper::Document

    key :url_key, String
    key :url, String
  end

class URLnip < Sinatra::Base
   get '/testmongo' do
    nipurl = URLstore.new(:url_key => "abc", :url => "www.google.com")
    nipurl.save
  end
end

Opening the Mongo terminal I can see the DB get's created
> show dbs
inone   0.203125GB

but doing this brings back no results at all
> db.inone.find()
>

or
> db.inone.find({url : 'www.google.com'})
>

same thing nothing.

A: Shouldn't that be db.urlstore.find()? Or however MongoMapper changes the case. What does show collections in a Mongo shell say after you select the right database?


text:
Q: How to implement a word counter in Rails? I'm wanting to implement a real-time word counter in a form. So as a user types into the box, a line below the box updates with the correct number of words.
Here is the relevant form code (my views are .html.haml):
= f.semantic_fields_for :student_biography do |fb|
  = fb.inputs :name => "About" do
    = fb.input :short_statement, :label => 'Describe yourself! (25 words) ' , :input_html => {:id => "bio_prof_stmt" }

So below this description box, I'd like to count the number of words and display an 'out of 25' notice.
I'm assuming that this is just some javascript I need to add, but I don't know where to proceed from here.
Rails 3.2.11, Ruby 1.9.7
Thanks!

A: It shouldn't be too difficult, you would need a div that had its content updated on the keyup event for the input box:
This is a little bit from memory and may need some adjustment but it should get you on the right path:
= fb.input :short_statement, :label => 'Describe yourself! (25 words) ' , :input_html => {:id => "bio_prof_stmt" }, :onkeyup => "update_word_count(this);"

I think this is the right haml syntax, please correct me if not:
#word-count-container

The intended html:

Javascript:

Alternative UJS approach (remove the onkeyup tag from the input):

A: This seems like something that you have to validate on the server side as well as the client side. So don't forget to do that.
validates :short_statement, length: { maximum: 25 }

If you want strict word counting you can use the Words Counted gem. Disclaimer I wrote it.


text:
Q: Find overlapping timestamps using pandas I have a dataframe containing start times, end times and transaction_ids like so:
    tid       starttime        endtime
0   0.0     1537204247.00   1537204309.00
1   1.0     1537204248.00   1537204309.00
2   21.0    1537207170.00   1537207196.00

I need to find overlapping transactions. So far, the most optimized code I've been able to produce is the following:
p['overlap'] = False # This is my original dataframe

def compute_overlaps(df):
    for i, row_curr in df.iterrows():
        if( p.loc[row_curr['ix']]['overlap'] != True ):
            overlap_indexes = df[(row_curr['ix'] != df['ix']) & (row_curr['starttime'] < df['endtime']) & (df['starttime'] < row_curr['endtime'])].index
            p['overlap'].loc[row_curr['ix']] = True
            p['overlap'].loc[overlap_indexes] = True

<p_grouped_by_something>.apply(compute_overlaps)

Output:
    tid       starttime        endtime     overlap
0   0.0     1537204247.00   1537204309.00   True
1   1.0     1537204248.00   1537204309.00   True
2   21.0    1537207170.00   1537207196.00   False

Note that for each transaction, I merely need to determine if it overlaps with at most one other transaction. If one is found, I don't need to check all other transactions; I can stop there and mark it as overlapping.
Initially, I had a nested for loop using iterrows that was abominably slow. I was then able to vectorize the inner loop, but the outer loop remains. Is there any way to vectorize the overall computation to make it run faster?

A: You can using numpy boradcast
s1=df.starttime.values
s2=df.endtime.values
sum(np.minimum(s2[:,None],s2)-np.maximum(s1[:,None],s1)>0)>1
Out[36]: array([ True,  True, False])

Explanation :
1st : over lap for range
(x1,y1) with (x2,y2)
min(y2,y1)-max(x1,x2)>0 then two ranges have overlap
2nd : why it need great than 2 , since I using numpy braod cast , so the diagonal always represented itself comparison . Then we need greater two .
Update :
Assuming you have df and split df1 ....dfn (look at np.split)
s1=df.starttime.values
s2=df.endtime.values
l=[df1,df2,df3,df4,df5...]
n=[]
for  x in l:
       n.append(sum(np.minimum(s2[:,None],x.values)-np.maximum(s1[:,None],x.values)>0)>1)


text:
Q: How to get AJAX to load page at top of div My site contains a div where different pages are loaded using ajax.  On a button click, a new page can be loaded and the pages always appear in that div.
The problem is if I go to a new page and scroll down without scrolling back to the top of that page, new pages will load at the same position below the top of the page, not at the top of the page.  I want to force all pages to load at the top.
Here are the relevant page elements:
The div (where the page content goes):

MTX

The button:

<button class="button_01" id="btn07" onclick="HideDropdown(); ShowAjax(7);">Page 7</button>

The AJAX code:

The most important line is:
$( "#C2" ).hide().load( filename ).fadeIn(500);

At the top of each page I have:

I want to open each page at the top of the page (at "bkmk00).  I saw a post that said I could add an id name and it would load the page at that ID:
$( "#C2" ).hide().load( filename "bkmk00" ).fadeIn(500);

but with that, it doesn't load anything.  Instead, the Firefox 67 dev console says "SyntaxError: missing ) after argument list" for this ajax function call, and it points to character 37 which is right after filename.  That looks like I can't add the second parameter "bkmk00."
My question is, how can I get the page to load at "bkmk00" at the top of the page to be loaded?

A:

You are close but not quite, load function has 2 parameters, input file and a function callback:
var filename = "page_" + type + ".htm"
$( "#C2" ).hide()
$( "#bkmk00" ).load(filename, function(){
    $( "#bkmk00" ).fadeIn(500);
});


text:
Q: Grab Handles by Three-Finger Tap not working after upgrade to 12.04 I recently upgrade my Ubuntu installation from 11.10 to 12.04.
Before the upgrade I was able to use three-finger tapping to bring up the grab-handles. Unfortunately, after the upgrade, that functionality is broken, since I cannot use the three-finger tap anymore.
Because the touchpad settings in ubuntu are somewhat limited, I don't really know what to do right now.
I hope someone can help me with that. I'll be glad to provide more info if needed.

Edit: The issue is not the gesture, but the binding of grab handles.
In CCSM, I cannot assign the middle-click to the grab-handle toggle.

A: This is not a real answer but a workaround. Here is what i did:

*

*reenable middle-click with synaptiks from software center

*assign a keyboard-shortcut to grab handles with ccsm

Kind of disappointing though, since it worked out of the box on 11.10


text:
Q: Keep default beamer bibliography but change citation style I would like to change the citation style to (author, year) while keeping the default bibliography style in beamer.
All solutions I found include using natbib, which works well but changes the appearance of the bibliography.
\usepackage[round]{natbib}
\bibliographystyle{apalike}


text:
Q: 'FacebookCore' does not specify a Swift version and none of the targets ('AppName') integrating it have the 'SWIFT_VERSION' attribute set i am getting this error when i trying to install pod.
Error:-
```['FacebookCore' does not specify a Swift version and none of the targets ('AppName') integrating it have the SWIFT_VERSION attribute set. Please contact the author or set the SWIFT_VERSION attribute in at least one of the targets that integrate this pod.

*

*'FacebookShare' does not specify a Swift version and none of the targets ('AppName') integrating it have the SWIFT_VERSION attribute set. Please contact the author or set the SWIFT_VERSION attribute in at least one of the targets that integrate this pod.]```

Here is my pod file detail:-
   use_frameworks!

  # Pods for AppName
  pod 'AppsFlyerFramework'
  pod 'FacebookShare'
  pod 'Firebase/Analytics'
  pod 'Firebase/Crashlytics'
end

using xcode 11.3.1 and not using any swift class

A: i tried to add Swift class in project and added "AppName-Bridging-Header.h". Then it's working fine.


text:
Q: Comparar el primer caracter del texto Tengo un código, que si a una función se le da como parámetro la string:
#elemento

Usará un document.getElementById();
y si recibe la string de la forma:
.elemento

Usará un getElementsByClassName();
Pero el problema es, ¿qué hago cuando envien "#."? Sería conveniente que se tomara en cuenta solamente el primer caracter, entonces pensé en hacer:
if(parametro.substr(0,1) == "#" ) { //Hacer algo }

Y funcionaría, pero ¿cómo podría hacerlo con una expresión regular?

A: Como comenté, jamás usaría regex para algo que se puede solucionar sencillo:
if (parametro[0] == '#') {
    // ...
}

Ni para reinventar una función que ya existe: document.querySelector(parametro).
Pero, como te interesa para aprender...

En regex, ^ es una aserción que coincide con el inicio del string (o de la línea si se usa un modificador). Como toda aserción, no coincide con un caracter, sino con una posición que cumple la condición.
Así, podemos utilizar ^ para garantizar que coincida con el inicio y luego con el caracter deseado. La expresión quedaría:
/^#/

*

*Un # al inicio del texto.

Código:

function esId(parametro) {
    return /^#/.test(parametro);
}

//Pruebas
console.log(esId("#abc"));  //true
console.log(esId(".#def")); //false
console.log(esId("#.ghi")); //true

Más información en Expresiones Regulares (MDN).

A: El objetivo aparente es detectar el primer caracter, pero yo veo un problema de fondo, y es detectar los nombres de las variables.
Para esto, lo que hago es, además de mirar el primer caracter, mirar que el segundo no sea un número, y además aceptar otros caracteres como guión bajo y signo pesos.
Estos caracteres son los más comunes, pero al momento de probar, puede aceptar hasta carácteres unicode. No voy a entrar en eso ya que es complicado, pero dejo una solución aproximada.
Una variable no puede empezar con un número, y lo siguiente puede ser un número, letras, o lo que sea, siempre que no se tope con los caracteres especiales del lenguaje.

*

*Para que no sea un número el primer caracter de la variable: [^0-9]

*Para que sea una letra: [a-z]

*Un número: \d

*Un punto: \.... Aquí hay que tener cuidado, porque el punto en algunos lenguajes es como un comodín, es decir, acepta cualquier cosa.

*Almohadilla (para este caracter no hay truco): #.

var nombre_variable="[^0-9][a-z\\d_$]{0,}"
new RegExp(nombre_variable,"i")
var almohadilla=new RegExp("^#"+nombre_variable+"$")
var propiedad=new RegExp("^\."+nombre_variable+"$")
console.log(almohadilla)
console.log(propiedad)

var pruebas=[
  "variable_8", "3_a"
]
for(var i in pruebas){

  console.log( "."+pruebas[i]+" "+
    propiedad.test("."+pruebas[i])
  )
  console.log( "#"+pruebas[i]+" "+
    propiedad.test("#"+pruebas[i])
  )
}

A: Por lo que entiendo necesitas validar que no ingresen "#.", si es así con la siguiente expresión regular puedes validar y ejecutar alguna condición de error.
var str="#.element";
var a = str.match(/\#\./);
if(a) {
    // condición de error
    alert(a);
}


text:
Q: BroadcastReceiver not receiving any activity recognition broadcast My main activity registering broadcast for Activity Recognition but and don't see any calls to Broadcast Receiver's onReceive method. I am not able to figure out why it's not working as expected.
I am testing on Real device with android 11 (API 30) with all required permission
Main Activity Register Broadcast
List<ActivityTransition> transitions = new ArrayList<>();
        PendingIntent activityPendingIntent;

        // Action fired when transitions are triggered.
        final String TRANSITIONS_RECEIVER_ACTION = "com.example.TRANSITIONS_RECEIVER_ACTION";

        transitions.add(
                new ActivityTransition.Builder()
                        .setActivityType(DetectedActivity.IN_VEHICLE)
                        .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
                        .build());
        transitions.add(
                new ActivityTransition.Builder()
                        .setActivityType(DetectedActivity.IN_VEHICLE)
                        .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
                        .build());
        transitions.add(
                new ActivityTransition.Builder()
                        .setActivityType(DetectedActivity.WALKING)
                        .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
                        .build());
        transitions.add(
                new ActivityTransition.Builder()
                        .setActivityType(DetectedActivity.WALKING)
                        .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
                        .build());
        transitions.add(
                new ActivityTransition.Builder()
                        .setActivityType(DetectedActivity.STILL)
                        .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
                        .build());
        transitions.add(
                new ActivityTransition.Builder()
                        .setActivityType(DetectedActivity.STILL)
                        .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
                        .build());

        transitions.add(
                new ActivityTransition.Builder()
                        .setActivityType(DetectedActivity.ON_BICYCLE)
                        .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)

                        .build());
        transitions.add(
                new ActivityTransition.Builder()
                        .setActivityType(DetectedActivity.ON_BICYCLE)
                        .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
                        .build());

        transitions.add(
                new ActivityTransition.Builder()
                        .setActivityType(DetectedActivity.RUNNING)
                        .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
                        .build());

        transitions.add(
                new ActivityTransition.Builder()
                        .setActivityType(DetectedActivity.RUNNING)
                        .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
                        .build());

        ActivityTransitionRequest request = new ActivityTransitionRequest(transitions);
        Intent mintent = new Intent(this, ActivityRecognitionBroadcastReceiver.class);
        mintent.setAction(TRANSITIONS_RECEIVER_ACTION);

        activityPendingIntent = PendingIntent.getBroadcast(this,
                0,
                mintent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        Task<Void> task = ActivityRecognition.getClient(this)
                .requestActivityTransitionUpdates(request, activityPendingIntent);

        task.addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(@NonNull Void command) {
                checkFirstimeActivityRecognition = false;
                Log.i(TAG, "Successfully added transition updates listener");
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.e(TAG,"Transitions could not be unregistered: " + e);
            }
        });
        ActivityRecognitionBroadcastReceiver broadcastReceiver = new ActivityRecognitionBroadcastReceiver();
        registerReceiver(broadcastReceiver, new IntentFilter(TRANSITIONS_RECEIVER_ACTION));
        Log.d(TAG, "setupActivityRecognition: Register Broadcast receiver ");

BroadcastReceiver
public class ActivityRecognitionBroadcastReceiver extends BroadcastReceiver {
    public static final String TAG = "Broadcast Recognition";

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "On Handle Intent");
        Log.d(TAG, "onReceive(): " + intent);
        Toast.makeText(MyApplication.getmContext(), intent.getAction(), Toast.LENGTH_SHORT).show();

    }

Manifest
<application ...

<receiver
            android:name=".Location_system.ActivityRecognitionBroadcastReceiver"
            android:permission="com.google.android.gms.permission.ACTIVITY_RECOGNITION">
            <intent-filter>
                <action android:name="com.example.TRANSITIONS_RECEIVER_ACTION"/>
            </intent-filter>
        </receiver>

</application>

A: I think the issue is you haven't set the receiver as exported.
Try adding android:exported="true" and check if it works. Also, make sure all permissions are declared and granted:
<uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION"/>
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />

A: At some point it seems that the following intent for an explicit class stopped working (or maybe never worked?):
Intent mintent = new Intent(this, ActivityRecognitionBroadcastReceiver.class);

Instead, I created the intent by passing in the action in the intent constructor, as follows:
Intent mintent = new Intent(TRANSITIONS_RECEIVER_ACTION);

...and then I started to get callbacks successfully from the Activity Transition API.
Note that this approach is used in the latest codelab as well:
https://github.com/googlecodelabs/activity_transitionapi-codelab/blob/master/complete/src/main/java/com/google/example/android/basicactivityrecognitiontransitionsample/MainActivity.java#L134


text:
Q: How to put configuration information inside the executable? If we want to store critical information, like passwords and server addresses, inside the executable file generated by the Delphi compiler, how can we do that, without knowing the final executable size and binary structure, like at the end of the file for example?
Side note:
The text to be stored is already encrypted; and in some computers the windows don't give access to write in the registry, specially when the user is not administrator, and there are hacks to monitor registry changes and the smart user can find the new windows registry entry.
Comment
Why this question was down voted? This is achievable! Doesn't meter if not interesting for most people.
I think about the bios and other firmware upgradeable, like satelite tv signal decoders that update themselves. How is that possible?

A: You can use an .rc file to put your data into a custom resource inside the final .exe file.  You can then access that resource at run-time, such as with a TResourceStream, and decrypt and use its content as needed.  However, you cannot write new data into the resource while the .exe is running, as the file is locked by the OS.  If you need to write new settings, and do not have write access to the Registry, you will have to use a separate file instead.  Windows has special folders set aside that users have write access to within their user profiles.

A: Create a string table resource is one way.
Create a text file. say secretstuff.rc (has to have .rc extension)
with something like this in it.
STRINGTABLE
{
  1,"This is my encrypted password in say Base64"
}

Compile it to a .res file with BRCC32.
Include it in the relevant code with a compiler directive
{$R secretstuff.res}

After that you access with TResourceStream.
If you want to manage it a bit better might be wise to stuff them in a dll instead of an exe, then you can update things by delivering a new version of the dll.
There's an example with a it more detail, another purpose but same principle here


text:
Q: activating "authorization" causes CSS stop working! how solve it? when i use:
<deny users="?"/>

in "authorization" tags, CSS stop working for unauthorized visitors. how can i define a exception for css files. i want them to apply to all visitors.
this is my web.config file:
<?xml version="1.0"?>
<configuration>
    <system.web>
        <authorization>
            <deny users="?"/>
        </authorization>
        <roleManager enabled="true"/>
        <authentication mode="Forms">
            <forms loginUrl="welcome.aspx" defaultUrl="Default.aspx"/>
        </authentication>
        <compilation debug="true" targetFramework="4.0"/>
</system.web>
</configuration>

i did edit my web.config to this:
<?xml version="1.0"?>
<configuration>
    <system.web>
        <authorization>
            <deny users="?"/>
        </authorization>
        <roleManager enabled="true"/>
        <authentication mode="Forms">
            <forms loginUrl="welcome.aspx" defaultUrl="Default.aspx"/>
        </authentication>
        <compilation debug="true" targetFramework="4.0"/>
       </system.web>

       <location path="styles">
         <system.web>
          <authorization>
            <allow users="*"/>
          </authorization>
         </system.web>
      </location>

     <location path="styles/welcome.css">
      <system.web>
       <authorization>
        <allow users="*"/>
       </authorization>
      </system.web>
    </location>
</configuration>

and it's working.
thank you.

A: Add the location of your CSS to your web.config. You can put it completely at the end, just before the </configuration>
<location path="css">
    <system.web>
      <authorization>
        <allow users="*"/>
      </authorization>
    </system.web>
   </location>

Of course, change "css" to the real folder of your css file... It is the easiest to put it in a separate folder where all items are public. Just like your images etc.

A: You are probably blocking access to the folder where you store css files.
Try to allow everybody to access your css-folder even if they are not autorized.

A: You can use the Location element to define which part of your site the configuration applies to:
(from MSDN)
<location allowOverride="True|False" path="path" />


text:
Q: Enable/Disable button using checkboxes I need to enable/disable button if both checkboxes are checked. I want to do in knockout.js. I am still a beginner. I have found an example enable/disable button using checkbox but that is doing for 1 checkbox. In my scenario, i have two checkboxes and they both should be checked to enable the button. If any of the checkbox is not checked then the button should be disabled.
<input type="checkbox" data-bind="checked: myBoolean" />
<button data-bind="enable: myBoolean">My Button</button>

ko.applyBindings({ myBoolean: ko.observable(true) });

Any help or suggestion would be appreciated.
Thanks in advance

A: You could

*

*add another observable for the other checkbox

*add a computed observable for the button, which returns true only when both checkboxes are checked (observables are true)

var test = {
  myBoolean1: ko.observable(false),
  myBoolean2: ko.observable(false)
};
test.myComputed = ko.computed(function() { return test.myBoolean1() && test.myBoolean2() });

ko.applyBindings(test);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<input type="checkbox" data-bind="checked: myBoolean1" />
<input type="checkbox" data-bind="checked: myBoolean2" />
<button data-bind="enable: myComputed">My Button</button>

A: You can do this using CSS only. Unless you need to support IE10 or lower.

button {
  cursor: not-allowed;
  pointer-events: none;
  color: grey;
  background-color: white;
}

#firstCheckbox:checked+#secondCheckbox:checked+button {
  color: black;
  cursor: pointer;
  pointer-events: auto;
}
<input type="checkbox" id="firstCheckbox">
<input type="checkbox" id="secondCheckbox">
<button>Click me</button>


text:
Q: Azure Service Bus Feature I have a simple question about azure Bus, i am trying to use it with azure functions and i intend to reduce the cost of the azure function due to polling of the azure service bus for messages is there a way to have the message sent out from azure service bus to an endpoint the moment the message is received. without using event grid ?

A: Yes! As per Sead Feldman, it is true. On your behalf, it is polled by the Service Bus when a function is triggered, it gives if messages available.
AFAIK, because of the underlying service architecture, the ServiceBusTrigger is on a polling basis.
As per this MSFT Documentation, the characteristics of a Azure Service Bus is:

is a reliable asynchronous message delivery (enterprise messaging as a service) that requires polling

The same issue is registered in the GitHub that Polling costs is high with Service Bus Queue triggers even in zero activity of the Azure Functions.
From that GitHub discussion,  switching to Azure Event Grid Trigger is the good option because Azure Service Bus integrates with Azure Event Grid as Service Bus will send events to Azure EventGrid when there are new messages which would prevent you from polling.


text:
Q: How to get booking list with matching with users of any company in laravel We have company and their users. We want to  get all booking list with users of a company.
Please suggest how can we solve this issue.
Let's something like this
$booking=Booking::with('users')->where()

In where like
users.company_id=$company_id

A: I think you need this:
$company_id = 1;
$booking=Booking::with('users' => function ($query) use ($company_id) {
    $query->where('company_id', $company_id);
}])->get();

It's in Documentation, the name of this is "Constraining Eager Loads"


text:
Q: GO: Exceeds 10000-thread on simple tcp server? I need to write a tcp server which can handle more than 500k connections.
I wrote a simple server on golang, but when connections more than 10k, the server crashed with the error message "runtime: program exceeds 10000-thread limit fatal error: thread exhaustion".
Server runs in last linux build. That go can use epoll for tcp connection, to make it async and use few fd. So why does the server exceed the thread limit?!
My simple server:
package main
import (
    "strconv"
    "net"
    "log"
    "time"
    "bufio"
    "io"
)

type Handler struct {
    conn   net.Conn
    closed chan bool
}

func (h *Handler) Listen() { // listen connection for incomming data
    defer h.conn.Close()
    bf := bufio.NewReader(h.conn)
    for {
        line, _, err := bf.ReadLine()
        if err != nil {
            if err == io.EOF {
                log.Println("End connection")
            }
            h.closed <- true // send to dispatcher, that connection is closed
            return
        }

        // ... some business logic with data
    }
}

type Dispatcher struct {
    handlers map[string]*Handler `map[ip]*Handler`
}

func (d *Dispatcher) AddHandler(conn net.Conn) {
    addr := conn.RemoteAddr().String()
    handler := &Handler{conn, make(chan bool, 1)}
    d.handlers[addr] = handler

    go handler.Listen()

    <-handler.closed // when connection closed, remove handler from handlers
    delete(d.handlers, addr)
}

func (d *Dispatcher) ListenHandlers(port int) {
    sport := strconv.Itoa(port)

    ln, err := net.Listen("tcp", ":" + sport)
    if err != nil {
        log.Println(err)
        return
    }

    defer ln.Close()

    for {
        conn, err := ln.Accept() // accept connection
        if err != nil {
            log.Println(err)
            continue
        }

        tcpconn := conn.(*net.TCPConn)
        tcpconn.SetKeepAlive(true)
        tcpconn.SetKeepAlivePeriod(10 * time.Second)

        go d.AddHandler(conn)
    }
}

func main() {
    dispatcher := &Dispatcher{make(map[string]*Handler)}
    dispatcher.ListenHandlers(3000)
}

Update 11.10.2015
The problem was that https://github.com/felixge/tcpkeepalive library. Please do not use it :)

A: The problem was that https://github.com/felixge/tcpkeepalive library.
This library get socket file descriptor (fd), copy then and worked with new fd, which running in blocked mode. Therefore, go created new thread on every connect. Go don't kill created thread (because this is native golang behavior), and after some times go failed with "Exceeds 10000-thread". That's it !
Please do not use it :)


text:
Q: querying WHERE condition to character length? I have a database with a large number of words but i want to select only those records where the character length is equal to a given number (in example case 3):
$query = ("SELECT * FROM $db WHERE conditions AND length = 3");

But this does not work... can someone show me the correct query?

A: I think you want this:
select *
from dbo.table
where DATALENGTH(column_name) = 3

A: Sorry, I wasn't sure which SQL platform you're talking about:
In MySQL:
$query = ("SELECT * FROM $db WHERE conditions AND LENGTH(col_name) = 3");

in MSSQL
$query = ("SELECT * FROM $db WHERE conditions AND LEN(col_name) = 3");

The LENGTH() (MySQL) or LEN() (MSSQL) function will return the length of a string in a column that you can use as a condition in your WHERE clause.
Edit
I know this is really old but thought I'd expand my answer because, as Paulo Bueno rightly pointed out, you're most likely wanting the number of characters as opposed to the number of bytes. Thanks Paulo.
So, for MySQL there's the CHAR_LENGTH(). The following example highlights the difference between LENGTH() an CHAR_LENGTH():
CREATE TABLE words (
    word VARCHAR(100)
) ENGINE INNODB DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_unicode_ci;

INSERT INTO words(word) VALUES('快樂'), ('happy'), ('hayır');

SELECT word, LENGTH(word) as num_bytes, CHAR_LENGTH(word) AS num_characters FROM words;

+--------+-----------+----------------+
| word   | num_bytes | num_characters |
+--------+-----------+----------------+
| 快樂    |         6 |              2 |
| happy  |         5 |              5 |
| hayır  |         6 |              5 |
+--------+-----------+----------------+

Be careful if you're dealing with multi-byte characters.

A: SELECT *
   FROM   my_table
   WHERE  substr(my_field,1,5) = "abcde";


text:
Q: Include dll's in WiX msi base Installer I am currently making an Outlook addin in Visual Studio 2012,
i create an Installer for my project, but in order for my addin to work on my clients computers i also need to add the SharePoint Foundation (http://www.microsoft.com/en-us/download/details.aspx?id=21786) dll's,
but when I try to add them from my C:\Windows\assembly folder to the WiX msi base installer Project\References - (by right clicking and pressing add Reference), I get the following error "A reference to [filepath] could not be added. Please make sure that the file is accessible, and that it is a valid WiX reference."
Do you know what I can do ?
thanks a lot for your help!

A: You need to add the files to Product.wxs - see http://wix.sourceforge.net/manual-wix3/wix_learning.htm . You only add .wixlib and other projects via references.

A: Another approach would be to use a WiX 3.7 Bootstrapper project. The bootstrapper engine is often called "Burn" so you might see that in discussions.
A bootstrapper project allows you to install dependencies using their own installers, such as the "SharePoint Foundation 2010 Client Object Model Redistributable" you linked to. A nice example of a bootstrapper is the WiX 3.7 installer itself but most projects can be much simpler.
Installing dependencies using vendor provided installers has the advantage of avoiding having to re-implement any necessary logic yourself and allows them to managed and upgraded by the user.


text:
Q: Do not "line break" the arrow when using btn-group How to do not allow the arrow to go to another line? This will happens if the screen did not have enough space, see the image:

JSFIDDLE
CODE:

            COLUMN 1
            COLUMN 2
            COLUMN 3
            COLUMN 4

                    Descrition of the item

Option 1

            Some info here
            Some more here
            And here too

                    Descrition of the i asd adasdasdasdasdtem

Option 1

            Some info here
            Some more here
            And here too

                    No item

Option 0

            Some info here again
            yay more info here too
            ok, enough info now, that is enough

Tried some white-space: nowrap; but could not get the desired result. Any help will be great. The arrow must be in the right side, always.

A: Instead of floating the carets right, float the text left.
Description...

Demo

A: span.pull-right floats the i.fa-caret-down to the right after your "Description of the item", which means it's placed on the next line. Try putting the float before the description. For example:

  Description of the item

Sample, fixing the first caret.

A: Setting the white-space: nowrap property will not effect the dropdown icon as it's in a different flow due to the float: right; applied to it by the class .pull-right.
What you're describing sounds as though you want to set a position: absolute against the icon. This does fix the issue of the icon not being effected by the text, but it raises a further question of, how do you want to resolve too much text in a button which isn't sufficiently big?
As far as I can see, the only way to resolve this would be to also apply an overflow: hidden property to the buttons, to force the spacing to the right where the icon sits to be empty, and to apply an ellipsis on the text if any overflow does occur. You can see the combination of these selectors in this JSFiddle, I have forced the buttons to be smaller purely to demonstrate how this would work when they are forced to consume a space smaller that you would otherwise like:
.btn {
    white-space: no-wrap;
    overflow: hidden;
    text-overflow: ellipsis;
    padding-right: 10px;
}

.fixed-right {
    position: absolute;
    right: 5px;
}


text:
Q: Complexity of finding the median using 2 heaps A way of finding the median of a given set of n numbers is to distribute them among 2 heaps. 1 is a max-heap containing the lower n/2 (ceil(n/2)) numbers and a min-heap containing the rest. If maintained in this way the median is the max of the first heap (along with the min of the second heap if n is even). Here's my c++ code that does this:
priority_queue<int, vector<int> > left;
priority_queue<int,vector<int>, greater<int> > right;
cin>>n; //n= number of items
for (int i=0;i<n;i++) {
    cin>>a;
    if (left.empty())
        left.push(a);
    else if (left.size()<=right.size()) {
            if (a<=right.top())
                left.push(a);
            else {
                left.push(right.top());
                right.pop();
                right.push(a);
            }
    }
    else {
        if (a>=left.top())
            right.push(a);
        else {
            right.push(left.top());
            left.pop();
            left.push(a);
        }
    }
}

We know that the heapify operation has linear complexity . Does this mean that if we insert numbers one by one into the two heaps as in the above code, we are finding the median in linear time?

A: Linear time heapify is for the cost of building a heap from an unsorted array as a batch operation, not for building a heap by inserting values one at a time.
Consider a min heap where you are inserting a stream of values in increasing order. The value at the top of the heap is the smallest, so each value trickles all the way down to the bottom of the heap. Consider just the last half of the values inserted. At this time the heap will have very nearly its full height, which is log(n), so each value trickles down log(n) slots, and the cost of inserting n/2 values is O(n log(n))
If I present a stream of values in increasing order to your median finding algorithm one of the things it has to do is build a min heap from a stream of values in increasing order so the cost of the median finding is O(n log(n)). In, fact the max heap is going to be doing a lot of deletes as well as insertions, but this is just a constant factor on top so I think the overall complexity is still O(n log(n))

A: *

*When there is one element, the complexity of the step is Log 1 because of a single element being in a single heap.

*When there are two elements, the complexity of the step is Log 1 as we have one element in each heap.

*When there are four elements, the complexity of the step is Log 2 as we have two elements in each heap.
So, when there are n elements, the complexity is Log n as we have n/2 elements in each heap and

*

*adding an element; as well as,

*removing element from one heap and adding it to another;

takes O(Log n/2) = O(Log n) time.

So for keeping track of median of n elements essentially is done by performing:

2 * ( Log 1 + Log 2 + Log 3 + ... + Log n/2 ) steps.

The factor of 2 comes from performing the same step in 2 heaps.

The above summation can be handled in two ways. One way gives a tighter bound but it is encountered less frequently in general. Here it goes:

*

*Log a + Log b = Log a*b (By property of logarithms)

*So, the summation is actually Log ((n/2)!) = O(Log n!).

The second way is:

*

*Each of the values Log 1, Log 2, ... Log n/2 is less than or equal to Log n/2

*As there are a total n/2 terms, the summation is less than (n/2) * Log (n/2)

*This implies the function is upper bound by (n/2) * Log (n/2)

*Or, the complexity is O(n * Log n).

The second bound is looser but more well known.

A: This is a great question, especially since you can find the median of a list of numbers in O(N) time using Quickselect.
But the dual priority-queue approach gives you O(N log N) unfortunately.
Riffing in binary heap wiki article here, heapify is a bottom-up operation. You have all the data in hand and this allows you to be cunning and reduce the number of swaps/comparisons to O(N). You can build an optimal structure from the get-go.
Adding elements from the top, one at a time, as you are doing here, requires reorganizing every time. That's expensive so the whole operation ends up being O(N log N).