text:
Q: Powershell v5 Get-Content (Chinese file names) amending. Filename/path not found or excluded I have been trying to figure this out for the past hour. I have Chinese named filenames, however im using powershell version: 5.1.22000.653. If I change it to test.lua it works just fine. However, upon running. it just tells me file is not able to be found or has been excluded. Only real work around I have found is amending the file name to temp 0-9 and re amending the file name afterwards manually as again not able able to read the Chinese file names. Only reason im using get child item for each is due to file names changing with -2 or -10 etc upon new updates. but the info inside said file names will always be static.
& "$env:windir\system32\chcp.com" 936
Get-ChildItem './*.lua' -Recurse | ForEach {
     (Get-Content $_) | ForEach  {$_ -Replace "Lua_Config_ZC_Out = true", "Lua_Config_ZC_Out = false" } | Set-Content $_
}

or
$PSDefaultParameterValues['*:Encoding'] = 'utf8'
& "$env:windir\system32\chcp.com" 936
$configFiles = Get-ChildItem . *lua -rec
foreach ($file in $configFiles)
{
    (Get-Content $file.PSPath)
    Foreach-Object { $_ -replace "Lua_Config_ZC_Out = true", "Lua_Config_ZC_Out = false" } |
    Foreach-Object { $_ -replace "Lua_Config_ZC_Open = 1", "Lua_Config_ZC_Open = 0" } |
    Foreach-Object { $_ -replace "Config_State = 1", "Config_State = 0" } |
    Foreach-Object { $_ -replace "Lua_Config = {xz = 50, xy = 10}", "Lua_Config = {xz = 65, xy = -1}" } |
    Foreach-Object { $_ -replace "Lua_Config_HD_Re = 1", "Lua_Config_HD_Re = 0" } |
    Foreach-Object { $_ -replace "admin_config = false", "admin_skill = true" } |
    Set-Content $file.PSPath
}
pause

same with both variations and just to test Rename-Item -Path "E:\test\[副]混牢.lua" -NewName "0.lua" result in Error:
PS E:\test> E:\test\Test.ps1
Active code page: 936

Rename-Item : Cannot rename because item at 'E:\test\[副本]混沌地牢.lua' does not exist.
At E:\test\Test.ps1:4 char:1
+ Rename-Item -Path "E:\test\[副本]混沌地牢.lua" -NewName "0.lua"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Get-Content : An object at the specified path Microsoft.PowerShell.Core\FileSystem::E:\test\[副]混牢.lua does not exist, or has been filtered by the -Include or -Exclude parameter.
At E:\test\Test.ps1:6 char:6
+     (Get-Content $file.PSPath)
+      ~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (System.String[]:String[]) [Get-Content], Exception
    + FullyQualifiedErrorId : ItemNotFound,Microsoft.PowerShell.Commands.GetContentCommand

Set-Content : An object at the specified path Microsoft.PowerShell.Core\FileSystem::E:\test\[副]混牢.lua does not exist, or has been filtered by the -Include or -Exclude parameter.
At E:\test\Test.ps1:14 char:5
+     Set-Content $file.PSPath
+     ~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (System.String[]:String[]) [Set-Content], Exception
    + FullyQualifiedErrorId : ItemNotFound,Microsoft.PowerShell.Commands.SetContentCommand

Press Enter to continue...:


text:
Q: Identify if sensor works when screen is OFF in android I want to identify if the Sensor used for Activity Recognition works when device screen is off.
Activity Recognition stops as soon as Device screen is turned OFF. I searched for it and found that sensor does not work when screen is OFF to save the battery.
So there is a method to identify such sensors by isWakeUpSensor(), but isWakeUpSensor() is applicable from API 21.
How can I make it work on API 14 onward. Identify sensor before starting Activity Recognition.
Same as application "Moves" does

A: After a little bit of searching I found this documentation which states

Up to KitKat, whether a sensor was a wake-up or a non-wake-up sensor was dictated by the sensor type: most were non-wake-up sensors, with the exception of the proximity sensor and the significant motion detector.

On the other hand, the significant motion detector page says

Implement only the wake-up version of this sensor.
  getDefaultSensor(SENSOR_TYPE_SIGNIFICANT_MOTION) returns a non-wake-up sensor

which confuses me. It is, however, a composite sensor, which means that it's wake-up-ness depends on the underlying actual sensors (I would imagine).
More research into this suggests that significant motion detector was added in Android 4.3 (API 18), so you're left with the proximity sensor for available wake-up sensors in API 14 devices, which is primarily intended to be used to turn the screen on and off when making phone calls.
Seems to me like there is no way to do exactly what you have in mind without a wake lock.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Beautiful Soup doesn't find first XML tag Question already appeared Beautiful Soup Can't Find the First Tag (XML) but wasn't resolved.
I'm facing the same problem, and I cannot see why this easy task cannot be resolved by a simple find_all <sentence/> tags function using Python:
for tag in items.find_all('sentence'):
    print(tag)

It remains just empty. Any idea why this is occurring?


text:
Q: Query Optimization for my code in Oracle SQL Here is my code:
    select
    (case when c.yr = 2019 and c.mon = 10 then 'October 2019'
    when c.yr = 2019 and c.mon = 11 then 'November 2019'
    when c.yr =2019 and c.mon = 12 then 'December 2019' end) as dae
    from (
          select substr(d,-4,4) as yr, substr(d,1,2) as mon
          from
          (select '10/11/2019' as d from dual)  )c;
