text:
Q: WinError 10049 when trying to connect to receive messages from multicast IP I have a bunch of devices that send messages using mDNS. i want to receive those messages. but the code always fails with OSError: [WinError 10049] The requested address is not valid in its context
import struct
import socket

MCAST_GRP = '224.0.0.251'
MCAST_PORT = 5353
IS_ALL_GROUPS = False

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if IS_ALL_GROUPS:
    # on this port, receives ALL multicast groups
    sock.bind(('', MCAST_PORT))
else:
    # on this port, listen ONLY to MCAST_GRP
    sock.bind((MCAST_GRP, MCAST_PORT))

mreq = struct.pack("4sL", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

while endLoop == 0:
# For Python 3, change next line to "print(sock.recv(10240))"
    data, addr = sock.recvfrom(10240)
    print(f"Received message from {addr}:\n {data}")

I tried closing every application that uses the port, but that didn't help.

A: The IP and port you bind to is local, not external. You cannot bind to a multicast because that would be binding to multiple ips, most of which are probably not your local machine. Instead, you have to bind to a local port. I do not think there is a way to check if an ip is part of a multicast group, but I don't understand what you are trying to do anyway. I recommend you change to
sock.bind(('0.0.0.0', MCAST_PORT))


text:
Q: kubernetes ingress-nginx ignore special characters in path I'm trying to have a rule listening to a specific path containing a dollar sign like this:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: metadata-ingress
  annotations:
    nginx.ingress.kubernetes.io/enable-cors: "true"
    nginx.ingress.kubernetes.io/ssl-redirect: "true"
    nginx.ingress.kubernetes.io/use-regex: "false"
spec:
  ingressClassName: public
  tls:
  - hosts:
    - mydomain.com
  rules:
  - host: mydomain.com
    http:
      paths:
      - path: /api/v2/$metadata
        pathType: Prefix
        backend:
          service:
            name: busybox
            port:
              number: 8280

I don't want any url rewrite or anything fancy, just want this specific path to be caught and forwarded to this service.
Without the "$" it works.
I thought disabling regex with use-regex: "false" would fix it, but no.
I also tried using the url encoded value for $ : %24metadata but it doesn't help either.
I also tried to use "exact" instead of "prefix" as the pathType but no.

A: I can't reproduce your problem, but I thought I walk through my test setup and you can tell me if anything is different. For the purpose of testing different paths, I have two deployments using the traefik/whoami image (this just provides a useful endpoint that shows us -- among other things -- the hostname and path involved in the request).
That looks like:
apiVersion: v1
kind: Service
metadata:
  labels:
    app: example
    component: app1
  name: example-app1
spec:
  ports:
  - name: http
    port: 80
    targetPort: http
  selector:
    app: example
    component: app1

---
apiVersion: v1
kind: Service
metadata:
  labels:
    app: example
    component: app2
  name: example-app2
spec:
  ports:
  - name: http
    port: 80
    targetPort: http
  selector:
    app: example
    component: app2

---
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: example
    component: app1
  name: example-app1
spec:
  selector:
    matchLabels:
      app: example
      component: app1
  template:
    metadata:
      labels:
        app: example
        component: app1
    spec:
      containers:
      - image: docker.io/traefik/whoami:latest
        name: whoami
        ports:
        - containerPort: 80
          name: http

---
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: example
    component: app2
  name: example-app2
spec:
  selector:
    matchLabels:
      app: example
      component: app2
  template:
    metadata:
      labels:
        app: example
        component: app2
    spec:
      containers:
      - image: docker.io/traefik/whoami:latest
        name: whoami
        ports:
        - containerPort: 80
          name: http

I've also deployed the following Ingress resource, which looks mostly like yours, except I've added a second paths config so that we can compare requests that match /api/v2/$metadata vs those that do not:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  annotations:
    cert-manager.io/cluster-issuer: house
    nginx.ingress.kubernetes.io/enable-cors: "true"
    nginx.ingress.kubernetes.io/ssl-redirect: "true"
  name: example
spec:
  ingressClassName: nginx
  rules:
  - host: example.apps.infra.house
    http:
      paths:
      - backend:
          service:
            name: example-app1
            port:
              name: http
        path: /
        pathType: Prefix
      - backend:
          service:
            name: example-app2
            port:
              name: http
        path: /api/v2/$metadata
        pathType: Prefix
  tls:
  - hosts:
    - example.apps.infra.house
    secretName: example-cert

With these resources in place, a request to https://example.apps.infra.house/ goes to app1:
$ curl -s https://example.apps.infra.house/ | grep Hostname
Hostname: example-app1-596fcf48bd-dqhvc

Whereas a request to https://example.apps.infra.house/api/v2/$metadata goes to app2:
$ curl -s https://example.apps.infra.house/api/v2/\$metadata | grep Hostname
Hostname: example-app2-8675dc9b45-6hg7l

So that all seems to work.

We can, if we are so inclined, examine the nginx configuration that results from that Ingress. On my system, the nginx ingress controller runs in the nginx-ingress namespace:
$ kubectl -n nginx-ingress get deploy
NAME                       READY   UP-TO-DATE   AVAILABLE   AGE
ingress-nginx-controller   1/1     1            1           8d

The configuration lives in /etc/nginx/nginx.conf in the container. We can cat the file to stdout and look for the relevant directives:
$ kubectl -n nginx-ingress exec deploy/ingress-nginx-controller cat /etc/nginx/nginx.conf
...
                location /api/v2/$metadata/ {
                ...
                }
...

Based on your comment, the following seems to work:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: example
  annotations:
    nginx.ingress.kubernetes.io/ssl-redirect: "true"
    nginx.ingress.kubernetes.io/rewrite-target: "/$2"
    cert-manager.io/cluster-issuer: house
spec:
  ingressClassName: nginx
  tls:
    - hosts:
      - example.apps.infra.house
      secretName: example-cert
  rules:
  - host: example.apps.infra.house
    http:
      paths:
      - path: /app1(/|$)(.*)
        pathType: Prefix
        backend:
          service:
            name: example-app1
            port:
              name: http

      # Note the use of single quotes (') here; this is
      # important; using double quotes we would need to
      # write `\\$` instead of `\$`.
      - path: '/api/v2/\$metadata'
        pathType: Prefix
        backend:
          service:
            name: example-app2
            port:
              name: http

The resulting location directives look like:
location ~* "^/api/v2/\$metadata" {
...
}
location ~* "^/app1(/|$)(.*)" {
...
}

And a request for the $metadata path succeeds.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Multiprocessing Equally Query as pandas df then merge df's into Single df I want to summarize many tables records count, and I want it parallelly running to save time.
list_tabl_cn =['TBL_A', 'TBL_B', 'TBL_C', 'TBL_D']

def tblRowCn(p_tbl):
    #connDb = pyodbc.connect(f'DSN={nama_db_target}', autocommit =True)
    connDb = sqlanydb.connect(uid='dba',
                               pwd='sql',
                               host='ip:port',
                               dbn='blah')
    is_tableExists = ego.my_desc(p_tbl,163).shape[0]
    if is_tableExists:
        proc_name = 'df_'+p_tbl
        if p_tbl == 'STG_CFG_SYS':
            Q_ = """\
              SELECT OPENDATE as TGL_POS, COUNT(1) CN FROM {0}
              GROUP BY TGL_POS
            """.format(p_tbl)
        else:
            Q_ = """\
              SELECT TANGGAL_POSISI as TGL_POS, COUNT(1) CN FROM {0}
              GROUP BY TGL_POS
            """.format(p_tbl)
        df_tbl = pd.read_sql_query(Q_, connDb, parse_dates=['TGL_POS'])
        df_tbl['THN'],df_tbl['BLN']= df_tbl['TGL_POS'].dt.year, df_tbl['TGL_POS'].dt.month
    else:
        df_tbl=[]

    return df_tbl

def task(table_nm):
    print(f"Task Executed with process {mp.current_process().pid}")
    tblRowCn(table_nm.upper())

def main():
    executor = mp.Pool(mp.cpu_count()-8)
    executor.map(task, [n_table_nm for n_table_nm in list_tabl_cn])
    executor.close()

if __name__ == "__main__":
    main()

May be something like this
def main():
    executor = mp.Pool(mp.cpu_count()-8)
    executor.map(task, [n_table_nm for n_table_nm in list_tabl_cn])
    append.[task1, task2, task...]
    executor.close()

Which my whole dataframe is append.[task1, task2, task...]
I believe I missed something in my code, but it is too blur.

A: If all your Dataframes has same columns and you want all the rows of all dataframes to be added in to one dataframe, then you can use pandas concat function. add all your individual dataframes to a list, then concat all of them to make your main dataframe.
list_of_df =[]
for df in executor.map(task, list_tabl_cn):
    if df:
        list_of_df.append(df)
main_df = pd.concat(list_of_df)

you can remove the else condition in tblRowCn method, its redundant and not needed.
In your code you generated a list from list_tabl_cn to pass it to map function, you don't have to do that, you can give list_tabl_cn to map function directly as in the above code.


text:
Q: create date time table using sql preocedure How I can create a table like this in Sql server using procedure?
Year   Month   Week  Day  Hour Min
2016     1      1     1    1   1
2016     1      1     1    1   2
-        -      -     -    -   -
2016     1      1     1    1   60
-        -      -     -    -   -
2016     1      1     1    2   60
-        -      -     -    -   -
2016     1      1     1    60  60

A: I use a udf to create date ranges on-the-fly.
Select Year=Year(RetVal)
      ,Month=Month(RetVal)
      ,Week=DatePart(WEEK,RetVal)
      ,Day=Day(RetVal)
      ,Hour=DatePart(HH,RetVal)
      ,Min=DatePart(MI,RetVal)
 From [dbo].[udf-Create-Range-Date]('2016-01-01','2016-01-02','MI',1)

Returns
Year    Month   Week    Day Hour    Min
2016    1   1   1   0   0
2016    1   1   1   0   1
2016    1   1   1   0   2
2016    1   1   1   0   3
2016    1   1   1   0   4
2016    1   1   1   0   5
2016    1   1   1   0   6
2016    1   1   1   0   7
2016    1   1   1   0   8
2016    1   1   1   0   9
...

Here is the function
CREATE FUNCTION [dbo].[udf-Create-Range-Date] (@DateFrom datetime,@DateTo datetime,@DatePart varchar(10),@Incr int)

Returns
@ReturnVal Table (RetVal datetime)

As
Begin
    With DateTable As (
        Select DateFrom = @DateFrom
        Union All
        Select Case @DatePart
               When 'YY' then DateAdd(YY, @Incr, df.dateFrom)
               When 'QQ' then DateAdd(QQ, @Incr, df.dateFrom)
               When 'MM' then DateAdd(MM, @Incr, df.dateFrom)
               When 'WK' then DateAdd(WK, @Incr, df.dateFrom)
               When 'DD' then DateAdd(DD, @Incr, df.dateFrom)
               When 'HH' then DateAdd(HH, @Incr, df.dateFrom)
               When 'MI' then DateAdd(MI, @Incr, df.dateFrom)
               When 'SS' then DateAdd(SS, @Incr, df.dateFrom)
               End
        From DateTable DF
        Where DF.DateFrom < @DateTo
    )

    Insert into @ReturnVal(RetVal) Select DateFrom From DateTable option (maxrecursion 32767)

    Return
End

-- Syntax Select * from [dbo].[udf-Create-Range-Date]('2016-10-01','2020-10-01','YY',1)
-- Syntax Select * from [dbo].[udf-Create-Range-Date]('2016-10-01','2020-10-01','DD',1)
-- Syntax Select * from [dbo].[udf-Create-Range-Date]('2016-10-01','2016-10-31','MI',15)
-- Syntax Select * from [dbo].[udf-Create-Range-Date]('2016-10-01','2016-10-02','SS',1)

A: With the help of CTE:
CREATE PROCEDURE dbo.dates
    @datestart date,
    @dateend date
AS
BEGIN
    SET NOCOUNT ON;

    WITH cte AS (
    SELECT CAST(@datestart as datetime) as d
    UNION ALL
    SELECT DATEADD(MINUTE,1,d)
    FROM cte
    WHERE d < DATEADD(minute,59,DATEADD(hour,23,CAST(@dateend as datetime)))
    )

    SELECT  DATEPART(YEAR,d) [Year],
            DATEPART(MONTH,d) [Month],
            DATEPART(WEEK,d) [Week],
            DATEPART(DAY,d) [Day],
            DATEPART(HOUR,d) [Hour],
            DATEPART(MINUTE,d) [Min]
    FROM cte
    OPTION (MAXRECURSION 0)
END

EXEC dbo.dates '2016-01-01', '2016-12-31'

Output:
Year    Month   Week    Day Hour    Min
2016    1       1       1   0       0
2016    1       1       1   0       1
2016    1       1       1   0       2
2016    1       1       1   0       3
2016    1       1       1   0       4
2016    1       1       1   0       5
2016    1       1       1   0       6
2016    1       1       1   0       7
2016    1       1       1   0       8
....
2016    12      53      31  23      59


text:
Q: Android 2.2 (API 8) Logging Out I have an app that will have multiple activities open.
Activity A -> Activity B -> Activity C
I want to logout and close all open activities. I have read many different links that describes how to do this.
On logout, clear Activity history stack, preventing "back" button from opening logged-in-only Activites
Close all running activities in an android application?
The issue for this however is that the Intent Flags only work with API level 11 and above. I have an app that I would like to be made available for API level 8 and above. I know that it goes way back but what is the best way to accomplish this for API level 8?
Or should I just give in and make the minimum level 11?

A: Intent intent  = new Intent(this, LoginActivity.class);
 intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
 startActivity(intent);``

A: Did you try this ?
   void signOut() {
        Intent intent = new Intent(this, HomeActivity.class);
        intent.putExtra("finish", true);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // To clean up all activities *not necessary*
        startActivity(intent);
        finish();
   }

from this answer

A: Okay, you can do one thing get ProcessID of your application and in onDestroy() kill that process. Thats it from this link How to force stop my android application programmatically?
int pid=android.os.Process.myPid();
android.os.Process.killProcess(pid);

you can use alternative told by one of user here  using startActivityForResult() and onActivityResult() works fine even on API level 8.
For this u need to use
 startActivityForResult() instead of startActivty. and onActivtyResult() for you work.

A: you say "I want to logout and close all open activities." , Intent.FLAG_ACTIVITY_CLEAR_TOP works on API Level 8 , I have incorporated Logout functionality ,that way in app that is already in store, but there is one difference if I understand you correctly , logout goes to LoginActivity , logout does not kill process or something as this goes against concept of Android. Anyway you can even do this also when you do this as suggested above:
  void logout() {
        Intent intent = new Intent(this, LoginActivity.class);
        intent.putExtra("finish", true);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
   }

And then in LoginActivity you can search for "finish" boolean in extra in onCreate method and finish that activity too.
@Override public void onCreate(Bundle state) {
    super.onCreate(state);
    if (getIntent().getBooleanExtra("finish", false)) finish();
}


text:
Q: How to replace first occurrence only in vim Is there any option to replace the first occurrence without asking for confirmation in vim?
I want to replace New York with \place{New York} in the first occurrence only without asking for confirmation. I used this code:
silent! /\\begin{text}/,/\\end{textit}/s/New York/\\place{New York}/g

> \begin{text}..[paragraphs]...\end{textit}

New York may be contained 10 times in the paragraph.

A: So you want to in a line range do only single substitution, not one sub per line. So the /start/,/end/ s/pat/rep/ will not work. I would make your example simpler, given that we have:
foo
nyc nyc
nyc nyc
bar

I guess what you are expecting to have is
foo
\\place{nyc} nyc
nyc nyc
bar

However :/foo/,/bar/ s/nyc/\\place{&} will give
foo
\\place{nyc} nyc
\\place{nyc} nyc
bar

Because :s will do sub for each line in range.
I would narrow the range to solve this problem:
/foo//nyc/s/nyc/\\place{&}/

note that between /foo/ and /nyc/, there is no comma.
The output should be:
foo
\\place{nyc} nyc
nyc nyc
bar

You may want to read :h range for details.

A: The /g flag at the end of your substitution means that it will be performed on every occurence of your search pattern. Remove it and it will only be performed on the first occurence.
Also, :s doesn't ask for confirmation by default; you would need to add the /c flag for that. So I'm not sure why you prepend it with :silent.
Another comment: You can reuse the matched text in the replace part with &:
:/\\begin{text}/,/\\end{textit}/s/New York/\\place{&}


text:
Q: Prove that an integral of a sequence of functions converging to $0$ implies that the sequence converges to $0$ $\mu$-a.e. We are given a decreasing sequence $(f_n)_{n=1}^\infty$ of non-negative Lebesgue integrable functions on a measure space $(X,\mathcal{A},\mu)$. We are asked to show that if the integral $\int f_n \,d\mu$ converges to $0$ as $n\rightarrow\infty$ then the sequence $(f_n)_{n=1}^\infty$ converges to 0 $\mu$-a.e.
Does anyone have any ideas on how to solve this? My first thought was to use the dominated convergence theorem, since we can use $f_1$ as the integrable majorant. We also talked about the fact that the sequence converges to $0$ in mean and thus converges to $0$ in measure, which implies that there is a subsequence of $(f_n)_{n=1}^\infty$ that then converges to $0$ $\mu$-a.e. One would then need to show that there are no subsequences not converging to $0$ $\mu$-a.e.

A: Why not proceed by contradiction and note that
\begin{equation*} H=\{x\in X \mid f_{n}(x) \text{ does not converge to } 0\} = \bigcup_{n=1}^{\infty}H_{m}=\bigcup_{m=1}^{\infty} \left\{x\in X \;\middle\vert\; \lim_{n\to\infty}f_{n}(x)\geq\frac{1}{m}\right\}\end{equation*}
and note further that if each set in the union is $\mu$-null, then so is $H$. It follows that there is some $m_{0}$ such that $\mu(H_{m_{0}})>0$. Now,
\begin{equation*} \lim_{n\to\infty}\int_{X}f_{n}(x)d\mu\geq \lim_{n\to\infty}\int_{H_{m_{0}}}f_{n}(x)d\mu\geq\int_{H_{m_{0}}}\frac{1}{m_{0}}d\mu=\frac{\mu(H_{m_{0}})}{m_{0}}>0\end{equation*}
by dominated convergence.


text:
Q: Combining all CSS in one file or dynamic loading then? I want to know if is better to have all CSS files minified and combined in a single file, that will have all the styles of the site, or having smallest files that will be loaded on demand depending of page visited.

A: I would say minifi right away and allow browsers to cache the information. it might take slightly longer to load the first visit, but all later visits will be faster.
Here Is a blog post I found explaining it.
http://www.hanselman.com/blog/TheImportanceAndEaseOfMinifyingYourCSSAndJavaScriptAndOptimizingPNGsForYourBlogOrWebsite.aspx


text:
Q: Reading from JSON I'm trying to read my i18n-strings from a JSON file following this guide.
I have en-US.json:
{
  "world": "the world!"
}

And for setting up my Vue app I use:
import { createI18n } from 'vue-i18n'
import enUS from '../src/i18n/en-US.json'

// Type-define 'en-US' as the master schema for the resource
type MessageSchema = typeof enUS

const i18n = createI18n<[MessageSchema], 'en-US'>({
  locale: 'en-US',
  messages: {
    'en-US': enUS
  }
})

This works. But as soon as I add one non-ASCII char (e.g. "world": "the w@rld!"), I get the following error message:
[plugin:vite-plugin-vue-i18n] Cannot read properties of undefined (reading 'message')
/home/bernhard/wd/quasar2-project/src/i18n/en-US.json

Strangely, this works when I do the following straight in my .ts file:
const enUS = {
   "world": "the w@rld!"
}

so maybe something wrong with the way the JSON is processed?

A: The answer has two layers.

*

*As @jonrsharpe pointed out, there is a set of special characters: { } @ $ | - i.e. for inserting variables. A @ should i.e. be replaced by {'@'}.

*A bug in how vite processes external json as described on this bug on Github. By default, quasar is using "@intlify/vite-plugin-vue-i18n": "^3.3.1". Changing that to "@intlify/vite-plugin-vue-i18n": "^7.0.0" solved the issue.


text:
Q: NullPointerException when accessing array of JTextAreas I'm making an assignment planner, where one enters the assignment for the day in a JTextArea. I made the JTextAreas static, so I could access them outside the class. To clean up my code, I decided to use for loops and put the JTextAreas into static instance variable- arrays. But, when I try to access a JTextArea through an array, I get a NullPointerException. Here is an example of the declaration of a JTextArea:
static JTextArea MondayEng;

The arrays (one per subject) are declared as so:
static JTextArea[] Eng =  new JTextArea[]{
    MondayEng,
    TuesdayEng,
    WednesdayEng,
    ThursdayEng,
    FridayEng
};

And then there is a JTextArea[][] which contains the arrays:
static JTextArea[][] subjs = new JTextArea[][] {Eng, Hist, Math, Sci, Lang};

The JTextAreas are instantiated inside the JFrame (Called PWin), like this:
MondayEng = new JTextArea();
MondayEng.setBounds(664, 68, 153, 100);
contentPane.add(MondayEng);

I'll try to get the contents of the JTextAreas like this:
for (int i = 0; i < PWin.subjs.length; i++) { // Iterate through subjects
        String sub = subjects[i]; // Store the current subject in a variable
        for (int y = 0; y < days.length; y++) { // Iterate through days in week
            String day = days[y]; // Store the current day in a variable
            String str = PWin.subjs[i][y].getText(); // Get the text of the JTextArea currently selected, plop it in a string

The this is exception when saving files:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at PSave.<init>(PSave.java:19)
    at PWin$1.actionPerformed(PWin.java:262)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2028)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2351)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
    at java.awt.Component.processMouseEvent(Component.java:6373)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
    at java.awt.Component.processEvent(Component.java:6138)
    at java.awt.Container.processEvent(Container.java:2085)
    at java.awt.Component.dispatchEventImpl(Component.java:4735)
    at java.awt.Container.dispatchEventImpl(Container.java:2143)
    at java.awt.Component.dispatchEvent(Component.java:4565)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4621)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4282)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4212)
    at java.awt.Container.dispatchEventImpl(Container.java:2129)
    at java.awt.Window.dispatchEventImpl(Window.java:2478)
    at java.awt.Component.dispatchEvent(Component.java:4565)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:679)
    at java.awt.EventQueue.access$000(EventQueue.java:85)
    at java.awt.EventQueue$1.run(EventQueue.java:638)
    at java.awt.EventQueue$1.run(EventQueue.java:636)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
    at java.awt.EventQueue$2.run(EventQueue.java:652)
    at java.awt.EventQueue$2.run(EventQueue.java:650)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:649)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