`

So I don't want to hard code the dates for the next 5 years, Is there a function that makes this easier.
Here is the Sample Input I want to try
10/11/2019
11/11/2019
12/11/2019
01/11/2020

Expected Output
October 2019
November 2019
December 2019
January 2020

A: You could use to_date() to turn your string to a date, and then convert it back to a string in the desired format with to_char():
to_char(to_date(d, 'mm/dd/yyyy'), 'Month yyyy')

Demo on DB Fiddle:
with t as (
    select '10/11/2019' d from dual
    union all select '11/11/2019' from dual
    union all select '12/11/2019' from dual
    union all select '01/11/2020' from dual
)
select to_char(to_date(d, 'mm/dd/yyyy'), 'Month yyyy') new_dt from t

| NEW_DT         |
| :------------- |
| October   2019 |
| November  2019 |
| December  2019 |
| January   2020 |

A: Use connect by to generate as many dates as you want.  Here the gen_dates CTE starts with your start_date and returns a total of 4 months per your example. To increase the number of months to generate, increase the number 4 to a higher number.
with gen_dates(date_in) as (
  select add_months('11-OCT-2019', level -1) date_in
  from dual
  connect by level <= 4
)
select date_in, to_char(date_in, 'Month yyyy') date_out
from gen_dates;

DATE_IN   DATE_OUT
--------- --------------
11-OCT-19 October   2019
11-NOV-19 November  2019
11-DEC-19 December  2019
11-JAN-20 January   2020

4 rows selected.


text:
Q: Storing resultant cell value from an addition and then adding it to new results every time I am creating a model in Excel in which a cell computes the sum of two cells and keeps adding to the value every time the two cells on which it is dependent change values. For example,
If,
A + B = C
Then,
Instance 1: -> 5 + 5 = 10
Instance 2: -> 4 + 3 = 17
Instance 3: -> 2 + 3 = 22
and so on...
I believe this can be achieved through a VB script.

A: you only need to put the following code in the worksheet code pane:
Private Sub Worksheet_Change(ByVal Target As Range)
    If Intersect(Range("A1:A2"), Target) Is Nothing Then Exit Sub
    Range("B1") = Range("B1") + WorksheetFunction.sum(Range("A1:A2"))
End Sub

of course you have to change:

*

*all "A1:A2" occurrences to your actual cells to sum address

*all "B1" occurrences to your actual cell holding the running sum address

A: Hold the running total in a Public variable (total). Initialize this as the workbook opens, using the workbook_open event, to the sum of the two cells of interest. Then use a worksheet_change event to monitor changes to those two cells and, if either changes, add their new value to the existing value of total. I have used cell C1 to show the running total.
In a standard module:
Option Explicit

Public total As Long
Public targetCell As Range

In the ThisWorkbook code pane
Option Explicit

Private Sub Workbook_Open()

    With ThisWorkbook.Worksheets("Sheet1")

        Set targetCell = .Range("C1")

        total = Application.WorksheetFunction.Sum(.Range("A1:B1"))
        targetCell = total

    End With

End Sub

In the worksheet code pane where the cells to monitor are
Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    If Not Application.Intersect(Target, Range("A1")) Is Nothing Then
        total = total + Target
        targetCell = total
    End If

    If Not Application.Intersect(Target, Range("B1")) Is Nothing Then
        total = total + Target
        targetCell = total
    End If

End Sub

Or correctly do what @DisplayName has done! I wrote this initially for a Debug.Print of total (not writing to cell) and forgot to re-factor.


text:
Q: Ctrl + Shift being swallowed I've noticed today that something is capturing ctrl+shift intermittently with Ubuntu 20.04.4. I've discovered it because it looks like 75% of the time that my application is being unfocused (and hence the caret disappearing). This is affecting me in Sublime Text and VSCode and is quite frustrating.
Does anyone know how I can track down what the cause is, as I'm not really sure where to look to diagnose? I'm not sure of anything obvious that I've changed, though I did dabble with changing the workspace settings in Gnome Tweaks the other day.
Below is an example where a popup is appearing correctly, but then on a number of presses the caret disappears and nothing happens :(

I've confirmed that this isn't a fault with the keyboard by testing on another device. This exhibits no problems. I've also confirmed that this is not unique to the keyboard, as the built in laptop keyboard has the same problem.
Update
I have discovered something interesting. The problem is not intermittent, but is dependent on the order of key presses.
If I press ctrl then shift then f, then my search will popup correctly (in whatever app I'm in, e.g. Sublime, VSCode, Terminal).
I've noticed the terminal renders a ☐ when I press ctrl and then changes back to a ■ when I press shift.

If I press shift then ctrl - at that point the cursor changes in
a different way, to a ☐, and pressing f won't do anything.


text:
Q: How can I write to a text file I got reading from a text file line by line working - but I need to write to a text file.  I need to write over it really but whatever I try it doesn't seem to work.
I have an existing text file with the value "board1" in it and I need to change that on a button click to board10.
Here is what I'm trying at the moment.
String sdcard = Environment.getExternalStorageDirectory().getAbsolutePath();

try {
    FileWriter filenew = new FileWriter(sdcard + "/multi10/default.cfg");
    BufferedWriter bw = new BufferedWriter(filenew);
    bw.write("board12");
    bw.close();
}
catch (IOException e) {
    //You'll need to add proper error handling here
}

if someone could help me I'd really appreciate it!
Thanks

A: With the little description you have given , I would say, Check the permission in AndroidManifest file for this.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


text:
Q: Run piped commands with eval I have the following command line to check free space of a file system:
fs_used=`df -h /u01 | sed '1d' | sed '1d' | awk '{print $4}' | cut -d'%' -f1`

It works fine.  It returns the percentage of the used space on the file system (without the % symbol).
Now I need to make it variable and run it with the eval command.  I tried the following but it doesn't work (exit with df: invalid option -- 'd')
df_cmnd="df -h $fs1 | sed '1d' | sed '1d' | awk '{print $4}' | cut -d'%' -f1"
fs_used=eval $df_cmnd

The problem, I guess, is that eval cannot run piped commands.  Is that true?
is there any workaround or alternative to make this code run?

A: Backslash-escape the $, and use $():
#              V                                         V
df_cmnd="df -h \$fs1 | sed '1d' | sed '1d' | awk '{print \$4}' | cut -d'%' -f1"
fs_used=$(eval "$df_cmnd")
#       ^^               ^

This will use the value of fs1 at the time you eval.
But, in reality, please don't use eval!  Make it a shell function instead:
df_cmnd(){
    df -h "$1" | sed '1d' | sed '1d' | awk '{print $4}' | cut -d'%' -f1
}
fs_used=$(df_cmnd /u01)

Then you don't have to worry about escaping.
Explanation
Look at how bash interprets your df_cmnd assignment:
$ df_cmnd="df -h $fs1 | sed '1d' | sed '1d' | awk '{print $4}' | cut -d'%' -f1"
$ echo $df_cmnd
df -h | sed '1d' | sed '1d' | awk '{print }' | cut -d'%' -f1
#    ^                                   ^

In my case, fs1 was empty, so I just got df -h for the df part.  In your case and mine, bash replaced $4 with its value, here, empty since I wasn't running in a script with four arguments.  Therefore, awk will print the whole line rather than just the fourth field.

A: I had a legitimate need for eval-ing a string: a helper scripts runs a complicated sequence of pipes with double-quoting (e.g. --json-override='"key": "value"'), 460+ characters long. But when I run it with --noop, I want to see the command that would be executed, in a copy-pasteable form for manual execution. I came up with this:
echo_eval () {
    cmd=$(cat)
    if ((noop)); then
        echo "$cmd"
    else
        eval "$cmd"
    fi
}

foo () { for arg; do echo "[$arg]"; done; }

echo_eval <<EOF
foo 1 2 "3 4" '"5 6"' " 7 " "\"8 9\"" | tac
EOF
exit 1

The main purpose of the here-document is to skip all the pitfalls of using the ' and " quotes in an already ' or "-quoted string (pain and suffering).
While I haven't tested it extensively, it seems to hit the relevant check-boxes, like pipes, quoting, quoting space-containing arguments, preserving quoted quotes, escaped quotes, leading/trailing space in arguments, etc.:
["8 9"]
[ 7 ]
["5 6"]
[3 4]
[2]
[1]

When noop is true, I get:
foo 1 "2" "3 4" '"5 6"' " 7 " "\"8 9\"" | tac

which is the command verbatim, copy-pasteable for manual execution and yielding the same output.
We can also use <<'EOF' to disable substitution of any $s before echo_eval, but if any variable/command substitution does need to happen before calling echo_eval, we have to use <<EOF and escape all $s that shouldn't be evaluated before.

Having said all this, I'd gladly (a) hear if there are pitfalls (apart from the $ mentioned above) and (b) see a better solution to the problem if there is one.


text:
Q: Primitive polynomial over $GF(2^n)$ with $n>1$ I need at least two primitive polynomials over $GF(2^n)$ (with $n>1$). All the articles I've found only primitive polynomials over $GF(p)$, never over $GF(p^n)$.
Does it exist some tables of such polynomials or algorithms generating them?

A: YES.
i've tried this on SAGE witch kind of work
K.<a>=GF (4)
R.<x>=K[]
V = R.irreducible_element(5);V
V.is_primitive();

and it gave me
x^5 + x^4 + (a + 1)*x^3 + a*x^2 + x + a + 1

of cours 'a' is a root of
x^2 + x + 1


text:
Q: how to change scalability in xml file This is my app in screen size 5.0, and 4.0.How can I change scales in the same way everywhere.
5.0

4.0

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/background"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv_sprawdz"
        android:layout_width="match_parent"
        android:layout_height="225dp"
        android:layout_marginTop="15dp"
        android:gravity="center_horizontal"
        android:text="Wybierz dzień"
        android:textAlignment="center"
        android:textColor="@color/White"
        android:textSize="18sp"
        android:textStyle="italic" />

    <LinearLayout

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="15dp"
        android:background="@drawable/bg_celen">

        <CalendarView

            android:id="@+id/calendarView"
            android:layout_width="350dp"
            android:layout_height="537dp">

        </CalendarView>
    </LinearLayout>

</LinearLayout>

A: This is a common question. Please read below which i extracted from Android Developer Docs

To ensure that your layout is flexible and adapts to different screen
  sizes, you should use "wrap_content" and "match_parent" for the width
  and height of most view components, instead of hard-coded sizes.
"wrap_content" tells the view to set its size to whatever is necessary
  to fit the content within that view.
"match_parent" makes the view expand to as much as possible within the
  parent view.
For example:
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/lorem_ipsum" />

Although the actual layout for this view depends on other attributes
  in its parent view and any sibling views, this TextView intends to set
  its width to fill all available space (match_parent) and set its
  height to exactly as much space is required by the length of the text
  (wrap_content). This allows the view to adapt to different screen
  sizes and different lengths of text.

And  further more you can use different layouts for different screen sizes as described below.

You can provide screen-specific layouts by creating additional
  res/layout/ directories—one for each screen configuration that
  requires a different layout—and then append a screen configuration
  qualifier to the layout directory name (such as layout-w600dp for
  screens that have 600dp of available width).
These configuration qualifiers represent the visible screen space
  available for your app UI. The system takes into account any system
  decorations (such as the navigation bar) and window configuration
  changes (such as when the user enables multi-window mode) when
  selecting the layout from your app.

 res/layout/main_activity.xml # For handsets (smaller than 600dp available Width)
 res/layout-w600dp/main_activity.xml # For 7" tablets
 or any screen with 600dp # available width (possibly landscape handsets)


text:
Q: Combine rows with instruction from separate list Is there a way to combine (SUM) rows with unique ID (column) numbers by specifying the ID numbers in a list and then make MYSQL combine rows in a table according to the specification in the list?
The data in the database I use change frequently changed but the customer ID that needs to be combined remains the same so it would be great if there was a a way to have the list in a separate file/table or similar to read form when I re-create the database with new values.
For example I want to combine ID 112 and 115 when I recreate the database to ID 112 with value 1 equal to 9 and value 2 equal to 12 (the sum of 112 and 115).
ID | VALUE 1  | VALUE 2
------------------------
...
112| 2       |5
113| 5       |6
114| 6       |6
115| 7       |7
...

To new table:
ID | VALUE 1  | VALUE 2
------------------------
...
112| 9       |12
113| 5       |6
114| 6       |6
...

This is sort of what I am looking for but is there a way to read the ID's from a list with several values? For example ( 112,115), ( 449,622), ( 123,423,321) etc.?
Something like:
select min(id) as newId,
sum(value_1) as newValue1,
 sum(value_2) as newValue2
 from myTable t

where id in list;
How would the list need to be formatted?

A: The following query should give you 112, 9, 12
select min(id) as newId,
       sum(value_1) as newValue1,
       sum(value_2) as newValue2
  from myTable t
 where id in ( 112,115);


text:
Q: Cannot query field signup on type Query Started messing around with GraphQL, but I'm stuck with this error. Not sure if it's a problem in the schema definition or in the query.
const express_graphql = require('express-graphql')
const { buildSchema } = require('graphql')
const users = require('../users/translator')

const schema = buildSchema(`
    type User {
        id: ID
        email: String
        role: String
    }
    type Query {
        user(id: ID!): User
        users: [User]
        token(email: String!, password: String!): String!
    }
    type Mutation {
        signup(email: String!, password: String!, role: String!): ID
    }`
)

const resolvers = {
    users: users.getAll,
    user: users.getById,
    token: users.login,
    signup: users.create,
}

module.exports = app => {
    // GraphQL route
    app.use('/graphql', express_graphql({
        schema,
        rootValue: resolvers,
        graphiql: true,
    }))
}

app is an express.js server while const users holds the logic. I'm able to fetch users and tokens, but when I try to POST a mutation
{
    signup(email: "my@email.com", password: "321321", role: "admin")
}

I get the error Cannot query field "signup" on type "Query". By looking at the GraphiQL suggestions after reading the schema from the server, it looks like the signup mutation doesn't even get exported:

Some tutorials say I should export resolvers using
const resolvers = {
    query: {
        users: users.getAll,
        user: users.getById,
        token: users.login,
    },
    mutation: {
        signup: users.create,
    }
}

But it doesn't work either. Any hints?

A: You need to specify the operation type (query, mutation or subscription) like this:
mutation {
  signup(email: "my@email.com", password: "321321", role: "admin")
}

If the operation type is omitted, the operation is assumed to be a query. This is called "query shorthand notation", but only works if your operation is unnamed and does not include any variable definitions.
It's good practice to always include the operation type regardless.


text:
Q: Open file in OS X In Delphi, I would like to open a file in OS X. My approach is as follows:
const
  Filename = 'test.bmp';

procedure SaveAndOpen;
begin
  Chart.SaveToBitmapFile(Filename);
  {$IFDEF MSWINDOWS}
  ShellExecute(0, 'open', Filename, '', '', SW_Normal);
  {$ELSE}
  _System(Filename);
  {$ENDIF}
end;

But nothing happens. What am I doing wrong?

A: You must add the open verb like so
_System(PAnsiChar('open ' + Filename));

A: This article from Embarcadero's Malcolm Groves covers this topic: Opening files and URLs in default applications in OS X.
In summary, all you need is this:
uses
  Macapi.Appkit,       // for NSWorkspace
  Macapi.Foundation;   // for NSSTR
....
var
  Workspace: NSWorkspace; // interface, no need for explicit destruction
....
Workspace := TNSWorkspace.Create;
Workspace.openFile(NSSTR(FileName));

For sake of completeness, should you wish to open a URL rather than a file, then you call openURL instead:
Workspace.openURL(NSSTR(URL));

Regarding your Windows code, I would recommend not using ShellExecute. That function does not have reasonable error reporting. Use ShellExecuteEx in its place.
And finally, you should probably abstract this functionality away so that it can be re-used by other parts of your program. You want to write that IFDEF as few times as possible.


text:
Q: Using fixtures in Pytest I have the following code in the conftest.py file
@pytest.fixture(scope="session", autouse=True)
def app(request):
    global fixture
    browser = request.config.getoption("--browser")
    base_url=target['baseUrl'])
    fixture = Application(browser=browser,base_url=web_config['baseUrl'])
    print("\n BEFORE SESSION")
    fixture.session.login()
    return fixture

@pytest.fixture(scope="session", autouse=True)
def stop(request):
    def fin():
        print("\n AFTER SESSION")
        fixture.session.ensure_logout()
        fixture.destroy()
    request.addfinalizer(fin)
    return fixture

The test file looks like this. Ie fixture, I obviously do not call.
import pytest

@pytest.yield_fixture()
def setup_method():
    print("\n BEFORE METHOD")
    yield
    print("\n AFTER METHOD")

@pytest.mark.usefixtures("setup_method")
def test_add_text_element(app):
    print("\n RUN TEST")
    app.element.add_blank_page()
    app.element.add_element(element_name='Header')

But what if I need to set some other class settings? If I get another fixture, how can I use it in the test file, instead of the one used now?

A: All about fixtures in py.test you can find in this doc. Below you can found an example how to use fixtures. First of all don't use global. Then be careful about autouse parameter of fixtures. For setup and teardown yield_fixture will be you choice. Use usefixtures as decorator for class. Class will be good to organize your test code. You can found more information about usage in this article (RUS)
conftest.py
@pytest.yield_fixture()
def destroy_method():
    yield
    print("\n DESTROY")

@pytest.yield_fixture(scope="session", autouse=True)
def app(request):
    browser = request.config.getoption("--browser")
    fixture = Application(browser=browser, base_url=web_config['baseUrl'])
    print("\n BEFORE SESSION")
    fixture.session.login()
    yield fixture
    print("\n AFTER SESSION")
    fixture.session.ensure_logout()
    fixture.destroy()

Test file will be looks like:
@pytest.yield_fixture()
def setup_method():
    print("\n BEFORE METHOD")
    yield
    print("\n AFTER METHOD")

@pytest.fixture()
def fix1():
    return 1

@pytest.fixture()
def fix2():
    return 2

@pytest.mark.usefixtures("setup_method", "destroy_method")
class TestSuiteA:
    def test_add_text_element(self, fix1, fix2):
        print("\n RUN TEST")
        assert fix1 + 1 == fix2

A: From pytest docs:
"yield_fixture" functions:

Since pytest-3.0, fixtures using
  the normal fixture decorator can use a yield statement to provide
  fixture values and execute teardown code, exactly like yield_fixture
  in previous versions.
Marking functions as yield_fixture is still supported, but deprecated
  and should not be used in new code.

Reference: https://docs.pytest.org/en/latest/yieldfixture.html


text:
Q: Wireguard doesnt provide connection I try to configure Wireguard on private VDS on DigitialOcean. Write all configs, but there is no connection
There is Server Config
[Interface]
Address = 10.8.0.1/24
Address = fd0d:86fa:c3bc::1/64
SaveConfig = true
PostUp = ufw route allow in on wg0 out on eth0
PostUp = iptables -t nat -I POSTROUTING -o eth0 -j MASQUERADE
PreDown = ufw route delete allow in on wg0 out on eth0
PreDown = iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE
ListenPort = 51820
PrivateKey = <privatekey>

[Peer]
PublicKey = <publickey>
AllowedIPs = 0.0.0.0/32
Endpoint = my.ip.addr:6153

There is client config
[Interface]
Address = 10.8.0.1/24
PrivateKey = <privatekey>
PostUp = ip rule add table 200 from 159.65.204.183
PostUp = ip route add table 200 default via 159.65.192.1
PreDown = ip rule delete table 200 from 159.65.204.183
PreDown = ip route delete table 200 default via 159.65.192.1
DNS = 8.8.8.8

[Peer]
PublicKey = <pubkey>
AllowedIPs = 0.0.0.0/0
Endpoint = server.ip.addr:51820
PersistentKeepalive = 20

Log when I execute wg on Server
interface: wg0
  public key: <pubkey>
  private key: (hidden)
  listening port: 51820

peer: <privatekey>
  endpoint: my.ip.addr:8982
  allowed ips: 0.0.0.0/32
  latest handshake: 21 minutes ago
  transfer: 720 B received, 720 B sent

What do I do wrong?


text:
Q: Implementing dplyr's filter() to show multiple entries across a number of years I have this sample data set:
df <- tibble(
  "PLAYER" = c("Corey Kluber", "CLayton Kershaw", "Max Scherzer", "Chris Sale",
           "Corey Kluber", "Jake Arrieta", "Jose Urena", "Yu Darvish"),
  "YEAR" = c(2016, 2016, 2016, 2016, 2017, 2017, 2017, 2017),
  "WHIP" = c(1.24, 1.50, 1.70, 1.35, 1.42, 1.33, 1.61, 1.10)
 )

The real data set goes from 2000 to 2017. How do I use filter() (or dplyr in general), to bring up all of the players that are active in multiple seasons? For example, in the sample set above, Corey Kluber comes up in 2016 and 2017. How do I use the dplyr package to bring him up? I imagine it is something like so:
df %>%
  select(PLAYER, YEAR, WHIP) %>%  #MY SET HAS MORE VARIABLES THAN THE SAMPLE SHOWS
  filter(PLAYER %in% YEAR == c(2016,2017))

This just returns <0 rows> (or 0-length row.names), when I would want Corey Kluber to come up twice. Thanks.

A: One can use dplyr::n_distinct to find out how many times a player appeared in different session/year. You have to group on PLAYER and then filter data using condition n_distinct(YEAR)>1:
library(tidyverse)

df %>% group_by(PLAYER) %>%
  filter(n_distinct(YEAR) > 1) # A player has appeared in many sessions

# # A tibble: 2 x 3
# # Groups: PLAYER [1]
#   PLAYER        YEAR  WHIP
#   <chr>        <dbl> <dbl>
# 1 Corey Kluber  2016  1.24
# 2 Corey Kluber  2017  1.42
#

If OP is interested in knowing just name of such players then
df %>% group_by(PLAYER) %>%
  filter(n_distinct(YEAR) > 1) %>%
  select(PLAYER) %>%
  distinct()
# # A tibble: 1 x 1
# # Groups: PLAYER [1]
# PLAYER
# <chr>
# 1 Corey Kluber


text:
Q: transform unique values using pandas groupby I have input dictionary like:
{
    "objects": [
        {
            "objType": "master",
            "objName": "sampleOne",
            "objTitle": "Sample One"
        },
        {
            "objType": "master",
            "objName": "sampleTwo",
            "objTitle": "Sample Two"
        },

    ]
}

and I want to group the same values of key objType to generate the dict as below
{
    "objects": [
        {
            "objType": "master",
            "objDetails": [
            {
                "objName": "sampleOne",
                "ObjectTitle": "Sample One"

            },
            {
                "objName": "sampleTwo",
                "ObjectTitle": "Sample Two"
            }
        ]
    ]
}

I have used pandas groupby but not able to get the desired output.

A: I am not sure pandas is appropriate for what you want to accomplish, given the multi=tiered structure o your data.  The following function will correctly parse your data, base on your example input and desired output.
def transform(di):
    tmp = dict()
    for ntry in di['objects']:
        tval = tmp.pop(ntry['objType'], [])
        indict = dict()
        indict['objName'] = ntry['objName']
        indict['ObjectTitle'] = ntry['objTitle']
        tval.append(indict)
        tmp[ntry['objType']] = tval
    return {'objects': tmp}

Given input of
di = {
    "objects": [
        {
            "objType": "master",
            "objName": "sampleOne",
            "objTitle": "Sample One"
        },
        {
            "objType": "master",
            "objName": "sampleTwo",
            "objTitle": "Sample Two"
        }
    ]
}

transform(di)

produces:
{'objects':
           {'master': [{'objName': 'sampleOne', 'ObjectTitle': 'Sample One'},
                       {'objName': 'sampleTwo', 'ObjectTitle': 'Sample Two'}]}}


text:
Q: List and List map to a new Map if I have two list.
the first is List:
[
{
  "A":"code1"
  "B":"1"
},
{
  "A":"code2"
  "B":"1,2"
},
{
  "A":"code3"
  "B":"2,3"
}
]

and the second is List:
[
{
  "C":"target1"
  "D":"1"
},
{
  "C":"target2"
  "D":"2"
},
{
  "C":"target3"
  "D":"3"
}
]

now I need a new Map
"code1" = "target1","code2" = "target1,target2","code3" = "target2,target3"

the rule is when the
List<Object1>.getB().contains(List<Object2>.getD())

I map it to a new Map,replace C to B.
I can use double for to make it.
eg:
public void dosome(){
        Map<String,List<String>> map = new HashMap<>();
        for(Object1 object1 : object1s){
            List<String> list = new ArrayList<>();
            for(Object2 object2 : object2s){
                if(object1.getB().contains(object2.getD())){
                    list.add(object2.getC());
                }
            }
            map.put(object1.getA(),list);
        }
        System.out.println(map);
    }

But I want to change using double "for" circle to using stream()(java8) to make my code more beautiful!

A: If you're seeking a functional solution, here's one way of doing this in functional style:
Map<String, List<String>> map =
        object1s.stream()
                .collect(toMap(Object1::getA,
                               o1 -> object2s.stream()
                                             .filter(o2 -> o1.getB().contains(o2.getD()))
                                             .map(Object2::getC)
                                             .collect(toList()),
                               (a, b) -> b));


text:
Q: Creating a Visual Studio project directory using T4 I am trying to use T4 for source code generation. Mostly, I am able to generate individual files using it. How do I create a complete Visual Studio directory (preferably separate from the T4 template directory) having the below sample structure:
/MyProject – Contains MyProject.sln.
/app - Contains the core project layers.
    /MyProject.ApplicationServices
    /MyProject.Core
    /MyProject.Data
    /MyProject.Web
    /MyProject.Web.Controllers
/build - Empty folder for housing build related stuff.
/lib - Contains the solution items for the deployable application.
/db - Contains database schema information; e.g., the result of scaffolding and/or NHibernate's schema export.
/docs - Project documents.
/logs - Output location for log files.
/tests
    /MyProject.Tests
/tools
    /lib - Contains the solution items for the tests project and all other non-deployable assemblies.
    /CrudScaffolding - Customizable CRUD, scaffolding generation code.

A: You may take a look at the Guidance Automation Extensions and Toolkit for Visual Studio from Microsoft. They are intended for exactly that purpose to be able to author project and solution generation wizards and leverage T4 a lot. In fact, they are the reason why T4 came into being in the first place. However, as they can be seen as a "Software Factory Factory", they do have a steep learning curve.

A: As herzmeister der welten mentions, I do think Guidance Automation could do this sort of job, but it is quite a learning curve.
Here are a couple of other options:

*

*Damien Guard has a post on how to generate Multiple outputs from T4.  However, it's probably not well-suited for creating lots of different types of files.  If you have many files to create of a similar type (e.g. several code files, various project files, etc) that you want to create, his technique would be quite useful.

*Another option would be to combine your existing T4 templates and knowledge and create your outputs using command line T4.  For example, you could simply use a .bat file that executes various commands to generate the necessary outputs using T4 and your existing templates.  The downside here is that it is difficult to pass arguments into the command line utility, but there are some workarounds to that problem too.


text:
Q: scala parallel set recursive value needs type I have a code from 'Scala in depth' that works in interactive editor:
(1 to 1000).par map { _ => Thread.currentThread.toString } toSet

This prints a set with threads that were used for this parallel operation. All works great and a result type is ParSet[String]
But then I try to use it in a code and I have this:
val pthr = (1 to 1000).par map { _ => Thread.currentThread.toString } toSet
//val x = pthr.toSet
println("thread = " + pthr)

This throws: " error: recursive value pthr needs type" in println line. Another observation is when I uncomment second line everything works fine and a result is ParSet().
What is going on here? What is a type of variable "pthr"?

A: The println method expects a string and you've provided a string with a + operator to pthr. In order to convert pthr to a string, the compiler needs to know which type it is. You haven't provided a type in your declaration of pthr but instead let it be inferred. For whatever reason, the inference isn't working so the compiler is requesting an explicit type declaration. You could simply do this:
val pthr : Set[String] = (1 to 1000).par map { _ => Thread.currentThread.toString } toSet

and that should take care of it.
However, I cannot reproduce your results with Scala 2.11.2. I get:
scala> val pthr = (1 to 1000).par map { _ => Thread.currentThread.toString } toSet
<console>:7: warning: postfix operator toSet should be enabled
by making the implicit value scala.language.postfixOps visible.
This can be achieved by adding the import clause 'import scala.language.postfixOps'
or by setting the compiler option -language:postfixOps.
See the Scala docs for value scala.language.postfixOps for a discussion
why the feature should be explicitly enabled.
       val pthr = (1 to 1000).par map { _ => Thread.currentThread.toString } toSet
                                                                             ^
pthr: scala.collection.parallel.immutable.ParSet[String] = ParSet(Thread[ForkJoinPool-1-worker-29,5,main], Thread[ForkJoinPool-1-worker-19,5,main], Thread[ForkJoinPool-1-worker-13,5,main], Thread[ForkJoinPool-1-worker-3,5,main], Thread[ForkJoinPool-1-worker-27,5,main], Thread[ForkJoinPool-1-worker-5,5,main], Thread[ForkJoinPool-1-worker-1,5,main], Thread[ForkJoinPool-1-worker-23,5,main], Thread[ForkJoinPool-1-worker-15,5,main], Thread[ForkJoinPool-1-worker-11,5,main], Thread[ForkJoinPool-1-worker-21,5,main], Thread[ForkJoinPool-1-worker-9,5,main], Thread[ForkJoinPool-1-worker-7,5,main], Thread[ForkJoinPool-1-worker-17,5,main], Thread[ForkJoinPool-1-worker-31,5,main], Thread[ForkJoinPool-1-worker-25,5,main])

scala> println("thread = " + pthr)
thread = ParSet(Thread[ForkJoinPool-1-worker-29,5,main], Thread[ForkJoinPool-1-worker-19,5,main], Thread[ForkJoinPool-1-worker-13,5,main], Thread[ForkJoinPool-1-worker-3,5,main], Thread[ForkJoinPool-1-worker-27,5,main], Thread[ForkJoinPool-1-worker-5,5,main], Thread[ForkJoinPool-1-worker-1,5,main], Thread[ForkJoinPool-1-worker-23,5,main], Thread[ForkJoinPool-1-worker-15,5,main], Thread[ForkJoinPool-1-worker-11,5,main], Thread[ForkJoinPool-1-worker-21,5,main], Thread[ForkJoinPool-1-worker-9,5,main], Thread[ForkJoinPool-1-worker-7,5,main], Thread[ForkJoinPool-1-worker-17,5,main], Thread[ForkJoinPool-1-worker-31,5,main], Thread[ForkJoinPool-1-worker-25,5,main])

Other than the use of the toSet method as a postFix operator, there's nothing wrong with the code and it compiles and executes correctly. Perhaps you should check your version of the compiler?

A: Yes I know this works in interactive scala but doesn't during compilation by scalac.
Okay here is minimalistic example let's call this file "test.scala":
//test.scala
object test {
  def main(args: Array[String]) = {
    val pthr = (1 to 1000).par map { _ => Thread.currentThread.toString } toSet
    println("thread = " + pthr)
  }
}

Now let's execute in terminal:
-> scalac test.scala
test.scala:5: error: recursive value pthr needs type
println("thread = " + pthr)
                      ^
one error found

-> scalac -version
Scala compiler version 2.11.2 -- Copyright 2002-2013, LAMP/EPFL

So again I have this issue only during compilation with scalac.
And when I add a type to pthr (val pthr: Set[String] = ...) then an error is:
test.scala:4: error: type mismatch;
 found   : Boolean
 required: Set[String]
    val pthr:Set[String] = (1 to 1000).par map { _ => Thread.currentThread.toString } toSet
                                                                                ^
one error found

No idea what is going on :/
BTW. this is the exact code copied from "Depth in scala" page 205.


text:
Q: How to manually provide core::panicking::panic* to lld? I am compiling the Rust code of an rlib to LLVM IR, and then using Clang to compile & link it with a C program. This works until my code contains panics, at which point I get linker errors:
ld.lld: error: undefined symbol: core::panicking::panic_bounds_check::hc3a71010bf41c72d
>>> referenced by ld-temp.o
>>>               lto.tmp:(run)
>>> referenced by ld-temp.o
>>>               lto.tmp:(run)
>>> referenced by ld-temp.o
>>>               lto.tmp:(run)
>>> referenced 11 more times

ld.lld: error: undefined symbol: core::panicking::panic::hd695e3b1d0dd4ef4
>>> referenced by ld-temp.o
>>>               lto.tmp:(run)
clang: error: ld.lld command failed with exit code 1 (use -v to see invocation)

I have tried two things to mitigate this:

*

*I have added a panic_handler to my library:
use core::panic::PanicInfo;

#[panic_handler]
pub extern fn panic(_: &PanicInfo<'_>) -> ! {
    loop{}
}

*I have set the panic mode to abort in my Cargo.toml:
[profile.release]
panic = "abort"

Neither on its own, nor combined, solves the issue.
Further details
In the comments, @Solomon Ucko requested more details on the whole compilation pipeline. As I wrote in the tags, this is with no_std; also, the compilation target is MOS 6502. This is the full list of commands to compile and (try to) link:
llvm-mos/bin/clang --config llvm-mos-sdk/build/commodore/64.cfg \
    -O2 -c \
    -o _build/main.c.o \
    src/main.c
cargo rustc --release -- \
    -C debuginfo=0 -C opt-level=1 --emit=llvm-ir
llvm-mos/bin/clang --config llvm-mos-sdk/build/commodore/64.cfg \
    -O2 \
    -o _build/charset.prg \
    _build/main.c.o \
    target/release/deps/chip8_c64-e21ff59526dd729a.ll

A: Based on this answer, I worked around this by passing -Z build-std to Cargo, thereby getting the LLVM IR from Rust's core library, and linking it in.
But then I realized I can do one better, and avoid the long compilation time imposed by -Z std, by just taking the definitions of
core::panicking::panic_bounds_check and core::panicking::panic from these IR files, simplifying their body, and adding them to a hand-written panic.ll file:
%"panic::location::Location" = type { { [0 x i8]*, i64 }, i32, i32 }

; core::panicking::panic
; Function Attrs: cold noinline noreturn nounwind nonlazybind
define void @_ZN4core9panicking5panic17hd695e3b1d0dd4ef4E([0 x i8]* noalias nonnull readonly align 1 %expr.0, i64 %expr.1, %"panic::location::Location"* noalias readonly align 8 dereferenceable(24) %0) unnamed_addr #22 {
start:
  unreachable
}

; core::panicking::panic_bounds_check
; Function Attrs: cold noinline noreturn nounwind nonlazybind
define void @_ZN4core9panicking18panic_bounds_check17hc3a71010bf41c72dE(i64 %0, i64 %1, %"panic::location::Location"* noalias readonly align 8 dereferenceable(24) %2) unnamed_addr #22 {
start:
  unreachable
}

TBH I'm not sure how robust that is (maybe they should loop by branchin to start before `unreachable?), but at least it got me to a fully linked and runnable program.


text:
Q: Odoo/OpenERP: hiding create button from treeview I have a situation here. I am using OpenERP 7. I am trying to hide Create button from tree view of my products. this can be done using
<tree create="false" .....

but situation is like. i want to keep it when user opens the tree view directly from "Asset Management" Module. But hide it when i click on Reporting for treeview.
I tried to use context like this from reporting button's function:
context['prod1']='false'
ctx = dict(context)
print ctx['prod1']

return {
   'type': 'ir.actions.act_window',
   'res_model': 'product.product',
   'view_type': 'form',
   'view_mode': 'tree,form',
   'target': 'current',
   'context':ctx,
   'create':False,
   'domain':[('id','in',domain)]
}

and in treeview form I did:
<tree create="context.get('prod1',False)"

but I get this json related error:
ERROR : SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

this stuff is working with my button but not with my tree view. I tried adding 'create':False in return too, but unable to do what I want to. What am I missing?

A: Are the views your accessing the same or are they different ?
If they are different, I believe the proper way to implement your requirement is to override the relevant view with the
create="false"
property you mentioned.
From the technical memento:

View Inheritance
Existing views should be modifying through inherited views, never directly. An inherited view references its parent view using the inherit_id field, and may add or modify existing elements in the view by referencing them through XPath expressions, and specifying the appropriate position.