Any help will be appreciated a lot!

A: It seems like your problem is that at the time you are creating your arrays, the JTextAreas haven't been constructed yet. Java is pass by value, so when you pass in the names of JTextAreas that are to be constructed later it is the same as passing null.

A: You need to replace this:
MondayEng = new JTextArea();
MondayEng.setBounds(664, 68, 153, 100);
contentPane.add(MondayEng);

with:
Eng[0] = new JTextArea();
Eng[0].setBounds(664, 68, 153, 100);
contentPane.add(Eng[0]);

Otherwise, the array Eng still contains nulls, and you are just creating a new JTextArea object and making MondayEng refers to that object instead of pointing to what Eng[0] is pointing to.
However, the more correct answer would be constructing the JTextAreas just before passing them to the array. Something like:
MondayEng = new JTextArea();
MondayEng.setBounds(664, 68, 153, 100);
contentPane.add(MondayEng);

// ...

static JTextArea[] Eng =  new JTextArea[]{
    MondayEng,
    TuesdayEng,
    WednesdayEng,
    ThursdayEng,
    FridayEng
};

A: Since JTextArea[][] subjs is a double dimensional array you need to take care of generating the array properly. The way you created is a single dimensional array. Ideally you may need to create like
JTextArea[][] subs = new JTextArea[][]{ {Eng, Hist, Math, Sci, Lang} };