Hope this helps.

A: I successfully solved the very same issue by using field_view_get:
def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
    res = models.Model.fields_view_get(self, cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=submenu)
    default_type = context.get('default_type', False)
    can_create = default_type != 'out_customer_production'
    update = not can_create and view_type in ['form', 'tree']
    if update:
        doc = etree.XML(res['arch'])
        if not can_create:
            for t in doc.xpath("//"+view_type):
                t.attrib['create'] = 'false'
        res['arch'] = etree.tostring(doc)

    return res

(I left tree and form view without the create attribute)

A: Don't know how to do it in python + xml either, i would stick with javascript extension, that gets data from context or from fields and disable and hide button depending on that data.


text:
Q: Apache 2.4.29: How to configure multiple I tried configured multiple SSLCACertificateFile in single vhost but apparently apache is accepting only requests with ca_sha256.cer as root cert, is there a way to support both SSLCACertificateFile in single vhost without creating separate vhosts
SSLCACertificateFile "C:/apache/conf/ca_sha1.cer"
SSLCACertificateFile "C:/apache/conf/ca_sha256.cer"

A: No it is not possible to do this and you must concatenate both files together so you can use one file with a list of all the CAs in it.
The easiest way to do what you want is to have the certificates in directory, symlimked to has file name, and then use SSLCACertificatePath instead.
The process to create the has filenames of each link is detailed here:

When you install multiple CA certificates in a single directory, you can
  calculate the hash for each file (NAME-OF-CA-FILE) by using the command:
openssl x509 -noout -hash -in NAME-OF-CA-FILE

Once you know the hash (HASH), you can then rename the file so that
  OpenSSL can find it:
mv NAME-OF-CA-FILE HASH.0

However, this is a little unfriendly for the system administrator, since
  it is not obvious what CA certificates are present.  So many people
  choose to keep the original name of the file and create a symbolic link
  to that file for OpenSSL:
ln -s NAME-OF-CA-FILE HASH.0

This way, OpenSSL can find the correct CA certificate efficiently, and
  system administrators can know what CA certificates are present.


text:
Q: Efficiently extract large amounts of data from Django ORM I have a Django setup with PostgreSQL DB.
One of the tables contains large amounts of data (>1e9 rows) and I need to efficiently iterate over a large subset of it.
Currently, when I try to select a large amount of data it starts buffering the result and my computer runs out of memory.
If I use .iterator() on QuerySet, it just hangs.
If I try to use raw SQL and fetchall() it also starts buffering.
I believe Django uses psycopg2 for PostgreSQL which has cursor.itersize parameter, but when I try to use it with cursor in Django it doesn't do anything.
I know that the problem is not on database end, since I can execute the query using psql (with -A --variable="FETCH_COUNT=10000") and it starts loading immediately without using any memory.
Extra info:

*

*The table has >10 columns, but I only need 2 of them, so if it is possible to only fetch selected for faster loading it would be nice.

EDIT: Using psycopg2 server-side cursor seems to work, but is slower and ugly: How can I use server-side cursors with django and psycopg2?
EDIT 2: Here is code which is working for me now, but which is quite ugly:
def get_stuff():
    def fetch_from_server_cursor(cursor, cursor_name, fetch_size=10_000):
        while True:
            cursor.execute(f"FETCH {fetch_size} FROM {cursor_name}")
            chunk = cursor.fetchall()
            if not chunk:
                return
            yield from chunk

    with transaction.atomic(), connection.cursor() as cursor:
        cursor_name = "my_cursor"
        cursor.execute(
            f"""
            DECLARE {cursor_name} CURSOR FOR
            SELECT first_column, second_column
            FROM {MyModel.objects.model._meta.db_table}
            """
        )
        yield from fetch_from_server_cursor(cursor, cursor_name)

EDIT 3: Here is Django model, N.B. I'm using Timescale on the table in DB which automatically creates index on TimeScaleDateTimeField:
class MyModel(models.Model):
    first_column = models.IntegerField()
    second_column = models.TimeScaleDateTimeField()
    third_column = models.URLField(null=True, blank=True)
    ...

    class Meta:
        ordering = ("second_column",)

A:
The table has [more than] 10 columns, but I only need 2 of them, so if it is possible to only fetch selected for faster loading it would be nice.

You can do this with .only(…) [Django-doc] to only select a subset of the columns, so for example:
for item in MyModel.objects.only('pk', 'other_column').iterator():
    print((item.pk, item.other_column))
This will reduce some bandwidth between the database, and the application layer. But regardless, 109 items is typically not really feasible in Python. If we for example simply sum up items of such range (sum(range(1000000000))), it will take ≈ 14 seconds, but that is a very simple generator. Django will for each record read the content from the database, create a model object, and set the fields accordingly, so this can easily take minutes, or even hours.


text:
Q: Wanting to make a JGraph with a JPanel I am attempting to create a JFrame where the top is a JPanel of a JGraph and the bottom is JPanel of a bar that allows the user to select how many nodes will appear in the Graph, and the Graph to update after this happens. For this reason I put the Graph in a separate class where later I will be building an update method.
My problem is that the Panel that contains the Graph is the size of the frame, but my Graph is only as large as the max vertex value. How do I get change my JPanel to be a certain size, and have the Graph fill up this space?
Also is the way I'm doing it the best way to achieve this goal or is there a better way?
public class MyGraph extends JFrame{

private static final long serialVersionUID = 1L;
private JPanel Gpanel;

public MyGraph(){
    super("Graph");
    JPanel Gpanel = new NewPanel();
    getContentPane().add(Gpanel);
}

public static void main(String args[]){
    MyGraph frame = new MyGraph();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(600, 600);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}

class NewPanel extends JPanel{
    private static final long serialVersionUID = 1L;
    mxGraph graph;
    Object parent;

    NewPanel(){
        this.graph = new mxGraph();
        this.parent = graph.getDefaultParent();
        graph.getModel().beginUpdate();
        try{
            Object v1 = graph.insertVertex(parent, null, "Hello", 20, 20, 80, 30);
            Object v2 = graph.insertVertex(parent, null, "World!", 300, 150, 80, 30);
            graph.insertEdge(parent, null, "Edge", v1, v2);
        }
        finally{
            graph.getModel().endUpdate();
        }
        mxGraphComponent graphComponent = new mxGraphComponent(graph);
        this.add(graphComponent);
    }

    public void Update(){

    }
}

}

A: always set a layout to the panels
public MyGraph(){
    ...
    getContentPane().setLayout(new BorderLayout());
    getContentPane().add(Gpanel, BorderLayout.CENTER);
}

class NewPanel extends JPanel{
    ...

    NewPanel(){
        ...
        this.setLayout(new BorderLayout());
        this.add(graphComponent, BorderLayout.CENTER);
    }
}


text:
Q: Sampling with replacement question I am selecting three letters at random from the word onomatopoeia with replacement.
I want to know how many different three letter combinations can I create?

A: You have $8$ distinct letters {o,n,m,a,t,p,e,i}. You have $8$ possibilities for the first letter you choose, $8$ for the second and $8$ for the third which gives $$8\times8\times8=8^3=512$$ different words.


text:
Q: Getting selected rows of report files from a WPF Datagrid on button click This is my first question on stackoverflow and I am entirely new to programming in C# so please bear with me. I created an application using WPF in which I displayed a list of files with .rpt extension in a datagrid. The datagrid contains the list of filenames and there is also a checkbox column in the datagrid. These files are populated in the grid dynamically from a folder browser when I click on a button. I am stuck on the part of retreiving these files for printing when I click on a second button (print, as I need to call a service to print the selected files).
This is the code snippet that I have tried until now:
public partial class MainWindow : Window
{
    public class ReportFile
    {
        public string Path { get; set; }
        public string FileName { get; set; }
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        string inputPath = AppDomain.CurrentDomain.BaseDirectory;

        System.Windows.Forms.FolderBrowserDialog fldDlg = new System.Windows.Forms.FolderBrowserDialog();
        fldDlg.SelectedPath = AppDomain.CurrentDomain.BaseDirectory;
        DialogResult result = fldDlg.ShowDialog();
        foreach (string str in Directory.GetFiles(fldDlg.SelectedPath))
        {

            ReportFile reportFile = new ReportFile();
            reportFile.Path = str;
            reportFile.FileName = System.IO.Path.GetFileName(str);
            dataGrid1.Items.Add(reportFile);
        }
    }

    private void button_Click_1(object sender, RoutedEventArgs e)
    {
        foreach (ReportFile drv in dataGrid1.SelectedItems.OfType<ReportFile>())
        {
            if (drv != null)
            {
                DataRow row = drv.Row;
                Title = row.ItemArray[3].ToString();
                System.Windows.MessageBox.Show(Title.ToString());
            }
        }

        var TransactionFactory = new TransactionFactory();
        var Transaction = TransactionFactory.NewTransactionString();
        var EnvironmentValue = (string)cmbEnvironment.SelectedValue;
        var CirieEngineServiceClientFactory = new CirieEngineServiceClientFactory(EnvironmentValue);

        var CirieEngineServiceClient = CirieEngineServiceClientFactory.NewCirieEngineServiceClient();
        var Form = new Cirie.Form()
        {
            Path = string.Empty,
            Title = string.Empty
        };

        var PackageID = Convert.ToInt16(txtPackageID.SelectedText);
        var Generation = Convert.ToInt16(txtGeneration.SelectedText);
        var formList = new List<Cirie.Form>();
        var stream = CirieEngineServiceClient.PrintFormCollection
            (Transaction,
             new Collection<Cirie.Form>(formList),
             PackageID,
             Generation
             );
    }
}

But I am not sure if it is correct since there is an exception being thrown: Unable to cast object of type 'ReportFile' to type 'System.Data.DataRowView'
I would really appreciate help on this one please!

A: You could use the OfType method to cast the SelectedItems to ReportFile objects and then access any properties of the ReportFile class:
foreach (ReportFile drv in dataGrid1.SelectedItems.OfType<ReportFile>())
{
    //...
}


text:
Q: RC circuit with lossy capacitor This circuit

simulate this circuit – Schematic created using CircuitLab
can be regarded as an RC series circuit with a lossy capacitor. The time expression for \$V_C(t)\$ with \$R_2 \to \infty \$ is available here and it is \$V_C(t) = V_0 (1 - e^{-t/\tau})\$.
I would like to obtain the same expression, but in this situation.
\$ V_0 \$ is the DC voltage generator; the switch is closed for \$t \geq 0\$ and \$V_C (t = 0) = 0\$ (capacitor initially discharged).
I can write
$$\frac{V_0 - V_C (t)}{R_1} = I(t)$$
$$\frac{V_0}{R_1} - \frac{1}{R_1 C} \frac{dQ(t)}{dt} = I(t)$$
which is the current across \$R_1\$ and so the total corrent entering \$ C // R_2 \$. \$V_C (t)\$ is variable during the capacitor charge. The fact is that here \$I(t)\$ is not simply \$dQ(t) / dt\$, because not all the charge exiting from \$R_1\$ goes through the capacitor: part of it flows across \$R_2\$ and this amount of "leaked" charge changes (raises) with time. So, how can this be taken into account?
Are there any hints to obtain a differential equation for the charge or the current of the capacitor?

A: The simplest way to analyze this circuit is to take V0, R1 and R2 as a group and find their Thévenin equivalent, with a different voltage and a new, single value of resistance. Then you can analyze it in the same way as the case with R2 = ∞.

A: I think the best approach to this problem is to use the Laplace Transform, but if you really want to use the time differential equation, you must take the expression of the current at the node that links R1, R2 and C.
\$I_{R1}(t) = I_C(t) + I_{R2}(t)\$.
If you work around with that formula, you will end up with the differential equation you are looking for.


text:
Q: Adding CSV to ASP.NET Web Application I am trying to create a basic d3.js chart by using Visual Studio 2013 and a csv file.
This is the first time I am playing with Visual Studio and not able to understand the reason for data binding not happening. after running the following code, I am getting no result. I believe its because the csv or json file should be in same folder. but even after that I am not getting desired results.
HTML Code
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> D3 Tutorial</title>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script type="text/javascript" src="https://rawgithub.com/NickQiZhu/dc.js/master/web/js/crossfilter.js"></script>
<meta http-equiv="content-type" content="text/html; charset=UTF8">

 </head>