text:
Q: APC FOR PHP 5.3.8 I've been trying to install apc . I've added the .dll file to the extenstions directory ( so far i'm running the application on xamppm, apache) . I've also updated the php.ini as well.
The problem comes up when I restart the apache and then the next warning appears :
php startup : unable to load dynamic library c:/xampp/php/ext/php_apc.dll

I think the problem might be the fact that the php version I employ is 5.3.8 .
I've been looking for apc download for php 5.3.8 and I hadn't found any,
What am I able to do in order to solve this problem ?
Any suggestion will be helpful , thanks in advance

A: I had the same problem and it was because i was using x64 version of WAMP server so i downloaded the x64 version of php_apc.dll file and it worked.
Here is a link

A: In the following site you'll be able to find the extension compiled for Windows in a variety of "flavours" ready to download:
http://dev.freshsite.pl/php-accelerators/apc.html
Hint: you mention you use XAMPP, which as far as I can tell bundles PHP compiled with VC9 and thread safe, so you are probably looking for this one if you use Windows 7 or this one for other windows versions.
Side note: As somebody who has been using Apache and PHP under win heavily, I can only recommend to switch to Linux as soon as you can: PHP extensions (among many other things) are way much less of a headache there.


text:
Q: Наведение на два объекта
Бизнес-планирование

подскажите как сделать, чтобы при наведении на ссылку окрашивался текст ссылки а в img подгружалась другая картинка, и наоборот, при наведении на картинку - менялась картинка и цвет ссылки

A: https://api.jquery.com/hover/

$(".menuHref").hover(
  function() { //mousein
    var $target = $(this)
    $target.find("a").css("color", "red");//new color
    $target.find("img").attr("src", "new_image_link");//new image
  },
  function() { //mouseout
    var $target = $(this)
    $target.find("a").css("color", "");//restore color
    $target.find("img").attr("src", "old_image_link");//restore old image
  }
)

Бизнес-планирование

A: Лучше это делать через CSS.
Будут следующие правила:
.menuHref a {
}
.menuHref img{
}
.menuHref:hover a {
}
.menuHref:hover img{
}

Тогда правила hover будут применяться при наведении на весь блок (на изображение и на ссылку).
И картинку лучше тоже в CSS указывать.
Для JS если что решение будет таким же — вешать событие на контейнер общий и уже изменять свойства "детей".

A:

$(".rightCenter").hover(
  function() { //mousein
    var $target = $(this)
    $target.find("a").css("color", "red");//new color
    $target.find("img").attr("src", "new_image_link");//new image
  },
  function() { //mouseout
    var $target = $(this)
    $target.find("a").css("color", "");//restore color
    $target.find("img").attr("src", "old_image_link");//restore old image
  }
)
a{
 color:#fdfbfb;
 text-decoration: none;
 transition: all 0.4s;
 cursor: pointer;
}
a:hover{
 cursor: pointer;
 color: #2987ac;
 transition: all 0.4s;
}

.active-link{

transition: all 0.4s;
vertical-align: middle;
}

 БЕЛАРУСЬ

     +3-211-111-111-11

   РОССИЯ

В чем проблема?


text:
Q: Modeling the probability of a uniform point on $[a, b]$ I was given the following exercise : Explain how to define a probability measure on $\mathbb R$ that corresponds to the intuitive notion of an uniform point on $[a, b]$.
And this is the solution :

Let $f : \Bbb R \to \Bbb R$ be defined as $f(x) := (b − a)x + a$. This
function is an affine bijection between $[0, 1]$ and $[a, b]$. Let
$\lambda$ be the Lebesgue measure on $[0,1]$. We can define a
probability measure $µ$ on $\Bbb R$ by setting $µ(B) := λ(f ^{−1}(B
> \cap [a, b]))$ for any Borel measurable subset $B$ of $\Bbb R^n$ . The
corresponding c.d.f. is given by $F(x) = 0$ if $x < a$, $F(x) = 1$ if
$x > b$ and $F(x) = f^{−1} (x) = \frac{x−a}{b−a}$ if $x ∈ [a, b]$.

I do not understand the question the exercise is asking. What is "the intuitive notion of an uniform point on $[a, b]$" ? Are they looking for a probability where all points in $[a,b]$ have the same probability ?

A: Uniform means that the probability of a Borel set should be proportional to it's Lebesgue measure. Therefore we should define $\mu(E) = \frac{1}{b - a}m(E)$, where $m$ is Lebesgue measure. Their solution is a strange way to arrive at the same $\mu$.


text:
Q: Excel - Macro Changing sheets and Fill to End - Compile Error I am creating a Macro to run consecutively on about 25 sheets, where I am naming a cells in a specific column.  I have the code for filling to end, and for changing sheets.  But when I combine the codes, I am getting a warning:

Compile Error:  Duplicate declaration in current scope

When I remove the DIM definition, it will run on the consecutive sheets, but only to the end of the first sheet.  My goal is to have each sheet dynamically filled to end in column N with a set name for each.
Here is the code I was working on
    Sub Mailbox_Name()
'
' Mailbox_Name Macro
' Adds Mailbox Name to Each Sheet

'
    Dim LR As Long
    LR = Cells.Find(What:="*", SearchDirection:=xlPrevious, SearchOrder:=xlByRows).Row
    Range("N1").Select
    ActiveCell.FormulaR1C1 = "Mailbox"
    Range("N2").Select
    ActiveCell.FormulaR1C1 = "ACC"
    Range("N2").Select
    Selection.AutoFill Destination:=Range("N2:N" & LR)
    Range("N2:N" & LR).Select

    Selection.Copy
    Sheets("ACPR").Select
    Dim LR As Long
    LR = Cells.Find(What:="*", SearchDirection:=xlPrevious, SearchOrder:=xlByRows).Row
    Range("N1").Select
    ActiveCell.FormulaR1C1 = "Mailbox"
    Range("N2").Select
    ActiveCell.FormulaR1C1 = "ACPR"
    Range("N2").Select
    Selection.AutoFill Destination:=Range("N2:N" & LR)
    Range("N2:N" & LR).Select
End Sub

Thanks for any help you can provide!

A: Just read what the error is telling you - you have a duplicate declaration. Sure enough, in your code you have Dim LR As Long twice.


text:
Q: Listview to pull up button/widget I have simple listview example here with bottomNavigationBar, I need to when listview reach end(bootom scroll) new button to show up. Should i put button inside listview somehow or there is other way?
here is complete example so Test button to show up on end of scrolling not all the time..
import 'package:flutter/material.dart';
import 'listview_column.dart';

void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(

        primarySwatch: Colors.blue,
      ),
      //home: MyHomePage(title: 'Flutter Demo Home Page'),
      home: ListViewColumn(),
    );
  }
}

listview class
import 'package:flutter/material.dart';