<body>
<script>

    d3.csv("mydata.csv", function(data) {

        var canvas = d3.select("body")
                        .append("svg")
                        .attr("width", 500)
                        .attr("height",500)

        canvas.selectAll("rect")
                .data(data)
                .enter()
                    .append("rect")
                    .attr("width", function(d) { return d.age * 50;})
                    .attr("height" , 50)
                    .attr("y", function (d , i) { return i * 50 })
                    .attr("fill", "blue")
</script>

</body>
</html>

Please find below the screen shot of my Solution explorer

Also mydata.csv
"name","age"
"Maria",30
"Fred",50
"Francis",12
Error
XMLHttpRequest cannot load file:///C:/xampp/htdocs/mydata.csv. Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https, chrome-extension-resource.
Uncaught TypeError: Cannot read property 'length' of null
Uncaught NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'file:///C:/xampp/htdocs/mydata.csv'.

A: You're trying to load a local file ("mydata.csv") via JavaScript, which is restricted in most modern browsers for security reasons. For your script to work, you need to load your page via a web server. You can either upload your files to a remote server, or host one on your local machine for development.


text:
Q: Rails and queries with complex joins: Can each joined table have an alias? I'm developing an online application for education research, where I frequently have the need for very complex SQL queries:

*

*queries usually include 5-20 joins, often joined to the same table several times

*the SELECT field often ends up being 30-40 lines tall, between derived fields / calculations and CASE statements

*extra WHERE conditions are added in the PHP, based on user's permissions & other security settings

*the user interface has search & sort controls to add custom clauses to the WHERE / ORDER / HAVING clauses.

Currently this app is built on PHP + MYSQL + Jquery for the moving parts. (This grew out of old Dreamweaver code.) Soon we are going to rebuild the application from scratch, with the intent to consolidate, clean, and be ready for future expansion. While I'm comfortable in PHP, I'm learning bits about Rails and realizing, Maybe it would be better to build version 2.0 on a more modern framework instead. But before I can commit to hours of tutorials, I need to know if the Rails querying system (ActiveRecord?) will meet our query needs.
Here's an example of one query challenge I'm concerned about. A query must select from 3+ "instances" of a table, and get comparable information from each instance:
SELECT p1.name AS my_name, pm.name AS mother_name, pf.name AS father_name
FROM people p1
    JOIN mother pm ON p1.mother_id = pm.id
    JOIN father pf ON p1.father_id = pf.id
    # etc. etc. etc.
WHERE p1.age BETWEEN 10 AND 16
# (selects this info for 10-200 people)

Or, a similar example, more representative of our challenges. A "raw data" table joins multiple times to a "coding choices" table, each instance of which in turn has to look up the text associated with a key it stores:
SELECT d.*, c1.coder_name AS name_c1, c2.coder_name AS name_c2, c3.coder_name AS name_c3,
    (c1.result + c2.result + c3.result) AS result_combined,
    m_c1.selection AS selected_c1, m_c2.selection AS selected_c2. m_c3.selection AS selected_c3
FROM t_data d
    LEFT JOIN t_codes c1 ON d.id = c1.data_id AND c1.category = 1
        LEFT JOIN t_menu_choice m_c1 ON c1.menu_choice = m_c1.id
    LEFT JOIN t_codes c2 ON d.id = c2.data_id AND c2.category = 2
        LEFT JOIN t_menu_choice m_c2 ON c2.menu_choice = m_c2.id
    LEFT JOIN t_codes c3 ON d.id = c3.data_id AND c3.category = 3
        LEFT JOIN t_menu_choice m_c3 ON c3.menu_choice = m_c3.id
WHERE d.date_completed BETWEEN ? AND ?
    AND c1.coder_id = ?

These sorts of joins are straightforward to write in pure SQL, and when search filters and other varying elements are needed, a couple PHP loops can help to cobble strings together into a complete query. But I haven't seen any Rails / ActiveRecord examples that address this sort of structure. If I'll need to run every query as pure SQL using find_by_sql(""), then maybe using Rails won't be much of an improvement over sticking with the PHP I know.
My question is: Does ActiveRecord support cases where tables need "nicknames", such as in the queries above? Can the primary table have an alias too? (in my examples, "p1" or "d") How much control do I have over what fields are selected in the SELECT statement? Can I create aliases for selected fields? Can I do calculations & select derived fields in the SELECT clause? How about CASE statements?
How about setting WHERE conditions that specify the joined table's alias? Can my WHERE clause include things like (using the top example) " WHERE pm.age BETWEEN p1.age AND 65 "?
This sort of complexity isn't just an occasional bizarre query, it's a constant and central feature of the application (as it's currently structured). My concern is not just whether writing these queries is "possible" within Rails & ActiveRecord; it's whether this sort of need is supported by "the Rails way", because I'll need to be writing a lot of these. So I'm trying to decide whether switching to Rails will cause more trouble than it's worth.
Thanks in advance! - if you have similar experiences with big scary queries in Rails, I'd love to hear your story & how it worked out.

A: Short answer is Yes. Rails takes care of the large part of these requirements through various types of relations, scopes, etc. Most important thing is to properly model your application to support types of queries and functionality you are going to need. If something is difficult to explain to a person, generally will be very hard to do in rails. It's optimized to handle most of "real world" type of relationships and tasks, so "exceptions" become somewhat difficult to fit into this convention, and later become harder to maintain, manage, develop further, decouple etc. Bottom line is that rails can handle sql query for you, SomeObject.all_active_objects_with_some_quality, give you complete control over sql SomeObject.find_by_sql("select * from ..."), execute("update blah set something=''...) and everything in between.
One of advantages of rails allows you to quickly create prototypes, I would create your model concepts, and then test the most complex business requirements that you have. This will give you a quick idea of what is possible and easy to do vs bottlenecks and potential issues that you might face in development.


text:
Q: Why in node, child_process `spawn` has no killSignal option but `spawnSync` has? Additionally, how to spawn a child process that ignore SIGTERM and can only be killed by SIGKILL?

A: Because this option is associated with the timeout option.
In spawn you have to decide when you kill the process.
Example: (from doc)
const { spawn } = require('child_process');
const grep = spawn('grep', ['ssh']);

grep.on('close', (code, signal) => {
  console.log(
    `child process terminated due to receipt of signal ${signal}`);
});

// Send SIGHUP to process
grep.kill('SIGHUP');


text:
Q: Navigation bar does not convert in RTL for arabic language in swift I have functionality for user to change language within app.
If I change the language within the app without set the root view controller, navigation bar does not convert its layout to RTL.
The current page view controller text will be changed according to language which I set from my App
I put my code here what i have done to change the auto layout for RTL & LTR
    if let languageArray = UserDefaults.standard.value(forKey: APPLE_LANGUAGE_KEY) as? Array<String> {

        switch languageArray[0] {
        case KLanguage_ar:
            if #available(iOS 9.0, *) {
                UIView.appearance().semanticContentAttribute = .forceRightToLeft
            } else {
                // Fallback on earlier versions
            }
            break
        case kLanguage_en:
            if #available(iOS 9.0, *) {
                UIView.appearance().semanticContentAttribute = .forceLeftToRight
            } else {
                // Fallback on earlier versions
            }

            break
        default:
            break

        }
    }

If I change the root view controller after change my App language, it is working fine.
So what should I do same thing without change the root view controller?


text:
Q: How To Programmatically Apply Borders To A Range Good morning!  I have researched my question, and have found certain variations to an answer, but not the exact answer I need.
Below is a 4-line snippet of a very large Excel worksheet formatting block.  I'm trying to take these four lines of code down to a single line, using a Range. All of my attempts have come up just short of being the proper syntax.  I would greatly appreciate any help.
xlWorkSheet.Cells[3, 2].Borders[Excel.XlBordersIndex.xlEdgeRight].Weight = 1d;
xlWorkSheet.Cells[3, 3].Borders[Excel.XlBordersIndex.xlEdgeRight].Weight = 1d;
xlWorkSheet.Cells[3, 4].Borders[Excel.XlBordersIndex.xlEdgeRight].Weight = 1d;
xlWorkSheet.Cells[3, 5].Borders[Excel.XlBordersIndex.xlEdgeRight].Weight = 1d;

Thanks!
Keith

A: This can be done in a single for-loop
Try this one:
for (int i = 2; i < 5; i++)
{
   xlWorkSheet.Cells[3, i].Borders[Excel.XlBordersIndex.xlEdgeRight].Weight = 1d;
}

A: For a Range
xlWorkSheet.get_Range(xlWorkSheet.Cells[3, 2], excelSheet.Cells[3, 5]).Borders ...

(However that would only set the boder of the rightmost member cell, if you wanted to set them all pass xlInsideVertical.)


text:
Q: how to get the long,lat,city,zip code country after passing full address? I have used google autocompelete api.With help of this i am able to get places in my search.After getting the address i want to get city,country,zipcode,street,longitude,latitude.I have used below code to get address.
let placesClient = GMSPlacesClient()
        print("text is \(textFieldAddress.text!)")
        placesClient.autocompleteQuery(textFieldAddress.text!, bounds: nil, filter:
        filter){ results, error in
          self.arr_addressSearch.removeAll()

          if results == nil
          {
            return
          }

          for result in results!
          {

            print("resut is \(result.attributedFullText.string)")
            print("address count  is \(self.arr_addressSearch.count)")

            self.arr_addressSearch.append(result.attributedFullText.string)
          }

A: You can get the placeId from your code like
result.placeID

Then use the below code to get the details of the place and you will recieve GMSPlace object. From that you will find coordinate property which will hold latitude and longitude.
From the above response of result you will get place_id for the place selected and then you can use the place_id to fetch all the details for the place like below.
let placeID = "ChIJV4k8_9UodTERU5KXbkYpSYs"

placesClient!.lookUpPlaceID(placeID, callback: { (place: GMSPlace?, error: NSError?) -> Void in   if let error = error {
    print("lookup place id query error: \(error.localizedDescription)")
    return   }

  if let place = place {
    print("Place name \(place.name)")
    print("Place address \(place.formattedAddress)")
    print("Place placeID \(place.placeID)")
    print("Place attributions \(place.attributions)")   } else {
    print("No place details for \(placeID)")
}
})

For more details you can go Here.

A: From google's documentation it appears that the results of an autocompleteQuery are an array of GMSAutocompletePredictions objects.
As such they contain the following properties

Properties
- attributedFullText
The full description of the prediction as a NSAttributedString.
- attributedPrimaryText
The main text of a prediction as a NSAttributedString, usually the name of the place.
- attributedSecondaryText
The secondary text of a prediction as a NSAttributedString, usually the location of the place.
- placeID
An optional property representing the place ID of the prediction, suitable for use in a place details request.
- types
The types of this autocomplete result.

There doesn't appear to be away to pull the lat,long,post code etc from here as attributedFullText, attributedPrimaryText, attributedSecondaryText and placeID are just strings. (or NSAttributtedString/NSString to be precise)
Based on similar questions it seems what you need to do is use the placeID of each GMSAutocompletePredictions object in a new request to get the info you need.
referenced question answer
This should at least be a start.

A: You want to get the latitude, longitude, city, and zip code from a user-entered freeform address. Freeform means that there could be varying capitalization, punctuation, abbreviations, and spelling. Because of this, you should consider the need to parse, standardize, and verify the address.
To get the information using your code and Google's API, you need to get the placeID from a result and make a request with it: that will give you the latitude, longitude, and other information you're looking for.
I'm not sure if you've seen this, but this Address Form Autocomplete Tutorial from Google will probably help a lot.
In truth, Google isn't an address verification service. They don't focus on address standardization and verification. If verified addresses are important to you (if you want to make sure you have a real address and a real place when you search), you may want to try a different service, such as SmartyStreets. They have an iOS SDK, too. They do a great job of finding a valid address using your search result and parsing it into address components, and then returning correct place information like latitude and longitude. They match their addresses to data from postal services.
Fair disclosure: I'm an employee of SmartyStreets.


text:
Q: I have a customer table and want to find duplicate entries from submission table and show it in customer table in new field I have a customer table and want to find duplicate entries from submission table and show it in customer table in new field (like in final table)
Customer table
id  email
 1   abc@gmail.com
 3   xyz@gmail.com
 4   ymz@gmail.com
Submission table
id  Submitteduser
1   abc@gmail.com
2   abc@gmail.com
3   xyz@gmail.com
4   ymz@gmail.com

Final table
id  email          count
1   abc@gmail.com    2
3   xyz@gmail.com    1
4   ymz@gmail.com    1

help me to make this query

A: you can use the following query
select Submission.id, Customer.email, count(Customer.*) from Customer inner join Submission on (email = Submitteduser) group by Submission.Submitteduser

A: Try this query: Click Here For Fiddle
SELECT a.id, a.email, COUNT(b.Submitteduser)  FROM Customer AS a
JOIN Submission AS b
ON a.email = b.Submitteduser
GROUP BY b.Submitteduser


text:
Q: Ruby: Too many open files @ rb_sysopen After opening a file with File.new(big_file) (without closing it) 1016 times (Ubuntu) or 1017 times (CentOS), it seems there is a limit and it raises:
Too many open files @ rb_sysopen - big_file (Errno::EMFILE)

Is there any way to raise that limit?
On my systems, ulimit is set to unlimited.

A: *

*EMFILE is too many files opened in your process.

*ENFILE is too many files opened in the entire system.

So Errno::EMFILE is due to the ruby process opening too many files. This limit is probably set to the default 1024 can be seen with:
$ulimit -n
1024

Instead of:
$ulimit
unlimited

You can raise the limit using this method.


text:
Q: Maximizing tcp connection rate from haproxy to jetty application server I'm using haproxy front-ended with nginx to loadbalance across jetty application servers, all running ubuntu-14-04-x64.
Nginx and haproxy share a 0.5G 1CPU VM. Each jetty server runs on a 4G 2CPU VM.
Nginx front-ends haproxy, configured like this:
user myc;
worker_processes 1;
pid /run/nginx.pid;

events {
    worker_connections 65536;
    multi_accept on;
    use epoll;
}

http {
    include mime.types;
    types_hash_max_size 2048;
    default_type application/octet-stream;
    proxy_cache_path /home/myc/cache levels=1:2 keys_zone=one:10m inactive=7d;
    proxy_http_version 1.1;
    proxy_set_header Connection "";

    upstream loadbalancer {
        server unix:/tmp/haproxy.sock;
        keepalive 8192;
    }

    server {
        listen 80 backlog=16384;
        server_name example.org;
        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

        gzip on;
        gzip_types text/plain application/javascript application/x-javascript text/javascript text/xml text/css application/json;
        gzip_vary on;
        gzip_min_length 10240;

        open_file_cache max=2000 inactive=20s;
        open_file_cache_valid 60s;
        open_file_cache_min_uses 5;
        open_file_cache_errors off;

        sendfile on;

        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        error_page 502 /502.html;
        location /502.html {
            root /home/myc/html;
        }

        proxy_cache one;

        location / {
            proxy_pass http://loadbalancer/;
            proxy_connect_timeout 60s;
            proxy_read_timeout 60s;

            add_header Cache-Control private; # Don't cache any of this publicly, because JSESSIONID will be cached, too

            add_header X-Proxy-Cache $upstream_cache_status;
        }

        location /api {
            proxy_pass http://loadbalancer/api;
            proxy_connect_timeout 60s;
            proxy_read_timeout 60s;

            proxy_ignore_headers Expires;
            proxy_hide_header Expires;
            proxy_ignore_headers Set-Cookie; # Make sure JSESSIONID is not cached with static content
            proxy_hide_header Set-Cookie;

            proxy_cache_valid 200 10s;

            add_header X-Proxy-Cache $upstream_cache_status;
        }

        location ~* ^.*\.(css|js|gif|jpe?g|png|ico)$ {
            proxy_pass http://loadbalancer$uri;
            proxy_connect_timeout 60s;
            proxy_read_timeout 60s;

            expires 1h;
            access_log off;
            log_not_found off;

            proxy_ignore_headers Expires;
            proxy_hide_header Expires;
            proxy_ignore_headers Set-Cookie; # Make sure JSESSIONID is not cached with static content
            proxy_hide_header Set-Cookie;
            add_header Cache-Control public;

            proxy_cache_valid 200 404 10s;

            add_header X-Proxy-Cache $upstream_cache_status;
        }
    }
}

HAProxy is configured like this:
global
    daemon
    maxconn 262144
    maxconnrate 128
    chroot /home/jail/

defaults
    mode http
    timeout connect 10s
    timeout client 120s
    timeout server 120s
    errorfile 502 /etc/haproxy/errors/502.http
    errorfile 503 /etc/haproxy/errors/503.http
    compression algo identity
    option http-keep-alive

frontend http-in
    bind /tmp/haproxy.sock user myc
    default_backend makeyourcase

backend makeyourcase
    option httpchk GET /
    appsession JSESSIONID len 52 timeout 1h
    server ny2-b-app01 <redacted>:8080 maxconn 1024 check inter 60000 fall 1 rise 1
    server ny2-b-app02 <redacted>:8080 maxconn 1024 check inter 60000 fall 1 rise 1

The TCP stack is tuned with these parms on the nginx/haproxy box and the two jetty boxes:
net.core.netdev_max_backlog = 65535
net.core.somaxconn = 65535
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.ipv4.tcp_rfc1337 = 1
net.ipv4.ip_local_port_range = 1024 65535
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_keepalive_intvl = 30
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_moderate_rcvbuf = 1
net.ipv4.tcp_syncookies = 0

net.ipv4.tcp_rmem = 4096 87380 16777216
net.ipv4.tcp_wmem = 4096 16384 16777216

net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_timestamps = 1
net.ipv4.tcp_window_scaling = 1

I'm using The Grinder to create load. Once the load builds to a certain point, SYN_SENT stacks up on the haproxy side. If I reduce maconnrate to 96, that reduces the connection rate enough that the SYN_SENTs never stack up. The back ends are never loaded beyond 20% CPU, and never over a load average of 1. I've tried a variety of tuning options in nginx, haproxy, and the tcp stack.
It seems that there might be some tcp parm that would let more connections/second come in to the jetty servers, and that would let haproxy fully load up the jetty servers.
OTOH, according to http://cbonte.github.io/haproxy-dconv/configuration-1.5.html, "By default HAProxy operates in keep-alive mode with regards to persistent
connections." And yet, the connections between haproxy and the app servers are not kept open. Is there some haproxy option I've specified that's preventing that? Or is there some option that would enable that?

A: Though I spent some time tweeking settings, shown below, the change that finally gave more reasonable results (about 14K simultaneous connections) was to bump the size of the VM hosting nginx and haproxy from 0.5G 1CPU to 2G 2CPU.
Here's the current nginx config:
user myc;
worker_processes 1;
pid /run/nginx.pid;
worker_rlimit_nofile 131072;

events {
    worker_connections 65536;
    multi_accept on;
    use epoll;
}

http {
    include mime.types;
    types_hash_max_size 2048;
    default_type application/octet-stream;
    proxy_cache_path /home/myc/cache levels=1:2 keys_zone=one:10m inactive=7d;

    upstream loadbalancer {
        server unix:/tmp/haproxy.sock;
        keepalive 32768;
    }

    upstream haproxy_admin {
        server 127.0.0.1:8081;
    }

    server {
        listen 80 backlog=16384;
        server_name makeyourcase.org;
        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

        gzip on;
        gzip_types text/plain application/javascript application/x-javascript text/javascript text/xml text/css application/json;
        gzip_vary on;
        gzip_min_length 10240;

        open_file_cache max=2000 inactive=20s;
        open_file_cache_valid 60s;
        open_file_cache_min_uses 5;
        open_file_cache_errors off;

        sendfile on;

        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        error_page 502 /502.html;
        location /502.html {
            root /home/myc/html;
        }

        proxy_cache one;

        location ~ ^/api/auth/local/.*$ {
            proxy_pass http://loadbalancer$uri;
        }

        location /admin {
            proxy_pass http://loadbalancer/admin;
        }

        location /stats {
            proxy_pass http://haproxy_admin/;
        }

        location / {
            proxy_pass http://loadbalancer/;
            proxy_connect_timeout 60s;
            proxy_read_timeout 60s;

            add_header Cache-Control private; # Don't cache any of this publicly, because JSESSIONID will be cached, too

            add_header X-Proxy-Cache $upstream_cache_status;
        }

        location /api {
            proxy_pass http://loadbalancer/api;
            proxy_connect_timeout 60s;
            proxy_read_timeout 60s;

            proxy_ignore_headers Expires;
            proxy_hide_header Expires;
            proxy_ignore_headers Set-Cookie; # Make sure JSESSIONID is not cached with static content
            proxy_hide_header Set-Cookie;

            proxy_cache_valid 200 10s;

            add_header X-Proxy-Cache $upstream_cache_status;
        }

        location ~* ^.*\.(css|js|gif|jpe?g|png|ico)$ {
            proxy_pass http://loadbalancer$uri;
            proxy_connect_timeout 60s;
            proxy_read_timeout 60s;

            expires 1h;
            access_log off;
            log_not_found off;

            proxy_ignore_headers Expires;
            proxy_hide_header Expires;
            proxy_ignore_headers Set-Cookie; # Make sure JSESSIONID is not cached with static content
            proxy_hide_header Set-Cookie;
            add_header Cache-Control public;

            proxy_cache_valid 200 404 10s;

            add_header X-Proxy-Cache $upstream_cache_status;
        }
    }
}

And HAProxy:
global
    daemon
    maxconn 32768
    maxconnrate 256
    chroot /home/jail/

defaults
    mode http
    timeout connect 10s
    timeout client 120s
    timeout server 120s
    errorfile 502 /etc/haproxy/errors/502.http
    errorfile 503 /etc/haproxy/errors/503.http
    compression algo identity

frontend http-in
    bind /tmp/haproxy.sock user myc
    default_backend makeyourcase

backend makeyourcase
    option httpchk GET /
    option http-server-close
    appsession JSESSIONID len 52 timeout 1h
    server ny2-b-app01 <redacted>:8080 maxconn 1024 check inter 60000 fall 1 rise 1
    server ny2-b-app02 <redacted>:8080 maxconn 1024 check inter 60000 fall 1 rise 1

listen stats localhost:8081
    mode   http
    stats  enable
    stats  hide-version
    stats  realm MYC
    stats  uri /

And sysctl:
fs.file-max = 1048576

net.core.netdev_max_backlog = 250000
net.core.somaxconn = 262144
net.core.rmem_max = 134217728
net.core.wmem_max = 134217728

net.ipv4.tcp_rfc1337 = 1
net.ipv4.ip_local_port_range = 1024 65535
net.ipv4.tcp_fin_timeout = 10
net.ipv4.tcp_keepalive_intvl = 30
net.ipv4.tcp_max_syn_backlog = 262144
net.ipv4.tcp_moderate_rcvbuf = 1
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_rmem = 4096 87380 67108864
net.ipv4.tcp_wmem = 4096 65536 67108864
net.ipv4.tcp_low_latency = 1

net.ipv4.tcp_tw_recycle = 0
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_timestamps = 1
net.ipv4.tcp_window_scaling = 1

vm.swappiness = 0


text:
Q: ¿Cómo pasar un tipo de dato número como prop con parseFloat? Quiero pasar un dato de tipo número como prop a un componente que acepta números, pero el componente tiene un parsefloat para convertir los strings a números y no me acepta el dato de tipo numero, ¿Cómo puedo pasar este dato de tipo numero?.
Este es el componente que recibe los strings con parseFloat:
markOrigin={{
  latitude: parseFloat(props.profile.location?.coords.latitude),
  longitude: parseFloat(props.profile.mobile)
}}

Este es el componente que recibe los props como números:
interface Props {
    markOrigin: {
        latitude: number
        longitude: number
    }
    markDestination: {
        latitude: number
        longitude: number
    }
}

export const HospitalMapRender: React.FC<Props> = (props) => {
    const { markOrigin, markDestination } = props

    const [origin, setOrigin] = React.useState({
        latitude: markOrigin.latitude,
        longitude: markOrigin.longitude
    })

    const [destination, setDestination] = React.useState({
        latitude: markDestination.latitude,
        longitude: markDestination.longitude
    })

    return (
        <View>
            <MapView
                style={Styles.map}
                initialRegion={{
                    latitude: markOrigin.latitude,
                    longitude: markOrigin.longitude,
                    latitudeDelta: 0.006,
                    longitudeDelta: 0.006
                }}
            >
                <Marker coordinate={origin} />
                <Marker coordinate={destination} />
                <MapViewDirections
                    origin={origin}
                    destination={destination}
                    strokeColor="red"
                    strokeWidth={2}
                    apikey={GOOGLE_MAPS_KEY}
                />
            </MapView>
        </View>
    )
}


text:
Q: Symbolic Links to an Existing Folder I'm trying to synchronize two folders on two different computers to my Dropbox folder on their respective machines. So for example:
XP:
C:\Dev -> C:\Documents and Settings\username\Dropbox\Dev
OSX:
~/dev -> ~/Dropbox/Dev
I'm using junction on XP and ln on OSX. However if I create the link using junction first, and that folder syncs via Dropbox to my Mac, I can't create the symbolic link there. And vice versa. Essentially I want the contents of these folders merged into Dropbox/Dev (so that they are actually merged in C:\Dev and ~/dev) on both machines.
Any suggestions?

A: Unfortunately, that's not how symlinks work.
Symlinks don't take two separate objects and turn them into one link. Rather they take one object and turn them into two separate links.
In your case, you need to turn the arrows the other way.
XP: Dropbox -> c:\Dev
OSX: Dropbox -> ~/Dev
That turn the Dropbox into the target of the symlink. So any changes you do to those files are really changes to the Dropbox files.
If you want the arrows the original way, then symlinks aren't the tool.  You'll need a folder merging tool that takes your local machine changes and merges them into the Dropbox folder.  That is more complicated and if they are source files, then I highly recommend you go with a Version Control Tool like Git or Mercurial.


text:
Q: pass value of td element to rails controller I'm trying to pass the value of a  element to a rails controller!
Currently, I have something like this:
<%= link_to db, :action => :show %>

This represents a row in an html table, which contains a string value, e.g. "development".
When the user clicks on the "development" link, the <%= link_to ... %> grabs the value from the current clicked  and passes that to a rails controller action, in this case the show action.
How can this be achieved!?
UPDATE - generating links:
<% @dbs.each do |db| %>

    <%= link_to db, :action => :show %>

UPDATE 2:
this is my index controller:
conn = Mongo::Connection.new
@dbs = conn.database_names #this returns an array of strings (which are the names of the databases)

Now I want to be able to click on of these databases and then to pass the clicked text to the rails controller show action. I'm not sure how I would generate a custom resources path for these links... but I was contemplating of doing it using Ajax or something javascript related. Maybe get the text of clicked link using jQuery and then send an Ajax request to the rails controller with the text as a parameter!

A: I think that it's a strange thing what you're trying to do, but a solution could be to use javascript to append the id to the href of each link as a query string.
If you could explain a little bit what you're trying to achieve maybe we could find a better solution.
Hope it helps!
Edit:
If you have a table of links I think that you should consider them as a resource and managing them the REST way.
Your controller should have an index and show action and you should declare the links as a resource in the routes file (maybe link it's a reserved word and you will have to use a different name, I'm not sure), the index action will fetch all the links and when you render them, you could specify the link for each one with something similar to "link_path(link.id)" (remember, you should have a show action defined) in the controller you will receive the link id so you could load it with a simple "find" and pass it to the view.
I recommend you to always look for the REST way to solve a problem in ROR.
Edit 2:
Ok let's see if this works for you:
I suppose that you have a model that represent those links that you're talkin about, for example:
class DataBaseLinks < ActiveRecord:Base

end

This model with be backed up by a table in your database, if you have generated it the rails way, you will also have an id column that identify each database link.
in your controller, let's say DataBaseLinksController, you'll have:
class DataBaseLinksController < ApplicationController

  def index
    @dabatase_links = DataBaseLink.all
  end

  def show
    @database_link = DataBaseLink.find(params[:id])
  end

end

(I've avoided all the validations and checks).
All you have to do in your index.html.erb is:
<% @database_links.each do |database_link| %>
  <%= link_to database_link.name, database_link_path(database_link.id) %>
<% end %>

This will generate all the links with the correct path to the show action (maybe the route helper is a little bit different, but not so much).
Notice also that you'll have to add into your routes.rb the following line:
resources :database_links, :only => [:index, :show]

How do you see it?
Edit 3:
(I'll delete all my edited answers when we find a correct one)
Ok I'm going to suppose that you are not using something like mongoid so you don't have active record similar objects.
Have you tried this in your view:
<% dbs.each do |dbs_name| %>
  <%= link_to dbs_name, :controller => "your_controller", :action => :show, :dbs_name => dbs_name %>
<% end %>


text:
Q: How to change format of date in function I have this Javascript snippet that retrieves a start date from combobox and compares it to an end date, it then works out how many months are in between the start and end date and outputs that value into another textfield, then in the end takes the end date and adds one day to it and sets that value as the expiry date, its a simple function however I cant figure out how to fix the format of the dates
Right now when a person enters the start and end date the format is in Y,m,d this needs to be changed to Y-m-d (with hyphens), however this affects the function itself and then it does not work, I can easily change the format in extjs but I need to make sure the function still works after
Here is the function
function monthDiff(startdate, enddate) {
    var months;
    months = (enddate.getFullYear() - startdate.getFullYear()) * 12;
    months -= startdate.getMonth();
    months += enddate.getMonth();
    return months <= 0 ? 0 : months;
}
var m = monthDiff(
    Ext.getCmp('startdateTextField').getValue(),
    Ext.getCmp('enddateTextField').getValue()
);
Ext.getCmp('durationTextField').setValue(m);

Date.prototype.addDays = function(d) {
    this.setDate(this.getDate() + d);
    return this;
};
Date.prototype.yyyymmdd = function() {
    var yyyy = this.getFullYear().toString();
    var mm = (this.getMonth() + 1).toString();
    var dd = this.getDate().toString();
    return yyyy + '-' + (mm[1] ? mm : "0" + mm[0]) + '-' + (dd[1] ? dd : "0" + dd[0]);
};

var end = Ext.getCmp('enddateTextField').getValue();
end.addDays(1);
var enddate = end.yyyymmdd();
var expirydate = enddate;
Ext.getCmp('expirydateTextField').setValue(expirydate);

Let me know if I should post the extjs form code

A: if you are using extJS, I strongly suggest you use the Ext.Date (http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.Date) class to manipulate, format and parse date.


text:
Q: PHP execute one insert SQL but add two records in database I used PHP Codeigniter's insert method to input on log data, but get two exactly same records in Mysql database. My code is like below:
public function add_practise_log($user_id, $question_id, $selected, $is_correct)
{
    $log_data = array(
        'user_id' => $user_id, 'question_id' => $question_id, 'selected' => $selected,
        'is_correct' => $is_correct, 'practise_time' => date('Y-m-d H:i:s')
    );

    $this->db_write->insert(TABLE_QUESTION_PRACTISE_LOG, $log_data);

    return;
}`

I ensure this code was just executed only once, but in Mysql general log  I found two same insert queries:
4198 Query INSERT INTO question_practise_log
(user_id, question_id, selected, is_correct, practise_time)
 VALUES ('20037', 6, 'option_c', 0, '2015-08-19 18:26:19')

4198 Query INSERT INTO question_practise_log
(user_id, question_id, selected, is_correct, practise_time)
 VALUES ('20037', 6, 'option_c', 0, '2015-08-19 18:26:19')`

4198 is connection id, I was so confused about this mysql activity.
Had anybody encountered this situation or can someone explain this weird action.
BTW, there also have some other methods to insert records but this situation only happened on this table

A: Better write this
$this->db->insert('question_practise_log',$log_data);


text:
Q: Change all external links using jQuery I want to change all external links on my blog (blogspot here, that's why I'm looking for jQuery code) without changing the posting of my blog because I need a lot of work if I do that.
For example, my website is example.com.
I want to change all external links to
http://example.com/p/go.html?url=http://externallink.com

without need for any changes on my blog post. I don't have any idea to start with.
SOLVED: https://gist.github.com/2342509 Thanks everyone :D I just need to change it a bit.

A: In jQuery you can try:
// DOM ready
$(function(){
    $('a[target="_blank"]').prop('href', 'http://example.com/p/go.html?url=http://externallink.com');
});

Ofcourse this will only work if you have set the target="_blank" property/attribute in HTML and if you want all links to open the same url. This idea derives from the fact you want to have external links open automatically in a different tab/window.
If this is not the required functionality, you can use a custom data- attribute in a similar way. Only difference is you will need to loop each link, and get the data from it.
// DOM ready
$(function(){
    $('a[data-href]').each(function(){
        var anc = $(this),
            href = anc.prop('href'),
            dataHref = anc.data('href');

        anc.prop('href', href + '?url=' + dataHref);
    });
});

HTML example:
external link

And now you will probably need to add more information if that is still not what you want.

A: Going off of @Tim Vermaelan's answer, you could try this, which will check for every link that doesn't start with your website's URL without relying on it being target="_blank":
$('a:not([href^="http://yoursite.com"])').prop('href', 'http://example.com/p/go.html?url=http://externallink.com');


text:
Q: Passing Information Between Output Blocks in Shiny I have a Shiny program that functions, but is extremely slow and cumbersome because I call compute-intensive functions repeatedly in each output block.
While this works, it takes minutes to run because I am forcing the computer to repeatedly calculate the same information each time it needs it.
How can I do a single function call, pull the resultant data into a single list, then distribute it to the various Shiny output blocks that need different parts of it?
Here is the server side code that works... (I think the ui side is ok...)
library(shiny)
 shinyServer(
  function(input, output) {
  output$table7 <- renderTable({
  inFile <- input$file1
  if (is.null(inFile))
  return(NULL)
  WorkingSet <- read.csv(inFile$datapath, header=TRUE, sep=',',
                      quote='"')
  TempHolder <- CARTOptimizer(WorkingSet, input$seed, input$k, input$whichcluster)
  TempHolder$v2
})
  output$plot1 <- renderPlot({
  inFile <- input$file1
  if (is.null(inFile))
    return(NULL)
  WorkingSet <- read.csv(inFile$datapath, header=TRUE, sep=',',
         quote='"')
  TempHolder <- CARTOptimizer(WorkingSet, input$seed, input$k, input$whichcluster)
  clustertree = rpart(badcluster ~ ., data=TempHolder$v3, method="class",
         control=rpart.control(cp=TempHolder$v1))
  prp(clustertree)
})
  output$table1 <- renderTable({
  inFile <- input$file1
  if (is.null(inFile))
  return(NULL)
  WorkingSet <- read.csv(inFile$datapath, header=TRUE, sep=',',
             quote='"')
  SingleClusterHolder <- SingleCluster(WorkingSet, input$seed, input$k,
    input$whichcluster)
  SingleClusterHolder$v1
 })
})

Screenshot of Shiny Output:

Note that CARTOptimizer and SingleCluster are user defined functions that return three different values each:

*

*CARTOptimizer$v1 = Best cp value for CART analysis

*CARTOptimizer$v2 = Confusion Matrix

*CARTOptimizer$v3 = Refined Data Set with Additional Columns for Subsequent Analysis

*SingleCluster$v1 = Matrix on Cluster Details

*SingleCluster$v2 = Refined Working Data Set (factors stripped)

*SingleCluster$v3 = Refined Holding Data Set (factors present)

As you can see, some of these are single values, some are matrices, and some are data frames.
Suggestions on how to make this more efficient would be greatly welcome.
Thank you.

A: As I see it, you have 3 entities that need to be updated: table7, table1, and plot1.  I think that the best think you could do here is to remove as much code as possible from the functions that assign those.  For example, it looks like you load the same csv file 3 times, once for each output.  You should have a separate reactive block of code that reads the file and assembles whatever information it needs from that file without producing any graphs.  To prevent it from causing the other functions to execute, use a return(NULL) condition in each output that prevents display if the other parameters haven't been set.  If results from the same function are used in more than one output, have that function be a separate reactive object.  Then, whenever a parameter is changed in the UI, that function executes once.  The fact that its results have changed then trigger the associated outputs to change.
In general, if you are putting the same computationally intensive code into your server.R file multiple times, you are creating a slower program.  Find a way to have the updates occur like dominoes, so that each variable to be updated in response to a change in input is held in its own reactive object and stored in a variable.  Then use those variables only where necessary in the definitions of your outputs.