class ListViewColumn extends StatelessWidget {
  final List<String> _listViewData = [
    "A List View with many Text - Here's one!",
    "A List View with many Text - Here's another!",
    "A List View with many Text - Here's more!",
    "A List View with many Text - Here's more!",
    "A List View with many Text - Here's more!",
    "A List View with many Text - Here's more!",
    "A List View with many Text - Here's one!",
    "A List View with many Text - Here's another!",
    "A List View with many Text - Here's more!",
    "A List View with many Text - Here's more!",
    "A List View with many Text - Here's more!",
    "A List View with many Text - Here's more!",
    "A List View with many Text - Here's one!",
    "A List View with many Text - Here's another!",
    "A List View with many Text - Here's more!",
    "A List View with many Text - Here's more!",
    "A List View with many Text - Here's more!",
    "A List View with many Text - Here's more!",
    "A List View with many Text - Here's one!",
    "A List View with many Text - Here's another!",
    "A List View with many Text - Here's more!",
    "A List View with many Text - Here's more!",
    "A List View with many Text - Here's more!",
    "A List View with many Text - Here's more!",
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('ListView in Column Example'),
      ),
      body: Column(
        children: <Widget>[

          Expanded(
            child: ListView(
              physics: ClampingScrollPhysics(),
              padding: EdgeInsets.all(10.0),
              children: _listViewData.reversed.map((data) {
                return Column(
                  children: <Widget>[
                    ListTile(
                      title: Text(data),
                    ),
                  ],
                );
              }).toList(),
            ),
          ),
          FlatButton(
            child: Text('test'),
            onPressed: (){},
          ),
        ],
      ),
      bottomNavigationBar: BottomAppBar(
        color: Color.fromRGBO(121, 85, 72, 1.0),
        child: Container(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[

              InkWell(
                  splashColor: Color.fromRGBO(78, 53, 43, 0),
                  highlightColor: Color.fromRGBO(78, 53, 43, 1),
                  onTap: () {

                  },
                  child: Padding(
                    padding: EdgeInsets.only(
                        top: 15.0, bottom: 15.0, left: 40.0, right: 40.0),
                    child: Text(
                      'Finish - Create Report',
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: 18.0,
                          fontWeight: FontWeight.w600),
                    ),
                  )),
            ],
          ),
        ),
      ),
    );
  }
}

A: You can use a ScrollController with a listener so when you attain the end of your list you add your button to your _listViewData using a setState. (Don't forget to add the controller to your ListView)
ScrollController controller;

@override
void initState() {
    super.initState();
    controller = ScrollController()..addListener(_scrollListener);
}

_scrollListener() {
    if (controller.position.pixels == controller.position.maxScrollExtent) {
      addButtonToList();
    }
}

A: You can wrap the Column with a SingleChildScrollView. The button will always appear at the end of the ListView's scroll.
/* Scaffold */
body: SingleChildScrollView(
        physics: ClampingScrollPhysics(),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            ListView(
              physics: NeverScrollableScrollPhysics(),
              padding: EdgeInsets.all(10.0),
              shrinkWrap: true,
              children: _listViewData.reversed.map((data) {
                return Column(
                  children: <Widget>[
                    ListTile(
                      title: Text(data),
                    ),
                  ],
                );
              }).toList(),
            ),
            FlatButton(
              child: Text('test'),
              onPressed: (){},
            ),
          ],
        ),
      ),
/* Scaffold */

A: With Dart 2.5 you can do this:
ListView(
  children: <Widget>[
    ..._listViewData,
      FlatButton(
        child: Text('test'),
          onPressed: (){},
        ),
    ]
)


text:
Q: Simple array lookup I have an array, $persons
When I execute: print_r($persons) I get:
(
[0] => 30131
[1] => 29763
)

The two five-digit numbers are IDs for two posts in a CPT called people
How do I iterate through the array and print the title of each post?
My best guess returns nothing:
            foreach( $persons as $person ):
                $title = get_the_title( $person->ID );
                $peopleout .= $title . ', ' ;
            endforeach;
            echo $peopleout

A: Judging from your first snippet, $person inside your loop is a single value, not an object.
That means you should change the $title = lines to this:
$title = get_the_title($person);

Also, you will currently be adding an extra comma at the end of the string. To resolve this, I would add the title to an array, then implode that array  to echo the values. That would look like this;
$peopleout = [];
foreach( $persons as $person ):
    $peopleout[] = get_the_title($person);
endforeach;
echo implode(", ", $peopleout);

A: $person is no object, so keep it plain as it contains the ID.
$title = get_the_title($person);

Just for fun you can do all of this as a one-liner.
echo implode(', ', array_map(fn($id) => get_the_title($id), $persons));


text:
Q: How to cover ember-simple-auth with acceptance tests? I am trying to cover sign in page with acceptance tests. Small example:
test('visiting /sign-in', function(assert) {
  visit('/sign-in');

  fillIn('.t_sign-in_email', 'tony.stark@example.com');
  fillIn('.t_sign-in_password', 'secret-password');
  click('.t_sign-in_submit');

  andThen(() => assert.equal(currentURL(), '/'));
});

But when it calls click function it immediately throws error:

SyntaxError: Unexpected token u in JSON at position 0

If I try sign in manually it works perfectly. Please help to find out what's wrong with this code?

A: The code above seems fine. I think your route handler expects a JSON string but receives something else. Are you using mirage?


text:
Q: C : shmget with a 2D array I try to use shmget with a 2D array.
This is my code :
char **array;
key_t key;
int size;
int shm_id;
int i = 0;
void *addr;

key = // here I get the key with ftok()
size = (21 * sizeof(char *)) + (21 * sizeof(char **));
shm_id = // here I get the shmid with shmget()

if (shm_id == -1) // Creation
{
     array = (char **)shmat(shm_id, NULL, SHM_R | SHM_W);
     while (i != 20)
     {
         array[i] = memset(array[i], ' ', 20);
         array[i][20] = '\0';
         i++;
     }
     array[i] = NULL;
     shm_id = // here I get the shmid with the flag IPC_CREAT to create the shared memory
     addr = shmat(shm_id, NULL, SHM_R | SHM_W);
}

But I've a segmentation fault with the line "array[i] = memset(array[i], ' ', 20);"
What am I doing wrong?

A: You should first check whether shmget succeeds or not. if allocation of shared memory fails, then you can't be using shared memory! ;-)
Like:
If ( shm_id = shmget(.......) == -1) {
exit(1);
}
else {
/* proceed with your work*/
}

and the same for shmat as well.
shmget returns void*. you can't assign it to a char** and and use it like a 2d array. In fact, a char* can easily be handled as a 2D array logically.


text:
Q: API To Object Mapping in PHP We have so many ORM (Object Relational Mapping) software:
http://en.wikipedia.org/wiki/List_of_object-relational_mapping_software#PHP
How about API to Object mapping?
We don't use database, but API. So all data come from REST APIs.
Classic ORMs do not seem to handle that. Looks like I should do my own using Zend's code generator: http://framework.zend.com/manual/en/zend.codegenerator.html


text:
Q: jQuery UI Sortable Ignoring items that doesn't match items selector I've got a special case situation for a table that contains two levels of groupings.  I'm dealing with some legacy code that uses a table construct with interleaved rows of class "group" and "member" to show a hierarchy of groups with all of their associated members.
Here is a simplified table:

      column 1

      group A

      member A1

      member A2

      group B

      group C

      member C1

      member C2

      member C3

      group D

I'm trying to use jQuery sortable to allow the user to drag and drop the member table rows to the desired position within the table:
$("#my_table tbody").sortable({items: '> .member', forceHelperSize: true });

I am able to drag the "member" rows among other "member" rows to reorder them... That portion is working fine except I can't drag the "member" rows below "group D" (since there are no "member" rows below it).
If I remove the 'items' option, then the "group" rows can also be dragged -- something that I don't want.
I tried to remove the 'items' option and add a 'start' event handler to cancel the sortable if a "group" row was attempted to be moved.
start: function(event, ui) {
  if (ui.item.hasClass("group")) {
    $(this).sortable('cancel');
  }
}

Unfortunately, the 'cancel' action causes: TypeError "null is not an object" (this.helper.outerWidth) and a corruption of the table display (the moved "group" row is superimposed with the row below it).
Anyone have another method to suppress the draggability of the "group" rows (while still allowing the "member" rows to be dragged to any row position in the table)?

A: You can fix the issue by specifying .group as the value of cancel option.

Prevents sorting if you start on elements matching the selector.

If you use items option, the non-matching elements will totally ignored by sortable, but if you use cancel instead, the elements will be considered but will not be draggable.

$("#my_table tbody").sortable({
  cancel: ".group",
  forceHelperSize: true
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">

      column 1

      group A

      member A1

      member A2

      group B

      group C

      member C1

      member C2

      member C3

      group D

A: Why not just use handle in the options?
$("#my_table tbody").sortable({
  handle: '.member',
  forceHelperSize: true
});


text:
Q: Reduce the SVN repo size I have a huge SVN repo, 450K+ revisions, am trying to reduce the size of the history to just take the last couple of thousands of revisions, for example 20K and restore it in a new repo, I trI tried many way to achieve that, and non worked, below is the methods I recall that I used
1- normal dump, using the command below, it took two days,and still running, the dump size exceeded the repo size 8 times ( the repo size is 70G and before I killed the dump process the size of the dump reached 500GB)

svnadmin dump demo2/ -r420000:HEAD > /share/svnbkup/split.dump
  WARNING 0x0001: Mergeinfo referencing revision(s) prior to the oldest dumped >revision (r420000). Loading this dump may result in invalid mergeinfo.

2- using the same command but I used --incremental, The dump is not restorable

svnadmin dump demo2/ -r420000:HEAD --incremental > /share/svnbkup/split.dump
  * Dumped revision 420136.
  WARNING 0x0000: Referencing data in revision 419907, which is older than the >oldest dumped revision (r420000).  Loading this dump into an empty >repository will fail.
  WARNING 0x0001: Mergeinfo referencing revision(s) prior to the oldest dumped revision (r419907). Loading this dump may result in invalid mergeinfo.
  * Dumped revision 420137.

3- I used the dump from the step above and tried to use svndumpfilter, and it did nothing,
4- I tried to restore the dump as it is,

<<< Started new transaction, based on original revision 420000
  svnadmin: E160013: File not found: transaction '0-0', path '/trunk/tool/test.xml'
      * editing path : trunk/tool/test.xml ...root@lxc:/user#
  root@lxc:/SVN# du -sh final/
  168K   final/

A: *

*Find LOWER border, which will NOT have references outside range (read warnings carefully - now you have to include at least from r419907)

*Don't use --incremental for the first, base dump

*Slice range, found in step 1, into small slices, and dump small ranges (second and later - with --incremental option) in turn - less time, in case of any error you have to re-done only one small dump

On the rights on delirium
Forget about historic data, transfer only HEAD in new repo


text:
Q: Advice on how to handle PostgreSQL database in Django app? For some background, I worked on a Django app that had a SQLite3 database. I just created models in Django using the python manage.py startapp model_name, and just directly manipulated the database by creating API endpoints in python. I would then make API requests and change my database like that.
But this time, I've created a Django app that has a PostgreSQL database. I managed to connect my database to Django after figuring out how to install psycopg2. Then, I created a Users table in PostgreSQL through the command line. I want to get this table to show on my Django admin site, and hopefully repeat the same method for the other app. But the Django admin site can render only Django models that have been registered to the admin. So now, I'm wondering if there is a better method for working with PostgreSQL in Django.
I saw SO posts suggesting inspectdb, but this creates a large models.py file generating other classes for my app. I also couldn't successfully register the Users model to the Django admin site. I am now curious if I am working in the opposite direction. Should I be generating User models in Django and then from there, generate my PostgreSQL database?
Basically, can someone explain how to work with a PostgreSQL database in a Django app?

A: Can you be more specific with your question?
If you are confused on how to register the User table in django admin, you can register it in admin.py. But the method of registering depends on the type of User model you are using. You can see the docs for Custom User model.
And to get the user table in your database, you need to do migrate:
python manage.py makemigrations
python manage.py migrate

Let me know if you need any help.


text:
Q: Passing lookup field value to Standard controller Am stuck and unable to understand how shall i pass the lookup field value to controller. I am using get set,but it dint show any variable value in logs for the lookupfield ? Am stuck and not sure what to do. Can anyone please guide.
<apex: inputField value = "{!XYZ.AccountId}" />

test

 <apex:page standardcontroller=Contact extension="testLookup">
  <apex:form>
    <apex:inputfield value = "{!Contacts.AccountId} label = OldeAccount>
     <apex:variable value = "{!Contacts.AccountId}  var =' OldA'/>
<apex:inputfield value = "{!Contacts.AccountId} label = NewAccount>
<apex:variable value = "{!Contacts.AccountId}  var =' NewA'/>
</apex:page>

.
public with sharing testLookup
{
    public string OldA{get;set;}
    public string NewA {get;set;}

   public void save()
  {
     contact con = [select accountype,accountnumber from account where id=: OldA];
  test;
 update;
}
}

A: You need to have something happen to set the value.
use a command button to call a method in the controller. Once you do that the setter will fire and the value will be accessible to the controller.
You are also going about it all wrong. You do not need the variable...See this example:
Page
<apex:page standardController="Account" extensions="testextension">

    <apex:form>
    <apex:inputField value="{!Account.Name}"/>

   <apex:commandButton action="{!save}" rerender="msgs"/>
   </apex:form>

</apex:page>

Class
public class testextension{

       public Account a {get;set;}

        public testextension(apexPages.standardController con){
            a = (Account)con.getRecord();
        }

        public void save(){
            system.debug(a.Name); //Should be whatever you entered on the page
        }

    }


text:
Q: Kendo custom validation for datepicker I'm having problem with kendo datepicker custom validation (There is actually not many examples found on the web for custom validation in angular way). I have set the min value of the datepicker but it only works if the user choose the date from the dropdown.
If the date is typed in the input field of datepicker the min value can not affect. I want to at least show the user that they have entered an invalid date.
But it seems a bit confusing for me how to do it.
this is the html part: (vm is my controller)
<form name="myForm" kendo-validator="vm.validator" ng-submit="vm.validate($event)">
    <input id="systemValidityFrom" name="systemValidityFrom" data-type="date" kendo-date-picker
        k-options="vm.validityFromOption" k-ng-model="vm.nominationVM.ValidityFromDate" placeholder="Start date"
        required validationMessage="Enter a valid date" />

    <input type="image"
        src="/webapp/content/img/globalIcons/save_icon@1x.png"
        name="template-save-button"
        class="template-btn"
        id="template-save-button"
        ng-click="vm.saveChanges();" />

    <label for="template-save-button">Save</label>
</form>

This is the JS part:
vm.nominationVM = {ValidityFromDate: null};

vm.saveChanges = function () {
    if (vm.validator.validate()) {
        TemplateService.saveTemplate();
    }
};

vm.validityFromOption = {
    min: new Date()
};

For example I want to make the entered date invalid if it is less than today (forcing the user to type a date greater than today).
I'd be grateful if you can help me with this issue.

A: Yes, according to Telerik, the Min and Max options are applied only on the DatePicker's calendar (https://www.telerik.com/forums/datepicker---max-and-min).
If you want to evaluate the direct input of the user, you'll have to create a custom rule in your validator, for an example look at this implementation: https://demos.telerik.com/kendo-ui/validator/custom-validation


text:
Q: Java: search the nearest value in array I have an array of ordered double of big dimension, for example:
[2.1,3.4,3.6,4.1]

Now I generate, in some manner, a double numer, for example:
3.51

I need to make a function in Java that get the array and the number and give me the nearest value in the array of this number. In this example 3.6.
How i can do this in the most efficent way ? Because I can have array of 300000 double and need to do this operation frequently. Then i can't make a simple compare.
Edit:
I have make this, in some test the result is correct, for you is correct?
        int pos = Arrays.binarySearch(allTime.times, value);
        double out;

        if(pos >= 0)
        {
//          System.out.println(allTime.times[pos]);
            out = allTime.times[pos];
        }
        else if(pos == -1)
        {
//          System.out.println(allTime.times[0]);
            out = allTime.times[0];
        }
        else
        {
            int insertionPoint = -pos-1;
            if(insertionPoint < allTime.times.length)
            {
                if(allTime.times[insertionPoint] - value < value - allTime.times[insertionPoint-1])
//                  System.out.println(allTime.times[insertionPoint] );
                    out = allTime.times[insertionPoint];
                else
//                  System.out.println(allTime.times[insertionPoint-1] );
                    out = allTime.times[insertionPoint-1];
            }
            else
//              System.out.println(allTime.times[allTime.times.length -1]);
                out = allTime.times[allTime.times.length -1];
        }

A: Arrays.binarySearch also works for elements not contained in the array.
int pos = Arrays.binarySearch(arr, value);

If the value is not contained it returns a negative value which describes where the value should be: (-(insertion point) - 1).
Then just find which of the two neighbor values is the correct.
if(pos < 0)
{
  int insertionPoint = -pos-1;
  if(insertionPoint == arr.length) //value is bigger than every value in array
    //arr[insertionPoint-1] is the nearest value
  else if(insertionPoint == 0) //value is smaller than every value in array
    //arr[0] is the nearest value
  else if(value-arr[insertionPoint-1] < arr[insertionPoint]-value)
    //arr[insertionPoint-1] is the nearest value
  else
    //arr[insertionPoint] is the nearest value
}else
  //arr[pos] has the same value

The value at index insertPoint is bigger than value. I also handled the case that the value is contained in the array.

A: Jimmy T answer is not handling the corner case, like if the searching number falls before 0th index or if it falls beyond the last index.
Here is the corrected one
     double searchNearest(double[] array, double searchNumber) {
    int pos = Arrays.binarySearch(array, searchNumber);
    if (pos >= 0)
        return searchNumber;
    else {
        int insertionPoint = -pos - 1;
        if (insertionPoint > 0 && insertionPoint < array.length) {
            if ((searchNumber - array[insertionPoint - 1]) < (array[insertionPoint] - searchNumber)) {
                return array[insertionPoint - 1];
            } else {
                return array[insertionPoint];
            }

        } else {

            return insertionPoint == 0 ? array[0] : array[array.length - 1];
        }
    }

}


text:
Q: How to get realtime firebase data and show on update table on web page I want to export data from firebase and show the data on web page.
The table should updtae but unfortantly the table can't create new rows.
the code is example for two childs and the image show how the page looks right now.
the html code:

      #
      Board
      Image
      Notes
      Yes
      No

      1

      <input type="checkbox" name="firstYes" />
      <input type="checkbox" name="firstNo" />

      2

      <input type="checkbox" name="secYes" />
      <input type="checkbox" name="secNo" />

the js code:
function doFunction(){
    var ref = firebase.database().ref();
      ref.on("value", function(snapshot) {
      board=snapshot.child("1").child("Board").val();
      imageChild=snapshot.child("1").child("Image").val();
      document.getElementById("board1").innerHTML = board;
      document.getElementById("image1").innerHTML = imageChild;
    })
  }

  function doFunctionSec(){
    var ref = firebase.database().ref();
      ref.on("value", function(snapshot){
        boardsec=snapshot.child("2").child("Board").val();
        imageChildsec=snapshot.child("2").child("Image").val();
        document.getElementById("board2").innerHTML = boardsec;
        document.getElementById("image2").innerHTML = imageChildsec;
       })
  }


text:
Q: Operator precedence in typescript shorthand array notation: typeof unknown[] In puppeteer's declaration file types.d.ts, I came across the following type definition:
  export declare type EvaluateFunc<T extends unknown[]>
      = (...params: InnerParams<T>) => Awaitable<unknown>;

  export declare type InnerParams<T extends unknown[]> = {
      [K in keyof T]: FlattenHandle<T[K]>;
  };

My question is in regards to <T extends unknown[]> and the operator precedence for typeof and [] .. is T extending unknown? Or is it extending unknown[], and, if it's the latter, then is the keyof operator able to be used on type Array? If so, does typescript take this to mean 'any numeric property of an array'? (aka, array item).
Assuming it's the former, and T is extending unknown, then how does the array shorthand [] operator affect the typeof operator? Just for context, here is the definition for FlattenHandle:
export declare type FlattenHandle<T> = T extends HandleOr<infer U> ? U : never;

Sub-question: export declare -- I've taken a break from TS for half a year and now that I'm back, I'm seeing these more and more. Is it a recent addition? What are we trying to say here? That, the type exists but was not exported in the source? One of the affects of this export declare is that my IDE (PHPStorm) thinks that the class ElementHandle exists, and even appears in console.log, but, if you Console.log(ElementHandle) you will get undefined:
export declare class ElementHandle<ElementType extends Node = Element> extends JSHandle<ElementType> {
    #private;
    // ...

Thank you for your help.


text:
Q: Height of Div tags being ignored I am sure this is something stupid I'm doing, but it's been quite a while since I messed with CSS. And for the life of me I cannot figure out why the div boxes are not displaying the right height (as specified in the CSS)...and why there is that black block of space between header divs and the columns.
Any help would be VERY appreciated! I know it's pretty bare-bones, I'm just trying to get the main layout down.
Thanks for any help!!
CSS:
#container { width: 1000px; margin: 30px auto 60px;}

    h1 { text-align: center;}

    #header { height: 200 px; width: 1000 px;  background-color: #993300}
    #mcol1 { height: 600; width: 500px; float: left; background-color: #2a9c3b;}
    #mcol2 { height: 600; width: 500px; float: left; background-color: #996666;}

HTML:

 Name

Test1

Test2

Since I can't directly post pictures because I'm new, here's a link to how it's displaying: http://imgur.com/gW0vY7a
Thanks!

A: Add px to every height value:
#header { height: 200px; width: 1000px;  background-color: #993300}
#mcol1 { height: 600px; width: 500px; float: left; background-color: #2a9c3b;}
#mcol2 { height: 600px; width: 500px; float: left; background-color: #996666;}

jsfiddle

A: Not
height: 200 px;
height: 200;

but
height: 200px;

A: Try and clear the floats on mcol1 and mcol2 by using this:

 Name

Test1

Test2

           .clear{
             clear:both;
             height:0;
             line-height:1px;
           }
            #mcol1 { height: 600px; width: 500px; float: left; background-color:#2a9c3b;}
            #mcol2 { height: 600px; width: 500px; float: left; background-color: #996666;}

A: In addition you may want to add style overflow hidden to your divs especially for small divs in internet explorer
style = "overflow: hidden;"

and also you may want to download reset.css and include it in the head
<link rel = "stylesheet" type = "text/css" href = "css/reset.css"/>


text:
Q: Determine zoom level that contains all polylines in Mapbox I am visualizing movements on a map and want to set the zoom level dependent on the span of the polylines which visualize the movement. I already found an answer how to do this for markers, but I can't figure out how to get the span of the visualized data.

A: I found a way to use the solution mentioned above by including all movements to the LatLngBounds. Maybe not the most elegant solution but it works.
Builder latLngBoundsBuilder = new Builder();
for (int i = 0; i < movements.size(); i++) {
  latLngBoundsBuilder.include(movements.get(i).getPosition());
}
LatLngBounds latLngBounds = latLngBoundsBuilder.build();


text:
Q: Stored Procedure For Report In my stored procedure of sql server, below code is having issue
SELECT NULL AS s_empname
UNION
SELECT s_empname FROM ps_OFFICE

In this, I am not getting NULL as first option as it is not a string. If I pass it as:
SELECT ('NULL') AS ps_name
UNION
SELECT ps_name  ps_OFFICE

It is not working.
How can I update the first one in such a way that  NULL must be s_empname but must be shown in drop-down list of report as  'NULL' or 'No job'?

A: union and union all do not guarantee the ordering of the results.  Only an ORDER BY clause does that.
So, you should use:
SELECT s_empname
FROM (SELECT NULL AS s_empname, 1 as priority
      UNION
      select s_empname, 2 from ps_OFFICE
     ) t
ORDER BY priority;

You should probably use UNION ALL, unless you intend to remove duplicates.


text:
Q: how to export bash arrays? any workaround tips? I am using the bash version 4.2.37 at ubuntu 12.10. But since ubuntu 12.04 I am unable to export arrays in bash...
This is an example (type these lines in the command line, it is not a script):
export astr=(a "b c" d)
declare -p |grep astr
bash
echo ${astr[@]}
declare -p |grep astr

echo outputs nothing...
declare -p |grep astr outputs nothing either...
What I am looking for is an workaround, because as far I know that is considered an known bash bug.
EDIT: btw, if possible, the workaround could avoid creating temporary storage files for the array as I may run the same script simultaneously on different shells.

A: It's not a bug with bash, there's just not any safe way to put a bash array in the environment.
As for workarounds, that depends on what you're trying to achieve with exporting arrays in the first place.
One possible workaround, for some cases, is to dump the array to a file and source that file where you need it.
astr=(a "b c" d)
declare -p astr > some_file

bash -c 'source ./some_file; printf "%s\n" "${astr[1]}"'

Another workaround could be to pass the array on as arguments to the next shell.
astr=(a "b c" d)
bash -c 'astr=("$@"); printf "%s\n" "${astr[1]}"' _ "${astr[@]}"

A: Wait wait wait... I know that I'm a little late here, but this question is still relevant when we are looking for exporting arrays on google so, my workaround was:
declare -a ASTR;
export ASTR=(`echo a b c`);

# Printing all elements content
echo "${ASTR[*]}";
# Printing a position
echo "${ASTR[2]}";

It will return c once arrays first position is 0.
I hope that helps someone looking for it.
Regards


text:
Q: navbar layout with bootstrap I have recently been exploring bootstrap and I am struggling with my nav bar. The code below shows how I would like it to look, the problem arises when I resize the browser window like a mobile phone. When I click on the hotdog button it only shows me the option to add username and password but I would also like to have access to the links. In order for me to get the layout I am looking for I have used two nav bars. I think that this is my issue. How can I achieve the same layout but with only one nav bar? I would like to to see all links and password boxes when the window is small, I am also trying to get rid of the black line that shows that there is two nav bars.

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css"
    rel="stylesheet" type="text/css">
    <link href="http://pingendo.github.io/pingendo-bootstrap/themes/default/bootstrap.css"
    rel="stylesheet" type="text/css">

      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">

      <link href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css"
      rel="stylesheet" type="text/css">
      <link href="http://pingendo.github.io/pingendo-bootstrap/themes/default/bootstrap.css"
      rel="stylesheet" type="text/css">

              <button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#navbar-main">

              </button>
                  Website Name

                <form class="navbar-form navbar-right" role="search">

                    <input type="text" class="form-control" name="username" placeholder="Username">

                    <input type="text" class="form-control" name="password" placeholder="Password">

                  <button type="submit" class="btn btn-default">Sign In</button>
                </form>

              <button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#navbar-main">

              </button>

                    Home

                    Dropdown

                        Action

                        Another action

                        Something else here

                        Separated link

                        One more separated link

                    Link

                    Link

                    Link

                    Register

                    Forgot Login

A: How about something like this? The modal allows you to add more options such as "register" or "forgot password" without necessarily needing them on the nav itself. Additionally, on mobile devices, it wouldn't show two navbars and instead would collapse normally.

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
  <link href="http://pingendo.github.io/pingendo-bootstrap/themes/default/bootstrap.css" rel="stylesheet" type="text/css">

        WebSiteName

Home

Page 1

Page 2

Page 3

 Login

          <button type="button" class="close" data-dismiss="modal">×</button>

Login

          <form>

              <input type="text" class="form-control" name="username" placeholder="Username">

              <input type="password" class="form-control" name="password" placeholder="Password">

          <button type="submit" class="btn btn-default" data-dismiss="modal">Sign In</button>

      </form>

codepen.io/zanderl/pen/mVoLdY

A: Here's an example of how you can do this with one navbar. You simply create another div for your links and position them accordingly. Nothing else to it.
See working example Snippet at FullPage.

@media (min-width: 768px) {
  .navbar .lower-nav {
    padding-top: 50px;
    margin-left: -15px;
  }
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar"> Toggle navigation

      </button>
       Website Name

      <form class="navbar-form navbar-right" role="search">

          <input type="text" class="form-control" name="username" placeholder="Username">

          <input type="text" class="form-control" name="password" placeholder="Password">

        <button type="submit" class="btn btn-default">Sign In</button>
      </form>

Home

            Dropdown

Action

Another action

Something else here

Separated link

One more separated link

Link

Link

Link

Register

Forgot Login

    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
    survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing
    software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a
    galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets
    containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's
    standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
    It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the
    printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries,
    but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker
    including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled
    it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages,
    and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since
    the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in
    the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting
    industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic
    typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem
    Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
    publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer
    took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset
    sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's
    standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
    It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.


text:
Q: Adding Columns in 2D array (Python) So I am trying to add all the columns of a 2D array except for the first two columns of the array. If the sum of the row is greater than or equal to 9 and less than 12, I want the function to print the row. Here is a sample of my 2D array that is a list of lists:
[[12606.000,  74204.000,     1.000,     1.000,     1.000,     1.000,     1.000,     0.000,     0.000],
[12606.000,  105492.000,     0.000,     0.000,     0.000,     0.000,     0.000,     0.000,     1.000],
[12606.000,  112151.000,     1.000,     1.000,     0.000,     0.000,     0.000,     0.000,     0.000],
[12606.000,  121896.000,     0.000,     0.000,     0.000,     0.000,     0.000,     1.000,     0.000]]

(Some columns were deleted for formatting).
Here is my code:
def sumBinRow(A):
    """Returns the list of employees recording data for at least nine months and fewer than twelve.
    """
    for i in range(len(A)):
        for j in range(len(A[i])):
            if 9 <= sum(A[i][j+2]) <12:
                print A[i]

I keep getting a "Type Error" saying the 'int' object is not iterable.

A: Basically, you need to iterate over each list, for each list, take a slice of that list starting from 2, then sum that and do your comparison.
def sumBinRow(A):
    """Prints the list of employees recording data for at least nine months and fewer than twelve.
    """
    for row in A:
        if 9 <= sum(row[2:]) < 12:
            print row

or in 1 line cause why not :P
def sumBinRow(A):
    """Prints the list of employees recording data for at least nine months and fewer than twelve.
    """
    print [row for row in A if 9 <= sum(row[2:]) < 12]

A: You should should sum like this.
def sumBinRow(A):
    """Returns the list of employees recording data for at least nine months and fewer than twelve.
    """
    for i in range(len(A)):
        sigma = 0
        for j in range(2,len(A[i])):
            sigma += A[i][j]
            if 9 <= sigma <12:
                print A[i]

A: If you use NumPy for this task it would be simpler and much faster:
import numpy as np

a = np.array([[12606.000,  74204.000,     1.000,     1.000,     1.000,     1.000,     1.000,     0.000,     0.000],
              [12606.000,  105492.000,     0.000,     0.000,     0.000,     0.000,     0.000,     0.000,     1.000],
              [12606.000,  112151.000,     1.000,     1.000,     0.000,     0.000,     0.000,     0.000,     0.000],
              [12606.000,  121896.000,     0.000,     0.000,     0.000,     0.000,     0.000,     1.000,     0.000]])

b = a[:, 2:].sum(axis=1)
check = (b >= 9) & (b < 12)
print(a[check])

A: The problem is that you are trying to sum over something that is not an array:
if 9 <= sum(A[i][j+2]) <12: // A[j][j+2] is not iterable, it is an int

Instead you want to use the slice function:
if 9 <= sum(A[i][2:]) <12:  // This will sum sum all but first two elements

A more pythonic way would be to use a list comprehension. This can be done with a single line of code:
A = [[12606, 74204 , 1, 1, 1, 1, 1, 0, 0],
     [12606, 105492, 0, 0, 0, 0, 0, 0, 1],
     [12606, 112151, 1, 1, 0, 0, 0, 0, 0],
     [12606, 121896, 0, 0, 0, 0, 0, 1, 0]]

print [row for row in A if 9 <= sum(row[2:]) < 12]


text:
Q: How to center-align image link and make it clickable only on image not overflowing area? I created a image link:-

    .post-image {
      margin: 20px auto;
      display: block;
      max-width: 100%;
      height: auto;
    }

But the link is clickable outside the image also.
How can I center-align the image and also make the link clickable only on the image not outside the image (overflowing area).
Centered image

A: Not sure if this is acceptable, but I use {display: inline-block}
Edit: Just noticed you want the image to be centered too. Edited code to reflect

body {
  text-align: center
}
.post-image {
  margin: 0 auto;
  display: inline-block;
  max-width: 100%;
  height: auto;
}

A: Add display: inline; to image .post-image to get it centered and add text-align: center; to tha parent of a tag

div {
  margin: 0 auto;
  text-align: center;
}
a {
  margin: 0px auto;
}
.post-image {
  margin: 20px auto;
  display: inline;
  max-width: 100%;
  height: auto;
}

A: Another Way:
Simply use Position:Absolute. And if you have any other elements in the page. position:absolute may affect their visibility.

.post-image {
  max-width: 100%;
  position: absolute;
  margin: 20px auto;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

A: You can add a div before href tag and add text-align: center; on this div. like:
.post-image {
      margin: 20px auto;
      display: inline-block;
      max-width: 100%;
      height: auto;
}


text:
Q: PHP Cron Job issue with Namespace I'm having some trouble with a cron job and namespace, I'm trying to implement this function which works great!
https://github.com/neitanod/forceutf8
http://www.irook.com/test/test.php
<?php

error_reporting(-1);
ini_set('display_errors', 1);

require_once('/home/irookcom/public_html/test/encoding.php');
use \ForceUTF8\Encoding;  // It's namespaced now.

echo Encoding::fixUTF8("Fédération Camerounaise de Football\n");

?>

This works fine when called from a browser, but when I add a cron job:
/ramdisk/bin/php5 /home4/irookcom/public_html/test/test.php
I get these errors:
[14-Nov-2015 09:17:01] PHP Warning:  Unexpected character in input:  '\'     (ASCII=92) state=1 in /home4/irookcom/public_html/test/test.php on line 7
[14-Nov-2015 09:17:01] PHP Parse error:  syntax error, unexpected T_STRING,     expecting T_CONSTANT_ENCAPSED_STRING or '(' in     /home4/irookcom/public_html/test/test.php on line 7

Is there a work around for the use function that the cron job would accept?

A: Yes, the PHP version was it.  The server was running 5.4 for web calls but 5.2 for the cron calls - changed it to force 5.4, and it works like a charm!


text:
Q: Debian - Boot from USB I currently have Debian 7.0 installed on my laptop (HP Pavilion dv9700). I would now like to install Arch instead. I wrote the Arch ISO to a USB drive, but when I start up my computer, it automatically loads to Debian.
I tried changing the boot order in the BIOS, but that didn't help, and there doesn't seem to be an option in the BIOS (PhoenixBIOS Setup Utility) to simply choose media to boot from. When setting USB Disk or USB diskette on key as the highest priority for booting,  get the message "Remove disks or other media. Press any key to restart", which brings me to the GRUB loader when I remove the usb and press any key.
I found this which is for booting Xubuntu while having Ubuntu installed, but I don't know how I'd apply that to Arch and Debian. How would I go about booting from the USB?

A: What method did you use to clone the ArchLinux ISO to your USB drive? The ISO is already 'hybridized' via isohybrid so you can just use dd.
In Debian, install qemu and test if the USB drive is bootable.
qemu-system-i386 -hda /dev/sdX where 'sdX' is the USB drive.
You should also note that the ArchLinux LiveCD uses syslinux as its bootloader instead of GRUB.
Finally, if this is a one-time installer then you could use GRUB2's ISO boot and boot the LiveCD installer that way.


text:
Q: How to Merge this Data-frames in Python Pandas? I have 3 Data-frames of Following Shapes:
(34376, 13), (52389, 28), (16531, 14)
This is the First Dataframe which we have:

This is the Second Dataframe which we have:

This the Third Dataframe which we have:

Now, as I have mentioned the shapes of all the Dataframes, the main task is we have to merge this on the Accession Number \
DF1-has the exact 34376 Accession which we want.
DF2- has around 28000 Accession which we want. This basically means that the remaining Accession of that table we don't want.
DF3- has around 9200 Accession which we want
How can we, merge all these 3 DF's on Accession Number, so that we get the extra columns of DF2,DF3 merged with DF1 on Accession Number. Also, we can see that DF2 has 52389 columns, so if there are same Accession Numbers repeated in DF2, we still want to merge it, but the rows of DF1 should be repeated while merged with the extra rows of DF2 and same with DF3. The Accession where no values are available in DF2/DF3 but present in DF1, the rows should become Null.

A: You can simply use the pandas merge function
pd.merge(pd.merge(df1,df2,on='ACCESSION_NUMBER'),df3,on='ACCESSION_NUMBER')

or
df1.merge(df2,on='ACCESSION_NUMBER').merge(df3,on='ACCESSION_NUMBER')

or
You could use the reduce class from functools library
reduce(lambda x,y: pd.merge(x,y, on='ACCESSION_NUMBER', how='outer'), [df1, df2, df3])


text:
Q: How do I replace a string with a newline using a bash script and sed? I have the following input:
Value1|Value2|Value3|Value4@@ Value5|Value6|Value7|Value8@@ Value9|etc...

In my bash script I would like to replace the @@  with a newline. I have tried various things with sed but I'm not having any luck:
line=$(echo ${x} | sed -e $'s/@@ /\\\n/g')

Ultimately I need to parse this whole input into rows and values.  Maybe I am going about it wrong.  I was planning to replace the @@  with newlines and then loop through the input with setting IFS='|' to split up the values.  If there is a better way please tell me, I am still a beginner with shell scripting.

A: I recommend using the tr function
echo "$line" | tr '@@' '\n'

For example:
[itzhaki@local ~]$ X="Value1|Value2|Value3|Value4@@ Value5|Value6|Value7|Value8@@"
[itzhaki@local ~]$ X=`echo "$X" | tr '@@' '\n'`
[itzhaki@local ~]$ echo "$X"
Value1|Value2|Value3|Value4

 Value5|Value6|Value7|Value8

A: Finally got it working with:
sed 's/@@ /'\\\n'/g'

Adding the single quotes around \\n seemed to help for whatever reason

A: If you don't mind to use perl:
echo $line | perl -pe 's/@@/\n/g'
Value1|Value2|Value3|Value4
 Value5|Value6|Value7|Value8
 Value9|etc

A: This will work
sed 's/@@ /\n/g' filename

replaces @@ with new line

A: Using pure BASH string manipulation:
eol=$'\n'
line="${line//@@ /$eol}"

echo "$line"
Value1|Value2|Value3|Value4
Value5|Value6|Value7|Value8
Value9|etc...

A: How about:
for line in `echo $longline | sed 's/@@/\n/g'` ; do
    $operation1 $line
    $operation2 $line
    ...
    $operationN $line
    for field in `echo $each | sed 's/|/\n/g'` ; do
        $operationF1 $field
        $operationF2 $field
        ...
        $operationFN $field
    done
done

A: This wraps up using perl to do it, and gives some simple help.
$ echo "hi\nthere"
hi
there

$ echo "hi\nthere" | replace_string.sh e
hi
th
re

$ echo "hi\nthere" | replace_string.sh hi

there

$ echo "hi\nthere" | replace_string.sh hi bye
bye
there

$ echo "hi\nthere" | replace_string.sh e super all
hi
thsuperrsuper

replace_string.sh
#!/bin/bash

ME=$(basename $0)
function show_help()
{
  IT=$(cat <<EOF

  replaces a string with a new line, or any other string,
  first occurrence by default, globally if "all" passed in

  usage: $ME SEARCH_FOR {REPLACE_WITH} {ALL}

  e.g.

  $ME :       -> replaces first instance of ":" with a new line
  $ME : b     -> replaces first instance of ":" with "b"
  $ME a b all -> replaces ALL instances of "a" with "b"
  )
  echo "$IT"
  exit
}

if [ "$1" == "help" ]
then
  show_help
fi
if [ -z "$1" ]
then
  show_help
fi

STRING="$1"
TIMES=${3:-""}
WITH=${2:-"\n"}

if [ "$TIMES" == "all" ]
then
  TIMES="g"
else
  TIMES=""
fi

perl -pe "s/$STRING/$WITH/$TIMES"


text:
Q: How can I prefix a file name with it's parent directory using Gulp? I am using the following hierarchy for a project:
src/img/de-de/file1.jpg, file2.gif....
src/img/en-gb/file1.jpg...
src/img/it-it/etc

There are global images inside of the img folder, and localised files in each of the mentioned sub-directories.
I am using the gulp-rename plugin to add a custom prefix (GulpTest_) to file names. However, I also want to add the sub-directory folder name to any localised files that are stored inside.
Example:
src/img/de-de/file1.jpg would be renamed GulpTest_de-de_file1.jpg
I am currently using the following code to source each of the files in the sub-directories and add the GulpTest prefix:
// Image Rename Task
gulp.src('.src/img/*/*')
.pipe(rename({prefix: "GulpTest"}))
.pipe(gulp.dest("./dst/" + )

How can I amend my task so that it it concatenates 'prefix + sub-directory + file.jpg'?
Thanks

A:     .pipe(rename(function (path) {
        console.log('path', path);
        if (path.extname) {
            if (path.dirname === '.') {
                path.dirname = '';
            }
            path.basename = 'GulpTest_' + path.dirname + '_' + path.basename;
            path.dirname = '';
            console.log('path-new', path);
        }
    }))
    .pipe(gulp.dest('dst/'));


text:
Q: Odoo adds "postmaster" prefix to sender address Apparently, ODOO does add a "postmaster" prefix to sender address of outgoing emails (e.g. "postmaster-[user]@[domain]"). How can I suppress this behaviour?

A: Removing all catchall parameters (mail.catchall.domain and mail.catchall.alias) under "Settings" -> "Technical" -> "Parameters" -> "System Parameters" does the trick.

A: I found a mistake in the source code. It is using mail.bounce.alias instead of mail.catchall.alias
def _get_default_bounce_address(self, cr, uid, context=None):
    '''Compute the default bounce address.

    The default bounce address is used to set the envelop address if no
    envelop address is provided in the message.  It is formed by properly
    joining the parameters "mail.catchall.alias" and
    "mail.catchall.domain".

    If "mail.catchall.alias" is not set it defaults to "postmaster-odoo".

    If "mail.catchall.domain" is not set, return None.

    '''
    get_param = self.pool['ir.config_parameter'].get_param
    postmaster = get_param(cr, SUPERUSER_ID, 'mail.bounce.alias',
                            default='postmaster-odoo',
                            context=context,)
    domain = get_param(cr, SUPERUSER_ID, 'mail.catchall.domain', context=context)
    if postmaster and domain:
        return '%s@%s' % (postmaster, domain)

So if you fill the mail.bounce.alias should work. Anyway I had to modify a couple of things more in the source code to make it work as I wanted:
def send_email(self, cr, uid, message, mail_server_id=None, smtp_server=None, smtp_port=None,
               smtp_user=None, smtp_password=None, smtp_encryption=None, smtp_debug=False,
               context=None):

    smtp_from = self._get_default_bounce_address(cr, uid, context=context)
    if not smtp_from:
        smtp_from = message['From']   # this is only for the smtp
    assert smtp_from, "The Return-Path or From header is required for any outbound email"

    # [...]

You can also modify the email_from in the build_email method. But you should fill the parameter email_from in the Odoo configuration file
def build_email(self, email_from, email_to, subject, body, email_cc=None, email_bcc=None, reply_to=False,
           attachments=None, message_id=None, references=None, object_id=False, subtype='plain', headers=None,
           body_alternative=None, subtype_alternative='plain'):

    email_from = tools.config.get('email_from')

    # [...]

I think I didn't forget anything


text:
Q: Rails 4 - All nested polymorphic comments showing on every page, not on individual pages I'm in the process of learning Rails and trying to create a site with nested polymorphic comments.
I have been following this tutorial http://www.tweetegy.com/2013/04/create-nested-comments-in-rails-using-ancestry-gem/ as well as some RailsCasts (262-trees-with-ancestry and 154-polymorphic-association).
I have successfully managed to create nested polymorphic comments (when I check rails console for each comment).  However, the problem I'm having is outputting the comments.  They all show up on every resources' show page, not on the relevant show page. In other words, all of the comments are showing on /videos/1 and videos/2 and lessons/1 and lessons/3 (the same comments are showing on every page).
I suspect my problem is in the comments_helper.rb or /lib/commentable.rb file, however I haven't had any luck debugging the problem.
Routes
config/routes.rb
  devise_for :users

  resources :videos do
    resources :comments
  end

  resources :lessons do
    resources :comments
  end

Controllers
app/controllers/comments_controller.rb
class CommentsController < ApplicationController
  def new
    @parent_id = params.delete(:parent_id)
    @commentable = find_commentable
    @comment = Comment.new( :parent_id => @parent_id,
                            :commentable_id => @commentable.id,
                            :commentable_type => @commentable.class.to_s)
  end

  def create
    @commentable = find_commentable
    @comment = @commentable.comments.build(comment_params)
    @comment.user_id = current_user.id
    if @comment.save
      flash[:notice] = "Successfully created comment."
      redirect_to @commentable
    else
      flash[:error] = "Error adding comment."
    end
  end

  private
  def find_commentable
    params.each do |name, value|
      if name =~ /(.+)_id$/
        return $1.classify.constantize.find(value)
      end
    end
    nil
  end

  def comment_params
    params.require(:comment).permit(:body, :parent_id, :commentable_id, :commentable_type)
  end

end

app/controllers/lessons_controller.rb
class LessonsController < ApplicationController
  include Commentable
...
end

app/controllers/videos_controller.rb
class VideosController < ApplicationController
  include Commentable
...
end

Models
app/models/comment.rb
class Comment < ActiveRecord::Base
    has_ancestry
    belongs_to :user
    belongs_to :commentable, polymorphic: true
end

app/models/lesson.rb
class Lesson < ActiveRecord::Base
    has_many :comments, :as => :commentable, :dependent => :destroy
end

app/models/video.rb
class Video < ActiveRecord::Base
    has_many :comments, :as => :commentable, :dependent => :destroy
end

app/models/user.rb
class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  has_many :comments, :as => :commentable, :dependent => :destroy
end

Helpers
app/helpers/comments_helper.rb
module CommentsHelper
  def nested_comments(comments)
    comments.map do |comment, sub_comments|
      content_tag(:div, render(comment), :class => "media media-nested")
    end.join.html_safe
  end
end

Lib
/lib/commentable.rb
require 'active_support/concern'

module Commentable
  extend ActiveSupport::Concern

  included do
    before_filter :comments, :only => [:show]
  end

  def comments
    @commentable = find_commentable
    @comments = @commentable.comments.arrange(:order => :created_at)
    @comment = Comment.new
  end

  private

  def find_commentable
    return params[:controller].singularize.classify.constantize.find(params[:id])
  end

end

Schema
create_table "comments", force: true do |t|
    t.text     "body"
    t.integer  "user_id"
    t.integer  "commentable_id"
    t.string   "commentable_type"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "ancestry"
  end

  add_index "comments", ["ancestry"], name: "index_comments_on_ancestry"

Views
Lessons & Views show.html.erb

  <%= nested_comments @comments %>
  <%= render "comments/form" %>

app/views/comments/_form.html.erb
<%= form_for [@commentable, @comment] do |f| %>
    <%= f.hidden_field :parent_id %>

        <%= f.label :body, "New comment" %>

    <%= f.text_area :body, :rows => 4 %>

       <%= f.submit "Post Comment" %>

<% end %>

app/views/comments/_comment.html.erb

<%= comment.user.username %>

    <%= comment.created_at.strftime('%b %d, %Y at %H:%M')  %>

    <%= simple_format comment.body %>

    <%= link_to "Reply", new_polymorphic_path([@commentable, Comment.new], :parent_id => comment) %>

  <%= nested_comments comment.children %>

Any feedback or ideas would be much appreciated.  Thanks ;)

A: Figured out a solution, however now child comments appear twice.
show.html.erb

    <%= nested_comments @lesson.comments %>
    <%= render "comments/form" %>


text:
Q: Histogramming boolean numpy arrays by giving each array a unique label I have a large sample (M) of boolean arrays of length 'N'. So there are 2^N unique boolean arrays possible.
I would like to know how many arrays are duplicates of each other and create a histogram.
One possibility is to create a unique integer (a[0] + a[1]*2 + a[3]*4 + ...+a[N]*2^(N-1)) for each unique array and histogram that integer.
But this is going to be O(M*N). What is the best way to do this?

A: numpy.ravel_multi_index is able to do this for you:
arr = np.array([[True, True, True],
              [True, False, True],
              [True, False, True],
              [False, False, False],
              [True, False, True]], dtype=int)
nums = np.ravel_multi_index(arr.T, (2,) * arr.shape[1])
>>> nums
array([7, 5, 5, 0, 5], dtype=int64)

And since you need a histogram, use
>>> np.histogram(nums, bins=np.arange(2**arr.shape[1]+1))
(array([1, 0, 0, 0, 0, 3, 0, 1], dtype=int64),
 array([0, 1, 2, 3, 4, 5, 6, 7, 8]))

Another option is to use np.unique:
>>> np.unique(arr, return_counts=True, axis=0)
(array([[0, 0, 0],
        [1, 0, 1],
        [1, 1, 1]]),
 array([1, 3, 1], dtype=int64))

A: With vectorized operation, the creation of a key is much more faster than a[0] + a[1]x2 + a[3]x4 + ...+a[N]*2^(N-1). I think that's no a better solution... in any case you need to almost "read" one time each value, and this require MxN step.
N = 3
M = 5
sample = [
    np.array([True, True, True]),
    np.array([True, False, True]),
    np.array([True, False, True]),
    np.array([False, False, False]),
    np.array([True, False, True]),
]

multipliers = [2<<i for i in range(N-2, -1, -1)]+[1]

buckets = {}
buck2vec = {}
for s in sample:
    key = sum(s*multipliers)
    if key not in buckets:
        buckets[key] = 0
        buck2vec[key] = s
    buckets[key]+=1

for key in buckets:
    print(f"{buck2vec[key]} -> {buckets[key]} occurency")

Results:
[False False False] -> 1 occurency
[ True False  True] -> 3 occurency
[ True  True  True] -> 1 occurency


text:
Q: Serving single HTTP request with multiple threads Angular 4 application sends a list of records to a Java spring MVC application that has been deployed in Websphere 8 Servlet container. The list is then inserted into to a temp table. After the batch insert, a procedure call is made in order to do some calculations and return  results. Depending on the size of the list that was inserted into temp table it may take anywhere between: 3000ms( N ~ 500 ), 6000ms( N ~ 1000 ), 50,000+ms ( N > 2000 ).
My asendach would be to create chunks of data and  simultaneously send them to database for processing. After threads (Futures) return results I would aggregate them and return back to the client. To sum up, I would split a synchronous call into multiple asynchronous processes(simultaneously executed) and return back to the client over the same thread that initiated HTTP call - landed into my controller.
Everything would be fine and I would not be asking this questions if a more experienced colleague of mine was not strongly disagreeing with this approach. His reasoning is that using this approach is prone to exceptions due to thread interrupts / timeouts / semaphores and so on. Hi is going as far as saying that multithreading should be avoided within a web container because it can crash the Servlet container in case it runs out of threads.
He proposes that we should have the browser send multiple AJAX requests and aggregates/present data in chunks.
Can you please help me understand which approach is better and why?

A: I would say that your approach is much better.

*

*Threads created by application logic aren't application container threads and limited only by operating system. While each AJAX request uses a thread from application container. So the second approach reduces throughput and increases the possibility of reaching application container limit while and the first one not. Performance also should be considered because it's much cheaper to create a thread than to send a request over network. Plus each network requests uses additional resources for authentication/authorization/encryption etc.

*It's definetely harder to write correct multithread code and it can easily prone to errors. However it shouldn't stop you from doing it because concurrency can significantly increase your performance. It's pretty straightforward to handle interrupts and timeouts using Future and you for sure don't need semaphores here.

*Exposing this logic to client looks like breaking of encapsulation. Imagine that you use rest api which forces you to send multiple request by splitting you data in chunks. What chunk size should i use? How to deal with timeouts/interrupts? How many requests should i sent? etc. You will have almost the same challenges in both approaches, but it's much easier to deal with them using specially designed for this libraries like ExecutorService and Future.