text:
Q: While using signalr, will there be any connection limits on IIS I have been looking at SignalR from last few days. Using this I have created an Admin Dashboard to get realtime information about a database table. Basically this table gets populated by may different users from various applications. It has come out well. These updates are possible only when there is persistent connection between client Broswer and WebServer. I have few doubts before deploying this app in production.
I understand that SignalR first checks WebSockets then looks for Long Polling based on there availability between client and server. No matter what it uses, there will be a connection open between client and server.
My question is how does it perform in scenario where more users are connected to the same server for example  100,000 admins are connected at same time. Does IIS has any limitations on number of persistent connections it can open at one point? If so can we configure to that to max value and what wud be that value.
Sorry if it is rookie question
ASP.NET MVC3 & IIS 7 are used for development.

A: Thanks Paige. Here are my findings. ASP.NET 4.0 by default accepts 5000 maximum concurrent requests per CPU. TO change this we need to set this number in ASP.NET Config file which can be found in this location
%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet.config
Also I found this great PodCast by
Scott HanselMan
http://www.hanselminutes.com/325/aspnet-45-updates-core-webforms-and-signalr-with-damian-edwards

A: You should review the Performance Section of the SignalR Wiki on GitHub. This provides some really good guidance for the following:

*

*IIS Configuration - Max Concurrent Requests Per Application

*ASP.NET Configuration - Max Concurrent Requests & Request Queue Limits

Additionally, it states the key Peformance Counters to monitor when performing load testing of your application. Which IMO you should do to truly have an understanding of how your application is going to perform and make adjustments as necessary for your specific scenario.
Finally, there is a link to Crank the recommended tool for generating client load with SignalR.
Update: Link to Crank is now current.

A: You're probably more likely to run into this on Windows 8 / 10 which has connection limits of only 10*. This will only affect you during development of course - but it's a big pain if you have multiple browsers open with active connections and it's very easy to exceed 10.
*I'm unable to confirm at this time that Windows 10 has the same connection limit as Windows 8, but likely so.


text:
Q: ENABLE resizing or scrolling of activity on keyboard pop up I've seen numerous threads on how to disable standard Android behavior of scrolling active text field or resizing current activity when on-screen keyboard pops up, yet my problem is exactly opposite. Neither scrolling nor resizing happens in my app.
What do I have to do to implement proper behavior?
<?xml version="1.0" encoding="utf-8"?>

<!-- The main content view -->
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RootView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="?colorPrimary">

    <com.sothree.slidinguppanel.SlidingUpPanelLayout xmlns:sothree="http://schemas.android.com/apk/res-auto"
        android:id="@+id/slidingPanel"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="bottom"
        sothree:umanoFadeColor="@android:color/transparent"
        sothree:umanoOverlay="true"
        sothree:umanoPanelHeight="200dp"
        sothree:umanoShadowHeight="0dp">

        <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/drawer_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <RelativeLayout
                android:id="@+id/fragmentContainer"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />

            <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/scrollView1"
                android:layout_width="@dimen/lewa_lista_size"
                android:layout_height="match_parent"
                android:layout_gravity="start"
                android:background="?xenoPanelBackgroundColor"/>
        </android.support.v4.widget.DrawerLayout>

        <RelativeLayout
            android:id="@+id/playlist"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center">

            <LinearLayout
                android:id="@+id/chwytak"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/tlo_kropek"
                android:orientation="vertical">

                <ImageView
                    android:id="@+id/kropki"
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/uchwyt_szuflady_height"
                    android:layout_centerHorizontal="true"
                    android:gravity="center_horizontal"
                    android:src="@mipmap/kropki" />

                <RelativeLayout
                    android:id="@+id/wypelniaczGorny"
                    android:layout_width="match_parent"
                    android:layout_height="0dp"/>
            </LinearLayout>

            <android.support.v7.widget.Toolbar
                android:id="@+id/playlistAB"
                style="?xenoActionBarTheme"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/chwytak"
                android:elevation="4dp"
                android:minHeight="?attr/actionBarSize">

                <Spinner
                    android:id="@+id/spinner_toolbar"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />
            </android.support.v7.widget.Toolbar>

            <RelativeLayout
                android:id="@+id/wypelniacz"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_alignParentBottom="true"
                android:background="?xenoPanelBackgroundColor"/>

            <android.support.v4.view.ViewPager
                android:id="@+id/pager"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_above="@id/wypelniacz"
                android:layout_below="@id/playlistAB"
                android:background="?xenoPanelBackgroundColor"/>
        </RelativeLayout>
    </com.sothree.slidinguppanel.SlidingUpPanelLayout>

</FrameLayout>

A: you can use an windowSoftInputMode property for activiy in manifest here is example
 <activity
    android:windowSoftInputMode="adjustPan"
    android:name=".YourActivity"></activity>

How the main window of the activity interacts with the window containing the on-screen soft keyboard. The setting for this attribute affects two things:
The state of the soft keyboard — whether it is hidden or visible — when the activity becomes the focus of user attention.
The adjustment made to the activity's main window — whether it is resized smaller to make room for the soft keyboard or whether its contents pan to make the current focus visible when part of the window is covered by the soft keyboard.
here u get more info https://developer.android.com/guide/topics/manifest/activity-element.html
you can get suitable attribute according to your requirement

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python how do I assign some data to a variables value Code snippet:
data = [("a", "b", "c", "d"),("e", "f", "g", "h")]
for i in data:
    console = '{}_{}'.join(('consoleip',str(i[2])))
    <> = Hostdata(hw_id = i[0],location_id = i[1],consoleip = i[2],          biosversion = i[3])

Expected result:
consolip_c = Hostdata(hw_id ='a', location_id ='b', consoleip ='c', biosversion ='d')
 consolip_g = Hostdata(hw_id ='e', location_id ='f', consoleip ='g', biosversion ='h')

Im looping through the data, which holds thousands of database records and I want each record to be held in a distinct variable unique to the record. This would help me access each record with a unique named tuple variable.
How can I fill in the gap for <>, to assign a the namedtuple(Hostdata) to the value associated for console. Because I get a "SyntaxError: can't assign to function call" when I directly use:
'{}_{}'.join(('consoleip',str(i[2]))) = Hostdata(hw_id = i[0],location_id = i[1],consoleip = i[2],biosversion = i[3])

A: Try this:
console=Hostdata(hw_id = i[0],location_id = i[1],consoleip = i[2],biosversion = i[3])

You are trying to assign the value to the value that the variable holds instead of the value to the variable. Basically, the <> is console.


text:
Q: Select default navigation drawer item When my app first loads I would like the first option in the navigation drawer to be selected by default. Currently, nothing is selected.
Previous similar questions have suggested using getMenu().getItem(0).setChecked(true) or setCheckedItem() but I am unsure where these would be used.
Main Activity.kt
class MainActivity : AppCompatActivity() {

    private lateinit var appBarConfiguration: AppBarConfiguration
    private lateinit var drawerLayout: DrawerLayout

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        drawerLayout = findViewById(R.id.drawer_layout)

        val topLevelDestinations: HashSet<Int> = HashSet(listOf(R.id.toDoList, R.id.allTasks, R.id.settings))

        val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
        val navController = navHostFragment.navController
        findViewById<NavigationView>(R.id.nav_view).setupWithNavController(navController)
        appBarConfiguration = AppBarConfiguration.Builder(topLevelDestinations)
            .setOpenableLayout(drawerLayout)
            .build()
        setupActionBarWithNavController(navController, appBarConfiguration)
    }

    override fun onSupportNavigateUp(): Boolean {
        val navController = findNavController(R.id.nav_host_fragment)
        return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
    }
}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".MainActivity">

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/nav_graph" />

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:menu="@menu/drawer_menu"/>

</androidx.drawerlayout.widget.DrawerLayout>


text:
Q: Error while trying to run transpiled typescript code using namespaces I try to utilize the "namespace" in typescript.
Here is my tsconfig.json file:
{
  "compilerOptions": {
    "target": "ES2017",                                /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
    "module": "amd",                           /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    "outFile": "dist/bundle.js",
    "outDir": "./dist",                        /* Redirect output structure to the directory. */
    "rootDir": "./src",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    "strict": true,                                 /* Enable all strict type-checking options. */
    "alwaysStrict": true,                        /* Parse in strict mode and emit "use strict" for each source file. */
    "typeRoots": ["./node_modules/@types"],                             /* List of folders to include type definitions from. */
    "esModuleInterop": true,                        /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    "skipLibCheck": true,                           /* Skip type checking of declaration files. */
    "forceConsistentCasingInFileNames": true,        /* Disallow inconsistently-cased references to the same file. */
    "lib": [
      "es2021",
    ]
  },

}

I have the following code:
src/code/code.darwin.ts:
namespace Test {
    export const terminator = () => console.log('DARWIN');
}

src/code/code.ts:
namespace Test {
    export class ATest {
        public terminate() {
            terminator();
        }
    }
}

src/outer.ts:
/// <reference path="./code/code.ts" />

Test.terminator();

When I compile it - all good, but trying to run it:
/Users/talrofe/Desktop/test/dist/bundle.js:12
Test.terminator();
     ^

TypeError: Test.terminator is not a function
    at Object.<anonymous> (/Users/talrofe/Desktop/test/dist/bundle.js:12:6)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:12)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
    at internal/main/run_main_module.js:17:47
talrofe@moranamar-g3 test %


text:
Q: F# Windows Forms game loop I want to make game loop in F# but i have problem with that.
let rec gameLoop (gamePanel:Panel) =  async {
    (*redraw gemaPanel *)
    lock gamePanel ( fun() ->
      let graphics = gamePanel.CreateGraphics();
      let rectangle = new System.Drawing.Rectangle(100, 100, 200, 200);
      graphics.DrawEllipse(System.Drawing.Pens.Black, rectangle);
    )
    return! gameLoop (gamePanel:Panel)
    }

let startGame (p:Panel) (p1:Panel) = hide p; Async.StartAsTask(gameLoop p1);()

If i add async this loop wont execute. If i will make this loop sync it will run forever.
What i want, to have loop which will be working all time in second thread and and will redraw game every 30ms and handle keyevents.

A: You need to use Async.RunSynchronously in startGame to actually kick off the async:
let startGame (p:Panel) (p1:Panel) = hide p; Async.RunSynchronously (gameLoop p1)


text:
Q: Insert new row for binary systems with SQL I have the following table
 (cl1  ,  cl2)
  ----  ----
  (a   ,  1)
  (a   ,  2)
  (b   ,  2)
  (c   ,  1)
  (c   ,  2)

each a , b ,c  can take two values (1 or 2 or both).
My question is :
How to insert a new row (with 0 on cl2) for all the cl1 that have only 1 or 2 and NOT the both in the example. I would like to insert the following row :
----
(b   ,  0)
----

A: I'm sure there are better ways, but here is one way to do it using group by and a having clause to enforce your rules (I'm assuming Oracle syntax):
insert into tbl (cl1, cl2)
(select cl1, 0
   from tbl
  group by cl1
 having count(case when cl2 in (1, 2) then 'X' end) != 0 -- contains 1 or 2
    and (count(case when cl2 = 1 then 'X' end) = 0 -- but not both
         or count(case when cl2 = 2 then 'X' end) = 0)
)

EDIT
A much simpler way:
insert into tbl (cl1, cl2)
(select cl1, 0
   from tbl
  where cl2 in (1, 2)
  group by cl1
 having count(distinct cl2) = 1
)

A: CREATE TABLE TestTable (cl1 VARCHAR(2), cl2 INT);

INSERT INTO TestTable (cl1, cl2) VALUES ('a', 1), ('a', 2), ('b', 1), ('c', 1), ('c', 2);

INSERT INTO TestTable (cl1, cl2)
SELECT cl1, 0
FROM TestTable
WHERE cl1 NOT IN (
    SELECT cl1
    FROM TestTable
    WHERE cl2 IN (1, 2)
    GROUP BY cl1
    HAVING COUNT(DISTINCT cl2) = 2
);

MySQL Demo: http://rextester.com/XWHGF50183

The below block returns the cl1 those have the cl2 is 1 and 2. Based on the result using NOT IN you can achieve the result.
SELECT cl1
FROM TestTable
WHERE cl2 IN (1, 2)
GROUP BY cl1
HAVING COUNT(DISTINCT cl2) = 2

Help from this answer

A: I am assuming that the BD is Oracle. Hope the below snippet helps.
SELECT B.CL1,
  0
FROM
  (SELECT A.CL1,
    CASE
      WHEN WMSYS.WM_CONCAT(A.CL2) LIKE '%1%'
      AND WMSYS.WM_CONCAT(A.CL2) LIKE '%2%'
      THEN 'both'
      ELSE 'one'
    END rnk
  FROM
    (SELECT 'a' cl1,1 cl2 FROM dual
    UNION ALL
    SELECT 'a' cl1,2 cl2 FROM dual
    UNION ALL
    SELECT 'b' cl1,2 cl2 FROM dual
    UNION ALL
    SELECT 'c' cl1,1 cl2 FROM dual
    UNION ALL
    SELECT 'c' cl1,2 cl2 FROM dual
    )A
  GROUP BY A.CL1
  )B
WHERE B.rnk = 'one';

A: Here you go:
insert into [YOUR TABLE NAME]
      select cl1,0 from [YOUR TABLE NAME]
    group by cl1 having count(distinct cl2)<> 2
;


text:
Q: SPST Power Switch with LED for Guitar Amplifier I would like to have a power switch for the solid state guitar amp I am building, but I would like an LED indicator to know when it is on. I know how to do this using a dpdt on-off, but would it be possible to use an spst and still have the LED?

A: Yes. Put the LED in parallel with your amp:

simulate this circuit – Schematic created using CircuitLab


text:
Q: ng-model data bing not working properly I'm trying to update a field with a new geo code value, but even though the model is updated it is not binding with first call.  My controller code is as follows:
function TheReportCtrl($scope) {
    $scope.code = [];
    $scope.code.lat = "19.2555500";
    $scope.getCode = function () {
        var geocoder = new google.maps.Geocoder();
        var address = "12323 Barker Cypress Rd, Cypress, Texas"
        geocoder.geocode({
            'address': address
        }, function (results, status) {
            if (status === google.maps.GeocoderStatus.OK) {
                $scope.code.lat = results[0].geometry.location.k;
            } else {
                console.log("Geocoding failed: " + status);
            }
        });
    }
}

What is the missing part of my code?
Here is the JsFiddle Code Sample

A: You've missed an
$scope().$apply();
See http://fiddle.jshell.net/yfLek2cw/
Also your Angular CDNLink inside your original fiddle doesn't work. The reason is, that the geolocation callback is done not from angular. Therefore the dirty check mechanism doesn't work there. To start the dirty check again, you've to call $scope.$apply();
This is needed for ALL external callback functions, even if those callbacks are inside the angular scope. Auto $apply only works for angular callbacks like $timeout or the $q service

A: Your code is actually working, you just need to update the $scope by using the $apply() method. Here's a fiddle:
http://fiddle.jshell.net/7v2dfLsv/3/


text:
Q: Getting json datas - jquery i cannot get the json datas via
     jQuery.parseJSON(myArr);
              $.each(myArr, function(key, value) {
  alert(key + ': ' + value);
});

What's wrong ?

A: You need to capture the return of the parseJSON method.
jQuery.parseJSON(myArr);

should read
myArr = jQuery.parseJSON(myArr);

otherwise, you are passing a string into the $.each method.


text:
Q: Nested select in create table query I want to write create table statement with query with nested select in if construction to compare with number constant. So that the code is readable.
create table transaction_client stored
    as
select
    if(c.record_id = '01',
       'Handle',
       c.record_name) as type,
    if(c.record_id = '02',
       cast(t.amount as string),
       '')            as value,
    if(c.record_id = '02',
       c.record_name,
       '')            as attribute
from transaction  t
join       client c
           on c.id = t.client_id;

I tried to use the with structure and select code from table, but it does not allow the use of different values in rows.
create table classifier as
select
    stack(5,
          '01', 'CODE_01', 'TRANSACTION_TYPE',
          '02', 'CODE_02', 'TRANSACTION_TYPE',
          '03', 'CODE_03', 'TRANSACTION_TYPE'
        ) as (code, description, classifier_name)
from any_table;

create table transaction_client stored
    as orc as
with
    cl as (select code as code from classifier where classifier_name = 'TRANSACTION_TYPE' and description = 'CODE_01')
select
    if(c.record_id = cl.code,
       'Handle',
       c.record_name) as type,
    if(c.record_id = cl.code,
       cast(t.amount as string),
       '')            as value,
    if(c.record_id = cl.code,
       c.record_name,
       '')            as attribute
from transaction  t
join       client c
           on c.id = t.client_id
cross join t;

I also tried using a map, but the query execution speed is doubled.
set hivevar:classifier=map('01', 'CODE_01',
                           '02', 'CODE_02',
                           '03', 'CODE_03')

....
 if(c.record_id = ${classifier}['CODE_01'],
       'Handle',
       c.record_name) as type,
...

Please tell me which structure is better to avoid magic number and make code more readable?


text:
Q: sqlite compound where datetime queries I have a 'presure' table in an sqlite3 database with a 'timestamp' column filled by datetime('now') by a python program which runs periodically adding line at a time to my table.
I'd like to query the database so as to return all the values just from today.
Easy enough:
select * from presure where timestamp like "2014-07-10 %";

BUT, I don't want to have to modify the query each time I run it, today ,tomorrow or any other day. So what I want is someway to replace the date string and wild card with a sub query that generates todays date like:
select date('now');

but I have been unsuccessful compounding the two queries. What am I missing?

A: In SQL, strings are concatenated with ||:
SELECT * FROM presure WHERE timestamp LIKE date('now') || '%'


text:
Q: Rails: How do you call 'update' from another action In my rails app, I have an action (def do_some_stuff) but I would first like to update my post before doing so & if it's successful, it'll finishing "doing stuff"... Simple, right?
Here's my action
def do_some_stuff
  Rails.logger.debug "Post id is #{@post.id}"
  update #calls the update action
  ## does some stuff
end

Instead of updating, Rails is throwing me this error: "Required parameter missing: post" (meaning 'post' is nil, right?)
I'm getting the post id in my logger but for some reason it gives me that error.
To make things simpler, I decided to just try to call the update action in the 'do_some_stuff' action.. I'm using strong_params btw
How do I call the "update" action from another action?
Thank you in advance. Any help would be greatly appreciated.

I typed this on my phone so sorry in advance for any typos

my log:
Processing by PostsController#do_some_stuff as HTML
Parameters: id = 149

A: You shouldn't be calling one action from another one. Instead, just call update_attributes on the post:
def do_some_stuff
  if @post.update_attributes(params[:post])
    ## do some stuff
  end
end

If successful, update_attributes will return true and the "do some stuff" block will be executed.
This assumes that you already have a @post present. Usually you would get that in a before_filter block or method with a find: @post = Post.find(params[:id]).


text:
Q: How to parse a long dataframe of text using regular expressions into a dataframe [R] I have a giant data frame which I would like to turn into a more usable format. It is based on a copy-pasted text file of a schedule, where the entries have a consistent format.So, I know that each day will have the format:
###
Title - Date
First event
Time: 11:00 AM
Location: Address
Address line 2
Second event description
Time: 12:00 AM
Location: Address
Address
###

What I am having trouble with is figuring out how to parse this. Basically, I want to store everything between the "###"'s as a single day, and then add events based on how many times the above format repeats, and make a string or datetime entry based on if letters are following a "Time:" or a "Location:".
However, I am really having trouble with this. I have tried putting it all into a giant dataframe where each line is a row, and then adding dummies for location rows, time rows, etc as seperate columns, but am not sure how to translate that into discrete days or events. Any help would be appreciated.
Data is public, so a sample is below -- it is a giant dataframe with one row for each row of text:
*Text*
###
The Public Schedule for Mayor Rahm Emanuel – January 5, 2014
There are no public events scheduled at this time.
###
The Public Schedule for Mayor Rahm Emanuel – January 6, 2014
Mayor Rahm Emanuel will greet and thank snow clearing teams from the Department of Streets and Sanitation.
Time: 11:30 AM
Location: Department of Streets and Sanitation
Salt Station
West Grand Avenue and North Rockwell Street
Chicago, IL*
*There will be no media availability.
Mayor Rahm Emanuel and City Officials will provide an update on the City's efforts to provide services during the extreme weather.
Time: 2:00 PM
Location: Office of Emergency Management and Communications
Headquarters
1411 West Madison Street
Chicago, IL*
*There will be a media availability following.
Mayor Rahm Emanuel will greet and visit with residents taking advantage of a City warming center.
Time: 3:00 PM
Location: Department of Family and Support Services
10 South Kedzie Avenue
Chicago, IL**
*There will be no media availability.
**Members of the media must respect the privacy of residents at the facility, and can only film City of Chicago employees.
###

Edit:
An example output I would like is something like (sorry the code here is broken, not sure why!):
Date            Time      Description           Location
December 4th    9:00 AM   A housewarming party  1211 Main St.
December 5th   11:00 AM   Another big event     1234 Main St.

If at all possible.
EDIT 2:
Basically -- I know how to pull all this stuff out of the columns. I think my issue may really be reshaping the data intelligently. I have split it into this giant dataframe with one column where each row is a string which corresponds to a row of text int he original schedule. I then have a bunch of columns like "is_time", "is_new_entry", "is_location" which are 1 if the row is a time, new entry beginning, or location. I just don't know how to reshape this into the output above.


text:
Q: Creating a treemap, based on count, using R I would like to create a tree map based on the count of "names". However, I am not sure how to do so. Seeking you help on this matter.
names <- c("A", "B", "B", "C", "D", "A", "A", "A", "A", "G", "B", "F", "F", "H")
names <- names %>% as.factor()
ggplot(names, aes(area= names, fill= names) + geom_treemap()

Many thanks

A: names <- c("A", "B", "B", "C", "D", "A", "A", "A", "A", "G", "B", "F", "F", "H")
names <- data.frame(names)

names <- names %>%
          count(names)

  ggplot(names, aes(area= n, fill= names)) + geom_treemap()


text:
Q: No message available MVC I have a message bundle under my resources in src/main the resources with messages are named messages_en_US.properties i.e. and I am getting the message to my JSP.
@Component
public class Messages {

    private MessageSource messageSource;

    @Autowired
    public Messages(MessageSource messageSource) {
        this.messageSource = messageSource;
    }

    private MessageSourceAccessor accessor;

    @PostConstruct
    private void init() {
        accessor = new MessageSourceAccessor(messageSource);
    }

    public String get(String code) {
        return accessor.getMessage(code);
    }
}

When I used the code above without any beans I had an exception that informed me there is no code for a message. So I added a BeanHelper class as below.
@Configuration
@ComponentScan("com")
public class BeansHelper {

    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:messages");

        return messageSource;
    }
}

When now I am trying to go on localhost:8000/ I am getting an 404 that says there is no message available. What is wrong in this code? My messages are under src/main in the resources. But the JSP of course are in WEB-INF/views/ any ideas guys how to solve the problem? I correctly added message properties file to my Local.


text:
Q: Making the size of one div equal to another I have two divs, box and stylewidth. stylewidth is a child of box, which I've tried to make as large as stylewidth in a function. to that end I've added this line.
$("#box").width(("#styleWidth").width);

The problem is, box doesn't change in size, and I'm not sure why. is this the correct method?

A: You forgot the parenthesis on the inner width() function and the dollarsign, and make sure you wrap it in document.ready or add it after the elements are loaded in the DOM:
$("#box").width( $("#styleWidth").width() );

A: You forgot the jQuery dollar sign (before #styleWidth) and .width is a function, so it takes ().
$("#box").width($("#styleWidth").width());

A: Are you sure you can't solve this problem with css?
You may be able to simply use width:100% assuming the positioning and document structure allow this.


text:
Q: Examples of real $2\times2$ and complex $3\times3$ matrices with minimal polynomial $t^2+1$ Consider the following corrolary (3.3.4 in Horn's and Johnson's Matrix Analysis book):

For each $A\in\mathbb{C}^{n\times n}$, the minimal polynomial $q_A(t)$ divides the characteristic polynomial $p_A(t)$. Moreover, $q_A(\lambda)=0$ if and only if $\lambda$ is an eigenvalue of $A$, so every root of $p_A(t)=0$ is a root of $q_A(t)=0$.

There is no real $3\times3$ matrix with minimal polynomial $t^2+1$ (proofs for that are here). However, there is a real $2\times2$ matrix and a complex $3\times3$ matrix with minimal polynomial $q_A(t)=t^2+1$. I am trying to find such examples.
For the $2\times2$ case consider
$$A=\begin{bmatrix}1&-1\\2&-1\end{bmatrix}$$
Its characteristic polynomial is
$$p_A(t)=\det(tI-A)=\dots=t^2+1=(t-i)(t+i)$$
Then, by the above theorem and by the definition of the minimal polynomial (the unique monic polynomial of minimum degree, $q_A(t)$, that annihilates $A$ i.e. $q_A(A)=0$) we have
$$q_A(t)|p_A(t)$$
and every eigenvalue is a root of $q_A(t)$. Thus, the minimal polynomial is indeed $q_A(t)=t^2+1$.
For the $3\times3$ case consider
$$A=\begin{bmatrix}i&0&0\\0&1&-1\\0&2&-1\end{bmatrix}$$
Similarly, it is easy to see that
$$p_A(t)=\det(tI-A)=\dots=(t-i)^2(t+i)$$
and among the two possibilities for the minimal polynomial
$$p_1(t)=(t-i)^2(t+i)\qquad\text{and}\qquad p_2(t)=(t-i)(t+i)$$
we see that $p_2(t)=t^2+1$ is the one with minimum degree that annihilates $A$ so that $q_A(t)=t^2+1$.
Are the above examples correct? Any other examples, perhaps more interesting?

A: $$
\left(
\begin{array}{cc}
0 & 1 \\
-1 & 0
\end{array}
\right)
$$
$$ $$
$$
\left(
\begin{array}{ccc}
i & 0 & 0 \\
0 & i & 1 \\
0 & 0 & i
\end{array}
\right)
$$

A: For $2\times 2$ matrices we know that the characteristic polynomial of $A$ is
$\chi_A(x)=x^2-Tr(A)x+det(A)$ so if you want it to be $x^2+1$ then $Tr(A)=0$ and $det(A)=1$ so you can find any other example you wish.


text:
Q: Pre-Populating forms in Flask not working I am using Flask and HTML to make a form that's already populated, when I have the value set in HTML on Flask when I do request.form.get('name') it just returns blank.
@main.route('/update/user', methods=['POST'])
def update_ban():
    name = request.form.get('name')
    print(name)
    return render_template('index.html') #Temp until finished system

 <input class="form-control" id="name" name="name" placeholder="Example: parker02311" value="test" disabled>

I am not sure why its just returning None instead of test, any help appreciated.

A: So turns out there was two issues, anyone in the future who needs help this is the fix:
Make sure no fields are disabled
In your API make sure the update is made properly


text:
Q: RESTful API in CouchDB: How to structure your documents? Since CouchDB is implementing a RESTful API, doesn't that mean I wanna put all documents of the same type in their own database?
eg.
POST http://localhost/users
GET http://localhost/users/1
PUT http://localhost/users/1
DELETE http://localhost/users/1

POST http://localhost/threads
GET http://localhost/threads/1
PUT http://localhost/threads/1
DELETE http://localhost/threads/1

Rather than putting them all in one big database (http://localhost/my_app).
Doesn't a 100% RESTful approach mean that the former is more correct?

A: The primary reason to use multiple databases is to split the data up because of volume, notably creating new views, compaction, etc. There's no reason logically to split them up.
The simple truth is that the DB doesn't care. Nor do the URLs. Nor do REST. You can easily create a logically similar URL structure within couch using views, or if you find that offensive you can use the built in URL Rewriting functionality with Couch.
REST cares about architecture. REST cares that you use unique URLs. REST cares that you provides links to other resources via their URLs using hypermedia. REST cares that you use ubiquitous media types. Pretty URLs are way down on the list of things REST cares about.
If you want to do REST, focus on architecture and media-types. URLs pretty much handle themselves.


text:
Q: Creación de tablas temporales en SQL Server Estoy usando SQL Sever. Mi duda es ¿puedo crear una tabla temporal sin definir sus columnas? o ¿existe alguna forma dinámica de crear una tabla temporal a partir de un SELECT Column1, Column2 FROM DBO.TBLDATACOPY?
El objetivo es crear una tabla temporal para almacenar los datos que devuelve un SELECT Column1, Column2 FROM DBO.TBLDATACOPY que se ejecuta mediante un EXECUTE sp_executesql. No puedo realizar lo siguiente SELECT * INTO #TBCOPY FROM (SELECT *FROM DBO.TBLDATACOPY) por que la tabla #TBCOPY se destruye al terminar el sp_executesql.

A: Sí no tienes más que utilizar un SELECT INTO:
 SELECT campo1, campo2 INTO #TablaTemporal FROM Tabla;

A: Ejecuta este ejemplo y me cuentas si se acerca a lo que necesitas, obviamente hacerlo dinámico no seria una opción.
USE tempdb
GO

-- Setup test data
IF OBJECT_ID('dept') IS NOT NULL DROP TABLE dept
CREATE TABLE dept ( deptId INT, deptName VARCHAR(30) )
GO
INSERT INTO dept VALUES ( 1, 'dept 1' ), ( 2, 'dept 2' )
GO

IF OBJECT_ID('#tmp') IS NOT NULL DROP TABLE #tmp
CREATE TABLE #tmp ( deptId INT, deptName VARCHAR(30) )

INSERT INTO #tmp
EXEC sp_executesql N'select * from dept'

SELECT * FROM #tmp

DROP TABLE #tmp

A: Hay una forma bastante rebuscada de hacerlo para mi gusto, paso a explicarte.
Normalmente cuando queremos crear una tabla temporal dinámicamente sin tener que definir el CREATE en primer lugar, lo que hacemos es:
SELECT *
       INTO #TMP
       FROM tabla_fisica

Esto mismo con el resultado de un SP no es posible hacerlo, si podemos hacer un INSERT INTO, pero claramente para esto, debemos conocer la estructura y haber creado la tabla en primer lugar. Una alternativa, es hacer pasar la ejecución del SP por un OPENROWSET que de alguna manera simula un Tabla con los resultados, pero para hacer esto, nuestro SQL Server debe tener una configuración especial, por lo que lo primero es reconfigurarlo así:
sp_configure 'Show Advanced Options', 1
GO
RECONFIGURE
GO
sp_configure 'Ad Hoc Distributed Queries', 1
GO
RECONFIGURE
GO

Si tenemos posibilidad de mantener esta configuración, entonces podremos hacer:
SELECT * INTO #TMP FROM OPENROWSET('SQLNCLI', '(Server=local)\SQL2012;Trusted_Connection=yes;',
     'EXEC Base.Owner.MiSp')

Obviamente modificar el dsn de conexión según corresponda, en este ejemplo estamos usando la seguridad integrada, pero se puede configurar usuario/contraseña. Esto tiene sus inconvenientes, dsn en texto claro, un overhead por el uso del OPENROWSET, etc. Si uno puede vivir con esos inconvenientes, esta puede ser una alternativa válida.

A: Estas usando algun SP (Stored Procedure)? De ser asi, usa tu SELECT INTO convencionalmente, sin el # (Numeral) inicial y va a crear la tabla, trabaja con ella todo lo que necesites, eso si, eliminala antes de que termine el mismo el SP. De no ser asi, determina un mecanismo para eliminarla durante tu proceso para que no te quedes con la tabla de manera indefinida.

A: Puedes hacerlo de la siguiente manera:
   Select Column1, Column2, Column3
          Into #TuTablaTemporal
   From DBO.TBLDATACOPY

De esta manera puedes definir las columnas que quieres tener en tu tabla temporal, es decir si quieres que contenga todas las columnas de la tabla física o solo algunas en especifico, ademas puedes realizar un filtrado de los datos ya que puedes agregar WHERE ademas de hacer Join con otras tablas

A: Un CTE, le puede servir
USE Name_BD
Go
WITH nombreCTE  ( idProducto , Descripcion )

AS
(SELECT ProductDescriptionID, Description FROM Production.ProductDescription)

SELECT * FROM nombreCTE;


text:
Q: Node.js selenium webdriver - Get browser capabilities inside test? I'm using selenium webdriver on node.js (currently via webdriverio, but I don't mind switching to webdriverjs or wd).
I run some tests on different browsers and want to save results of each test along with information about the browser, for example:

*

*Test 1 - chrome - 199 assertions, 0 failures, 0 skipped

*Test 1 - IE9 - 199 assertions, 0 failures, 0 skipped

*etc..

How can I get the "desiredCapabilities" object from within the test?
Or how can I pass it to the test so it will be available?
EDIT
I found that browser.desiredCapabilities returns the requested capabilities object, but now I realize I actually need the "actual capabilities" used (for example if I ask for IE8 on a machine that only has IE11 I get IE11 but the desiredCapabilities object shows version=8).
I'm looking for a way to get the actual used browser capabilities, as documented on selenium wiki:

If a session cannot support a capability that is requested in the
  desired capabilities, no error is thrown; a read-only capabilities
  object is returned that indicates the capabilities the session
  actually supports.

A: Using WebDriverJS (which you mentioned you could switch to), you can use getCapabilities:
browser.getCapabilities().then(function (caps) {
    console.log(caps);
});

The code above will just dump the capabilities but you should use the methods of the Capabilities class to inspect the values. For instance:
browser.getCapabilities().then(function (caps) {
    console.log(caps.get("browserName"), caps.get("version"));
});


text:
Q: Can not build a mex file in octave using mkoctfile --mex I am trying to build a mex file in octave. The Octave instructions says that we need to use mkoctfile --mex to build one. The file I am trying to build is in the following path:
> C:\devwork\Octave\boosted\toolbox\channels\private\rgbConvert.cpp

When I write
> mkoctfile --mex rgbConvert.cpp

I get the following error:
> g++: error: rgbConvert.cpp: No such file or directory g++: fatal
> error: no input files compilation terminated.

Note: My current directory is set correct. It is at \devwork\Octave\boosted\toolbox\channels\private
Can some one explain me why am I getting this error.

A: The problem is resolved using: mkoctfile --mex -DMATLAB_MEX_FILE rgbConvertMex.cpp
Hence, if you want to convert any Matlab compiled .mex file to Octave executable file, do the following two steps:

*

*Modify wrappers.hpp file by adding #include <stdlib.h>

*Save the file.

*Simply run: mkoctfile --mex -DMATLAB_MEX_FILE file_name

*.o file will be created.

I did it using the same and it worked fine.
Eskapp was grateful enough to release the Octave compiled MEX files. You'll need to manually add the files to the main toolbox.Please find the link here:
https://github.com/Eskapp/Piotr_vision_extrafiles_Octave
Hope it helps others :)


text:
Q: a command for sherlock.py is interpreted differently from linux command line and java process api It sounds a little strange,doesn't it?
I am working with a project - https://github.com/sherlock-project/sherlock
I need to run this program using Java Process API.
Here is that program usage.
$ python3 sherlock.py --help
usage: sherlock.py [-h] [--version] [--verbose] [--rank]
               [--folderoutput FOLDEROUTPUT] [--output OUTPUT] [--tor]
               [--unique-tor] [--csv] [--site SITE_NAME]
               [--proxy PROXY_URL] [--json JSON_FILE]
               [--proxy_list PROXY_LIST] [--check_proxies CHECK_PROXY]
               [--timeout TIMEOUT] [--print-found]
               USERNAMES [USERNAMES ...]

I have a problem in using USERNAMES.
When I specify a username that has a white space, from command line it works well(The white space is interpreted well). Pay attention for the property - checking username .
// command to be executed
python3 ${SHERLOCK_HOME}/sherlock.py --print-found --timeout 10 "skoriy serhii"

[*] Checking username skoriy serhii on:
[+] 500px: https://500px.com/skoriy serhii
[-] Error Connecting: Aptoide
[-] Error Connecting: Basecamp
[+] CapFriendly: https://www.capfriendly.com/users/skoriy serhii

But,when I am using Java Process API , I get the following:
// command to be executed
python3 /home/gorilla/sherlock/sherlock.py --print-found --timeout 10 "skoriy serhii"

[*] Checking username "skoriy on:
[+] 500px: https://500px.com/"skoriy
[-] Error Connecting: Aptoide
[-] Error Connecting: Basecamp
[+] Bookcrossing: https://www.bookcrossing.com/mybookshelf/"skoriy/
[+] CapFriendly: https://www.capfriendly.com/users/"skoriy
[-] Error Connecting: Carbonmade
[+] CashMe: https://cash.me/$"skoriy
[+] Chatujme.cz: https://profil.chatujme.cz/"skoriy
[+] Cloob: https://www.cloob.com/name/"skoriy
[-] Error Connecting: Crevado

As you can see there is some troubles with interpretation of the username argument.
Here is java code.
public class Main {

public static void main(String[] args) {
    try {
        CommandBuilder commandBuilder = new CommandBuilder();
        String command = commandBuilder.user("skoriy serhii").build();
        System.out.println(command);
        Process process = Runtime.getRuntime().exec(command);
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = null;
        while ((line = reader.readLine()) != null)
            System.out.println(line);
        process.destroy();
        if (process.isAlive())
            process.destroyForcibly();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

//CommandBuilder.java
public class CommandBuilder {

private final static String BASE = "python3 /home/gorilla/sherlock/sherlock.py --print-found --timeout 10";
private StringBuffer buffer = new StringBuffer();

public CommandBuilder user(String user) {
    buffer.append(" \"" + user + "\" ");
    return this;
}

public String build() {
    return BASE + new String(buffer);
}

}


text:
Q: Unable to use Postgres DB in docker-compose - ECONNREFUSED I have a Node.js app and have set up docker-compose. I'm trying to use Postgres DB in the container.
Here is docker-compose
version: "3"
services:
  web:
    build: .
    ports:
      - "3000:3000"
    links:
      - redis
      - db
  angular: # image of nginx
    image: "qp-angular-nginx"
    ports:
      - "4200:80" # specify port forewarding

  redis:
    image: "redis:3"
    ports:
     - "6379:6379"
  db:
    image: "postgres:9.6"
    ports:
     - "5432:5432"
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
    volumes:
         - pgdata:/var/lib/postgresql/data
  dbadmin:
    image: "myimage/phppgadmin"
    ports:
         - "8085:80"
    environment:
        POSTGRES_HOST: db
        POSTGRES_PORT: 5432
volumes:
     pgdata:

I have the containers running successfully and even database connected, but I get this error when making a DB request
 "stack": {
        "code": "ECONNREFUSED",
        "errno": "ECONNREFUSED",
        "syscall": "connect",
        "address": "127.0.0.1",
        "port": 5432
    }

A: If you connect to the database from another docker container, use the service name in the connection string(db in your case). From the error message it seems that there is something wrong with your configuration. It tries to connect to localhost (127.0.0.1)

A: For those, you use more recent structure project with a config file like below:
require('dotenv').config();

module.exports = {
    development: {
        username: process.env.DB_USER,
        password: process.env.DB_PASSWORD,
        database: process.env.DB_NAME,
        host: process.env.APP_URL_DOCKER,
        dialect: 'postgres'
    },
    test: {
        username: process.env.DB_USER,
        password: process.env.DB_PASSWORD,
        database: process.env.DB_NAME,
        host: process.env.APP_URL_DOCKER,
        dialect: 'postgres'
    },
    production: {
        username: process.env.DB_USER,
        password: process.env.DB_PASSWORD,
        database: process.env.DB_NAME,
        host: process.env.APP_URL_DOCKER,
        dialect: 'postgres'
    }
};

You can specify the service name of your postgres database in your .envfile. And it should be good for you.
// .env file
APP_URL_LOCAL=127.0.0.1
APP_URL_DOCKER=db # database service name
APP_PORT=8000
APP_KEY=6dd63668dab9a309c7c59a2982126a43b064816925a40b9680d16e2665f41b676a87dae4d506712e6332479c82827993059ddefb607b65caa3534b66b20253ed

DB_USER=postgres
DB_PASSWORD=db_password
DB_NAME=db_name
DB_PORT_CONTAINER=5432
DB_PORT_LOCAL=5433


text:
Q: Solve system of linear equations $Ax=b$ with $x$ and $b$ partially known. I've been working on the finite element method and got stuck at the following point.
To solve the displacements in a mechanical rigid body we need to solve this system of equations:
$$Ku=f$$
The problem is that I do not know every value of $f$. On the other hand, I know a few values of $u$. In fact I know exactly the values of $u$ that are unknown for $f$. Maybe this small example helps:

I thought that there must be a way to transform this system of linear equations into a system where the rhs is fully known. Is there a way to do this?
I am very happy if someone could help me here.

A: I agree, being originated from something as concrete as mechanical rigid body, it feels like there must be a way to solve this completely.
At first glance, it is not clear what to do. When in doubt, let's apply the definition to expand the matrix multiplication and see what we get:
$$\begin{align}
\pmatrix{f_{x1} \\ f_{y1} \\ 0 \\ f_{y2} \\ f_{x} \\ f_{y}} &= 0 \pmatrix{k_{11} \\ k_{21} \\ k_{31} \\ k_{41} \\ k_{51} \\ k_{61}} + 0 \pmatrix{k_{12} \\ k_{22} \\ k_{32} \\ k_{42} \\ k_{52} \\ k_{62}} + u_{x2} \pmatrix{k_{13} \\ k_{23} \\ k_{33} \\ k_{43} \\ k_{53} \\ k_{63}} + 0 \pmatrix{k_{14} \\ k_{24} \\ k_{34} \\ k_{44} \\ k_{54} \\ k_{64}} + u_{x3} \pmatrix{k_{15} \\ k_{25} \\ k_{35} \\ k_{45} \\ k_{55} \\ k_{65}} + u_{y3} \pmatrix{k_{16} \\ k_{26} \\ k_{36} \\ k_{46} \\ k_{56} \\ k_{66}} \\
&= u_{x2} \pmatrix{k_{13} \\ k_{23} \\ k_{33} \\ k_{43} \\ k_{53} \\ k_{63}} + u_{x3} \pmatrix{k_{15} \\ k_{25} \\ k_{35} \\ k_{45} \\ k_{55} \\ k_{65}} + u_{y3} \pmatrix{k_{16} \\ k_{26} \\ k_{36} \\ k_{46} \\ k_{56} \\ k_{66}}
\end{align}$$
Next, remove the rows with $f_{x1}, f_{y1}$ and $f_{y2}$ since they are not known:
$$\pmatrix{0 \\ f_{x} \\ f_{y}} = u_{x2} \pmatrix{k_{33} \\ k_{53} \\ k_{63}} + u_{x3} \pmatrix{k_{35} \\ k_{55} \\ k_{65}} + u_{y3} \pmatrix{k_{36} \\ k_{56} \\ k_{66}}$$
Re-write it back into a linear system:
$$\pmatrix{0 \\ f_{x} \\ f_{y}} =\pmatrix{k_{33} & k_{35} & k_{36} \\ k_{53} & k_{55} & k_{56} \\ k_{63} & k_{65} & k_{66}} \pmatrix{u_{x2} \\ u_{x3} \\ u_{y3}}$$
Therefore, we now know $u_{x2}, u_{x3}$ and $u_{y3}$ by solving the above linear system.
Finally, from the first equation:
$$\pmatrix{f_{x1} \\ f_{y1} \\ f_{y2}}
= u_{x2} \pmatrix{k_{13} \\ k_{23} \\ k_{43}} + u_{x3} \pmatrix{k_{15} \\ k_{25} \\ k_{45}} + u_{y3} \pmatrix{k_{16} \\ k_{26} \\ k_{46}}$$
Re-write it back into matrix form:
$$\pmatrix{f_{x1} \\ f_{y1} \\ f_{y2}}
= \pmatrix{k_{13} & k_{15} & k_{16} \\ k_{23} & k_{25} & k_{26} \\ k_{43} & k_{45} & k_{46}} \pmatrix{u_{x2} \\ u_{x3} \\ u_{y3}}$$
We now know $f_{x1}, f_{y1}$ and $f_{y2}$ as well since $u_{x2}, u_{x3}$ and $u_{y3}$ are already known. Hence we have found all unknowns in the original linear system.


text:
Q: User permissions to /system files What is the best route to accomplish the following.
Let's say in my rails application I have folders:
/system/cms/attachments
/system/attachments/
/system/attachments/Project
/system/attachments/Meeting

Files are uploading into these folders and are web accessible. At this time I want to add some permissions to access them. If someone tries to access myapp/system/attachments/meetings/doc1.docx I want to ensure they are authenticate with the application. For another myapp/system/attachments/Project/doc2.docx I may want to check that the user has a certain role.
My thought was to setup some Rack Middleware to accomplish this, when I did this my middleware appears to handle all my requests expect for those is /system
Is there a configuration setting I can change to allow my Middleware to also interact with /system paths.
Is there a better, easier way to accomplish what I'm looking to do?
Essentially a route or something if path is like '/system/attachment/project/' run this block of logic. This logic may be somewhat complex and will require access to models and environment stuff.  It will then ultimately return the response of the file content or fail/redirect to insufficient permissions.
Appreciate your thoughts and dialog on this.  Thanks.

A: It would be better, and simpler to implement, to accomplish this by associating your uploads to a model and applying permissions to the models which will be used to initiate downloads.
Implementation overview

*

*Use Paperclip to upload files and associate them with a Model e.g. Attachment

*

*This will make it easy for users to upload files. A record will be created for each upload. The model will store the file_name and you'll be able to call @attachment.url to get the URL of the file to download for the user.

*Use CanCanCan to implement permissions on the Attachment model.

User's Workflow

*

*The user will be able to upload files, or the admin can manually upload files.

*Each upload will save an Attachment record to the db with a reference to the path where the file was uploaded to (Paperclip let's you configure this path so you can set it to your /system path.

*Show the users an index of Attachment's i.e. GET /attachments and when the user clicks to download one, your app will receive a request at GET /attachments/1

*Your controller will find it: @attachment = Attachment.find params[:id]

*Now you can do the permission check: authorize! @attachment, :read (this will be based off rules you set up in an ability.rb file)

*You can also choose to only display attachments that the user is allowed to see: @attachments = Attachment.accessible_by current_ability see https://github.com/ryanb/cancan/wiki/Fetching-Records

*If an AccessDenied error was raised (because the user didn't have permission for this attachment) then catch the error and render a flash message or something, otherwise

*Your controller will then initiate the download using send_data or send_file e.g. send_file @attachment.url, filename: @attachment.attachment_file_name, disposition: 'attachment'
This approach leverages existing upload and permissions libraries to accomplish your goal with minimal code on your part. An additional benefit is that users will never see the actual URL of the uploaded file, they will only see resourceful paths (e.g. /attachments/1) and you won't have to publicly expose your /system directory, which is a very good idea.


text:
Q: combining multiple SSAS queries as one dataset I have a fact-table with one date dimension linked three times to attributes for Ordered, Prepared and Shipped dates.  So, I am able to get counts on ordering, manufacturing and dispatch and currently I am running these as three separate excel pivot table requests and combining them into one graphs giving three bars per month.  I am wondering if there is a more sleek way I should be doing this by which I write a query which returns the three separate counts as individual measures rather than running the query three times doing it once against each dimension.
Currently, the fact table looks something like this: -
DEPID, PRODCODE, ORDERDATE, PROCESSDATE,SHIPDATE
001,001,20120101,20120102,20120104
002,001,20120103,20120105,20120106
003,002,20120104,20120106,20120107
004,002,20120105,20120107,20120108

A: You could create 3 calculated measures in the cube (Ordering Count, Manufacturing Count, Dispatch Count)...then just drag them into your pivot table in the values section and use a date dimension in the rows group.


text:
Q: Vuex useStore is giving me undefined in this component <template>
  <div :style="styles">
    <Spinner v-if="showSpinner" class="w-14 h-14" />

  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import Spinner from '../common/Spinner.vue';

export default defineComponent({
  name: 'FullQuestionnaire',
  components: { Spinner },
});
</script>

<script setup lang="ts">
import { withDefaults, defineProps, computed, ref, toRefs, watch } from 'vue';
import { useStore } from 'vuex';

const props = withDefaults(
  defineProps<{
    isLoading?: boolean;
    additions: AdditionalParameters;
    questionnaireConfig: QuestionnaireConfig;
    questionnaireStyling?: RawQuestionnaireStyles | null;
    submitAnswers: SubmitAnswersFunction;
    goBack: () => void;
  }>(),
  { isLoading: undefined, questionnaireStyling: null }
);
const store = useStore();

const redirectUrl = computed(
  () => thankYouScreenInfo.value.properties.redirect_url ?? ''
);

const processedRedirectUrl = computed(() => {
  const url = populatePlaceholdersInLinkQueryParameters(
    redirectUrl.value,
    ''
    // store.getters.userProfile
  );

});

</script>

Hi, I am new to Vue and still learning. As you can see in the code I am importing useStore from vuex but when I tried to console.log(store) after this declaration const store = useStore(); its giving me undefined.
Vue Document
When I look into the vuex documentation. the example is using the useStore when setting up. Can I call const store = useStore(); outside of the setup?
Why is that?


text:
Q: 404 in the backend in updating products/orders I am getting 404 Errorin backend on updating products, orders but nothing shows in system.log.
I can access the backend however with no troubles.What can cause this problem and how to fix it?


text:
Q: Where do I put classes in Symfony that are neither Controllers nor models? For my application bundle, I will need some classes that are neither controllers nor models. For instance, I would like to have a scorecard class that has members such as "skill", "efficiency", "beauty", etc. Also, it may have member method/getters like "meanScore".
Where would such a class go in the Symfony framework?

A: I agree with @Gordon that this sounds like a business object. But if you're sure that it isn't, your next step is to figure out how you would classify it. Is it a helper? An event listener? A utility class? Once you figure that out, ask yourself: is it specific to a bundle, or are you going to reuse it amongst projects?
Let's say you decide it's an event listener and belongs to the bundle. Put it in MyBundle/EventListener. If it's a helper, put it in MyBundle/Helper. Now if you plan on reusing it amonst projects (which in this case it actually doesn't sound like it, but bear with me...) you might be better off creating a place in vendor for it.
The important thing to remember is that because Symfony2 is so young, there isn't really a definitive list of best practices that answer questions like these. Right now it's kind of up to us to see what works, and what doesn't. It's like the wild west :)

A: The way I answer these sorts of questions for myself is I go to KnpBundles and check how other developers are doing it.
Another thing to note is that Symfony2 is all about freedom of choice when it comes to configuration. You can stick everything in Random folder for all Symfony2 kernel cares, as long as you set it up correctly. Well, that's probably taking it a bit to the extreme, but for example Listener or EventListener - no difference.
Now, if you'd ask me, I'd say that for the Scorecard - depending on where you're going to use it, either Service or Helper/Util
About the breadcrumb - seems like a good example for a twig extension.

A: Since this class apparently represents a business object from your Domain, it belongs to the Model.


text:
Q: CSRF Clarification I'm trying to determine whether the following can be classified as a CSRF (Cross-Site Request Forgery) vulnerability on a website:
If website-1.com contains the following code:   and "http://website-2.com/img.png" performs a 302 redirect to some sensitive content on website-1.com, such as http://website-1.com/delete.php?file=test.jpg and "test.jpg" is deleted succesfully, is that a CSRF attack, even though the malicious content was embedded on website-1.com and not on a 3rd party site?
Thank you for your help

A: Deleting with a simple GET request is a pretty bad practice and makes CSRF attacks easy.
Does plain link from website-2 to http://website-1.com/delete.php?file=test.jpg cause file to be deleted? If not, then there must be some sort of CSRF protection. But there are a lot of other things to be watched for to ensure CSRF is not possible (like if/how CSRF token is exactly implemented or what sort of user content sites allow, how much admins of both sites trust each other, etc). From your limited info, I'd consider website-1 vulnerable.


text:
Q: Get a thread by Id I worked in JMX java and I get all the thread IDs by using the getAllThreadIds () method of the interface ThreadMXBean but I need a way to kill the thread of a given ID.
for example:
ThreadMXBean tbean;
tbean = ManagementFactory.getThreadMXBean();
long[] IDs=tbean.getAllThreadIds();
//.... I need a way to kill the Threads which have this IDs

A: There is actually no good way to kill a thread in java. There used be an api called Thread.stop() but it is also deperecated. Check this link for more details why Thread.stop was bad and how we should be stopping a thread.
http://docs.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html
Getting just the thread id will not help you, you need to have the thread object reference to set a flag to stop that thread.

A: You can use this method:
static Map<Thread,StackTraceElement[]>  getAllStackTraces()

to get all threads, then traverse map by key and find appropriate thread.
But this is a very bad approach. How are you going to stop thread? Using void stop() method? Id suggest using Executor framework in conjunction with interruption mechanism.

A: Thread.getAllStackTraces returns all stack traces of all live threads Map<Thread,StackTraceElement[]>. These are supposed to be the same threads that ThreadMXBean returns. You can extract threads from this map and interrupt them. Note that there is no legal method in Java to kill a thread.

A: You can try this:
public void printAllThreadIds() {
    Thread currentThread = Thread.currentThread();
    ThreadGroup threadGroup = getRootThreadGroup(currentThread);
    int allActiveThreads = threadGroup.activeCount();
    Thread[] allThreads = new Thread[allActiveThreads];
    threadGroup.enumerate(allThreads);

    for (int i = 0; i < allThreads.length; i++) {
        Thread thread = allThreads[i];
        long id = thread.getId();
        System.out.println(id);
    }
}

private static ThreadGroup getRootThreadGroup(Thread thread) {
    ThreadGroup currentGroup = thread.getThreadGroup();

    ThreadGroup parentGroup;
    while ((parentGroup = currentGroup.getParent()) != null) {
        currentGroup = parentGroup;
    }

    return currentGroup;
}

But you should interrupt a Thread and not stop it.
The Thread.stop() method is deprecated, because it immediately kills a Thread. Thus data structures that are currently changed by this Thread might remain in a inconsistent state. The interrupt gives the Thread the chance to shutdown gracefully.


text:
Q: What do I need to learn to code an app like Snapchat? I am new to programming and have been learning for the past month. I am trying to build an app that can record and upload short videos like Snaps to a database. Then the app can access these videos from the database. I am learning Java and Android Studio currently to make the Android version of the app, but later I want to learn the iOS side to make the iOS version of this app.
I would deeply appreciate some guidance on what exactly I need to learn to be able to make this app myself.

A: Well you can get started with the Camera API(updated to Camera2 API) and the CameraX API which will help you with photography on Android devices.
Camera2API described here
CameraAPI Documentation
Video Recording Documentation
CameraX Documentation
Regarding storage, I suggest that you start with what is provided in the Google Documentation and work your way up from there.
Storing files on android
The best way to learn is by using the Android Developer Guides as a base and StackOverflow posts to clarify implementation problems and troubleshooting.
Cheers!


text:
Q: Spring MVC Request processing failed My spring MVC controller keep getting org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
My code is as followed:
movie.jsp
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
 <%@page contentType="text/html" pageEncoding="UTF-8"%>
 <!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>

    <c:choose>
    <c:when test="true">

Please enter the details below:

        <form:form method="POST" commandName="movie">

Lead Actor:	<form:input path="actor"/>

Lead Actress:	<form:input path="actoress"/>

Genre:	<form:input path="genre"/>

Year:	<form:input path="year"/>

                <form:hidden path="way" value="add"/>
                <form:hidden path="page" value="5"/>
                <input type="submit" value="Add Moives"/>
        </form:form>

     </c:when>
     <c:when test="${requestScope.page eq '2'}">

Searching Movies

        <form:form method="POST" commandName="movie">
            Keyword:<form:input path="key"/>

            <form:radiobutton path="search" value="title"/>Search By Title

            <form:radiobutton path="search" value="actor"/>Search By Actor

            <form:radiobutton path="search" value="actress"/>Search By Actress

            <form:hidden path="way" value="browse"/>
            <form:hidden path="page" value="5"/>
            <input type="submit" value="Search Moives"/>
        </form:form>
    </c:when>
    <%-- <c:when test="${requestScope.page eq '3'}">

Add movie successful

     </c:when>
    <c:when test="${requestScope.page eq '3'}">

Movie Title:${requestScope.title}

Actor:${requestScope.actor}

Actress:${requestScope.actress}

Genre:${requestScope.Genre}

Year:${requestScope.Year}

    </c:when> --%>
    <c:otherwise>

Welcome to our Movie Store

Please make your selection below

        <form:form method="POST" action="movie.htm" commandName="movie">
            <form:select path="page">
                <form:option value="1">Add New Movie to Database</form:option>
                <form:option value="2">Browse Movies</form:option>
            </form:select>
            <input type="submit" value="Send"/>
        </form:form>
    </c:otherwise>
    </c:choose>

And here is my controller:
public class movieController extends SimpleFormController {

 public movieController() {
     //Initialize controller properties here or
    //in the Web Application Context

    setCommandClass(Movie.class);
    setCommandName("movie");
    setSuccessView("movie");
    setFormView("movie");
 }

/*
@Override
protected void doSubmitAction(Object command) throws Exception {
    throw new UnsupportedOperationException("Not yet implemented");
}
* */
//Use onSubmit instead of doSubmitAction
//when you need access to the Request, Response, or BindException objects

 @Override
 protected ModelAndView onSubmit(
 HttpServletRequest request,
 HttpServletResponse response,
 Object command,
 BindException errors) throws Exception {
 //Do something...
 Movie movie = new Movie();
 String page = movie.getPage();
 if(page.equals("1")||page.equals("2")){
     request.setAttribute("page",'1');
 }
 else{
    Connection con = null;
Statement statement = null;
ResultSet st = null;
    if(movie.getWay().equals("add")){
        String title = movie.getTitle();
        title = title.replaceAll("[^A-Za-z0-9\\s]","");
        String actor = movie.getActor();
        actor = actor.replaceAll("[^A-Za-z0-9\\s]","");
        String actress = movie.getActoress();
    actress = actress.replaceAll("[^A-Za-z0-9\\s]","");
        String genre = movie.getGenre();
        genre = genre.replaceAll("[^A-Za-z0-9\\s]","");
        String year_temp = movie.getYear();
        year_temp = year_temp.replaceAll("[^A-Za-z0-9\\s]","");
        int year = Integer.parseInt(year_temp);
        try{
                Class.forName("com.mysql.jdbc.Driver");
                con = DriverManager.getConnection("jdbc:mysql://localhost:3306/moviedb",
      "root","");
                String sql = "INSERT INTO movies (title,actor,actress,genre,year) VALUES
      ('"+title+"','"+actor+"','"+actress+"','"+genre+"','"+year+"')";
                statement = con.createStatement();
                statement.executeUpdate(sql);
        } catch (SQLException ex) {
    // TODO Auto-generated catch block
    System.out.println("error happend:" + ex);
        } catch (ClassNotFoundException e) {
    // TODO Auto-generated catch block
    System.out.println("error happend:" + e);
        }
        finally{
    try{
        if(statement != null) statement.close();
        if(con != null) con.close();
                    //request.setAttribute("page", "3");
    } catch (SQLException ex) {
        System.out.println("error happend:" + ex);
    }
        }
    }
    else{
        String search = movie.getSearch();
        String key = movie.getKey();
        key = key.replaceAll("[^A-Za-z0-9\\s]","");
        try{
            Class.forName("com.mysql.jdbc.Driver");
    con = DriverManager.getConnection("jdbc:mysql://localhost:3306/moviedb", "root","");
    String sql = "select * from movies where "+search+"='"+key+"'";
    statement = con.createStatement();
    st = statement.executeQuery(sql);
    while (st.next()) {
                request.setAttribute("page", "4");
                request.setAttribute("title",st.getString(1));
                request.setAttribute("actor",st.getString(2));
                request.setAttribute("actress",st.getString(3));
                request.setAttribute("Genre",st.getString(4));
                request.setAttribute("Year",st.getInt(5));
    }
        } catch (SQLException ex) {
    // TODO Auto-generated catch block
    System.out.println("error happend:" + ex);
        } catch (ClassNotFoundException e) {
    // TODO Auto-generated catch block
    System.out.println("error happend:" + e);
        }
        finally{
    try{
                if(st != null) st.close();
                if(statement != null) statement.close();
                if(con != null) con.close();
    } catch (SQLException ex) {
                System.out.println("error happend:" + ex);
    }
        }
    }
 //End
 }
 return new ModelAndView("movie","movie",movie);
 }
}

Thanks a lot!

A: These lines look to be the problem in your onSubmit():
Movie movie = new Movie();
String page = movie.getPage();

You are creating a new Movie object rather than casting and assigning the command object from the onSubmit() parameter, shouldn't it be:
Movie move = (Movie)command;
String page = movie.getPage();


text:
Q: Building packages with Rcpp, Attributes not handled correctly I've been playing around with setting up an R package which aims to make use of Rcpp in RStudio, but I'm struggling to get things to work properly with Rcpp Attributes.
My understanding of how this works is fairly tenuous, but my understanding is as follows:

*

*In the source C++ files, you can add Rcpp Attributes, for example the tag // [[Rcpp::export]] marks a C++ function for exporting, making it available for R.

*When you do Build the package, Rcpp then generates the appropriate C++ code in the file RcppExports.cpp, and wrapper functions in the R source file RcppExports.R.

This doesn't seem to be working properly (as I expect) when I build my package. Roxygen isn't playing nicely with this when generating the NAMESPACE file (so i've disabled that). The tag // [[Rcpp::export]] seems to just mark the function for exporting to R, rather than also marking a function for being exported to the package Namespace.
More importantly, the Rcpp Attribute tag // [[Rcpp::depends()]] isn't being handled correctly. If I copy the code here into a new source file, and rebuild my package, gcc throws errors on the RcppExports.cpp file saying that the BigMatrix identifier is undeclared indicating that the attribute tage // [[Rcpp::depends(bigmemory)]] isn't being handled correctly.
Since multiple things aren't working as I would expect, What am I missing in my understanding of Rcpp Attribute tags?

A: // [[Rcpp::export]] doesn't export functions to the package NAMESPACE, it just says "we should make this function available to R" -- it's still up to you on how you want to manage this function in your namespace.
Roxygen works to parse roxygen tags from source file comments; you'll have to include an //' @export tag in your .cpp source files, as partially described in 3.4 of the attributes vignette.
For your second problem, you still need to make sure bigmemory is in your Depends: and LinkingTo: sections of your DESCRIPTION file. I suppose one might prefer for // [[Rcpp::depends]] to automatically modify the package DESCRIPTION file, but it's easy enough to do yourself.
There was also a similar discussion here on the RStudio help boards.

A: This is an issue with the RcppExports.cpp file that is generated. At the moment, there is no way to teach it to include header files from somewhere else, so it just does not include bigmemory/MatrixAccessor.hpp.
A workaround is to do this:
#include <Rcpp.h>
#include <bigmemory/MatrixAccessor.hpp>

Rcpp::NumericVector BigColSums(Rcpp::XPtr<BigMatrix> pBigMat) {

    // Create the matrix accessor so we can get at the elements of the matrix.
    MatrixAccessor<double> ma(*pBigMat);

    // Create the vector we'll store the column sums in.
    Rcpp::NumericVector colSums(pBigMat->ncol());
    for (size_t i=0; i < pBigMat->ncol(); ++i)
        colSums[i] = std::accumulate(ma[i], ma[i]+pBigMat->nrow(), 0.0);
    return colSums;
}

// [[Rcpp::export]]
Rcpp::NumericVector BigColSums( SEXP pBigMat ){
    return  BigColSums( Rcpp::XPtr<BigMatrix>( pBigMat) ) ;
}

So that you capture the type in your .cpp file and RcppExports.cpp only has to know about SEXP.


text:
Q: PySpark - String matching to create new column I have a dataframe like:
ID             Notes
2345          Checked by John
2398          Verified by Stacy
3983          Double Checked on 2/23/17 by Marsha

Let's say for example there are only 3 employees to check: John, Stacy, or Marsha. I'd like to make a new column like so:
ID                Notes                              Employee
2345          Checked by John                          John
2398         Verified by Stacy                        Stacy
3983     Double Checked on 2/23/17 by Marsha          Marsha

Is regex or grep better here? What kind of function should I try? Thanks!
EDIT: I've been trying a bunch of solutions, but nothing seems to work. Should I give up and instead create columns for each employee, with a binary value? IE:
ID                Notes                             John       Stacy    Marsha
2345          Checked by John                        1            0       0
2398         Verified by Stacy                       0            1       0
3983     Double Checked on 2/23/17 by Marsha         0            0       1

A: In short:

regexp_extract(col('Notes'), '(.)(by)(\s+)(\w+)', 4))
This expression extracts employee name from any position where it is after by then space(s) in text column(col('Notes'))

In Detail:
Create a sample dataframe
data = [('2345', 'Checked by John'),
('2398', 'Verified by Stacy'),
('2328', 'Verified by Srinivas than some random text'),
('3983', 'Double Checked on 2/23/17 by Marsha')]

df = sc.parallelize(data).toDF(['ID', 'Notes'])

df.show()

+----+--------------------+
|  ID|               Notes|
+----+--------------------+
|2345|     Checked by John|
|2398|   Verified by Stacy|
|2328|Verified by Srini...|
|3983|Double Checked on...|
+----+--------------------+

Do the needed imports
from pyspark.sql.functions import regexp_extract, col

On df extract Employee name from column using regexp_extract(column_name, regex, group_number).
Here regex('(.)(by)(\s+)(\w+)') means

*

*(.)   - Any character (except newline)

*(by)  - Word by in the text

*(\s+) - One or many spaces

*(\w+) - Alphanumeric or underscore chars of length one

and group_number is 4 because group (\w+) is in 4th position in expression
result = df.withColumn('Employee', regexp_extract(col('Notes'), '(.)(by)(\s+)(\w+)', 4))

result.show()

+----+--------------------+--------+
|  ID|               Notes|Employee|
+----+--------------------+--------+
|2345|     Checked by John|    John|
|2398|   Verified by Stacy|   Stacy|
|2328|Verified by Srini...|Srinivas|
|3983|Double Checked on...|  Marsha|
+----+--------------------+--------+

Databricks notebook
Note:

regexp_extract(col('Notes'), '.by\s+(\w+)', 1)) seems much cleaner version and check the Regex in use here

A: Brief
In its simplest form, and according to the example provided, this answer should suffice, albeit the OP should post more samples if other samples exist where the name should be preceded by any word other than by.

Code
See code in use here
Regex
^(\w+)[ \t]*(.*\bby[ \t]+(\w+)[ \t]*.*)$

Replacement
\1\t\2\t\3

Results
Input
2345          Checked by John
2398          Verified by Stacy
3983          Double Checked on 2/23/17 by Marsha

Output
2345    Checked by John John
2398    Verified by Stacy   Stacy
3983    Double Checked on 2/23/17 by Marsha     Marsha

Note: The above output separates each column by the tab \t character, so it may not appear to be correct to the naked eye, but simply using an online regex parser and inserting \t into the regex match section should show you where each column begins/ends.

Explanation
Regex

*

*^ Assert position at the beginning of the line

*(\w+) Capture one or more word characters (a-zA-Z0-9_) into group 1

*[ \t]* Match any number of spaces or tab characters ([ \t] can be replaced with \h in some regex flavours such as PCRE)

*(.*\bby[ \t]+(\w+)[ \t]*.*) Capture the following into group 2

*

*.* Match any character (except newline unless the s modifier is used)

*\bby Match a word boundary \b, followed by by literally

*[ \t]+ Match one or more spaces or tab characters

*(\w+) Capture one or more word characters (a-zA-Z0-9_) into group 3

*[ \t]* Match any number of spaces or tab characters

*.* Match any character any number of times

*$ Assert position at the end of the line

Replacement

*

*\1 Matches the same text as most recently matched by the 1st capturing group

*\t Tab character

*\1 Matches the same text as most recently matched by the 2nd capturing group

*\t Tab character

*\1 Matches the same text as most recently matched by the 3rd capturing group

A: When I read the question again, the OP may speak of a fixed list of employees ("Let's say for example there are only 3 employees to check: John, Stacy, or Marsha").
If this is really a known list, then the simplest way is to check against this list of names with word boundaries:
regexp_extract(col('Notes'), '\b(John|Stacy|Marsha)\b', 1)

A: Something like this should work
import org.apache.spark.sql.functions._
dataFrame.withColumn("Employee", substring_index(col("Notes"), "\t", 2))

In case you want to use regex to extract the proper value you need something like
 dataFrame.withColumn("Employee", regexp_extract(col("Notes"), 'regex', <groupId>)


text:
Q: Relation between HCF, LCM and product of multiple numbers It is well known that for two numbers $a $ and $b$, $$\text {lcm} (a,b)\times \text {hcf} (a,b)=ab$$ Does there exist a similar equality/ inequality between HCF, LCM and product of multiple numbers? (i.e. some relation between $\text {hcf} (a_1,a_2,...,a_n)$, $\text{lcm} (a_1,a_2,...,a_n)$ and $a_1\times a_2 \times ...\times a_n$)

A: You cannot express $a_1a_2\dots a_n$ in terms of $\gcd(a_1,a_2,\dots,a_n)$ and $\operatorname{lcm}(a_1,a_2,\dots,a_n)$ in any way if $n>2$.  For instance, if $n=3$, note that $\{2,4,16\}$ and $\{2,8,16\}$ have the same GCD and LCM, but they have different products.  You can find similar examples for any $n>2$.
For an inequality, I don't know what sort of thing you're looking for.  But it is straightforward to see that $$\gcd(a_1,a_2,\dots,a_n)\operatorname{lcm}(a_1,a_2,\dots,a_n)\leq a_1a_2\dots a_n$$
whenever $n\geq 2$ (just compare the $p$-adic valuations of both sides for each prime $p$--the left-hand side is the sum of the valuations of two of the $a_i$, while the right-hand side is the sum of the valuations of all of them).

A: Not with just product.
The product of the lcm and hcf of $(2,2,2)$ is $4$. For $(1,1,8)$ it is $8$. But $2\times 2\times 2=1\times 1\times 8$.
Thus the product of lcm and hcf is not a function of the product of the three numbers.
Similarly, note that $(2,2,4)$ and $(2,4,4)$ have the same lcm and hcf. But their products are different, so the product of three numbers is not a function of their lcm and hcf.


text:
Q: Calling native method from eclipse plugin I am succeeded to call a c++ library from my JAVA code using JNI.Now I want to load the same. dll from a eclipse plugin and call the library functions.I kept the library in root directory of the plugin folder .
I am getting error like:
Caused by: java.lang.UnsatisfiedLinkError: testproj.testClass.testCall:()V
please help me to resolve that.Why the same code working for Java but not working from plugin?

A: Got it the package and class name should be same in the plug in and also the dll should be in the same root folder of the .java file where u load the library


text:
Q: why foreign key doesn't work in websql..? i try to use foreign key in my app using web sql.. i test it in chrome.. no error.. but when i test with manual insert to table img (contain FK)
i expect to fail.. but insert is still succes..  this is my code.. please help me..
tx.executeSql("PRAGMA foreign_keys = ON;");
tx.executeSql("CREATE TABLE IF NOT EXISTS img (ID INTEGER PRIMARY KEY ASC,imgID VARCHAR, image VARCHAR,  FOREIGN  KEY (imgID) REFERENCES trans (ID) )", []);

i this case i try to use FK method for save my image name data and connect to trans table..
my insert code
tx.executeSql("insert into img (imgID,image) values ('100','23.jpg')");

A: Is the INSERT performed on the same database connection as the CREATE? Because the PRAGMA foreign_keys = ON is only valid for the connection.  It has to be executed for each connection you open.
Also, make sure that you run that PRAGMA statement when you're not in a transaction, since that wouldn't have any effect.  Your example code starting with tx. suggests that is the cause of your problem.
UPDATE
As pointed out in the comments by MisterSmith, extensions of Chromium-based browsers can't run SQL statements outside a transaction anyway, so no foreign key enforcement is possible.
So, you'll have to ensure your foreign keys maintain integrity either in your application code, or you can write triggers to enforce the foreign keys (if triggers are permitted to Chromium extensions, that is).


text:
Q: Fatal Error: Main. Application Forced closed Im designing my first android application and keep coming up with the following error which is draining the life out of me and I do not understand it very well (Please find my Logcat (verbose), Java Code(this i played around with and this began to occur once started to work on my editButton and buttonUpdate bit. Does it have anything to do with the editStatus? I really think it may) and I have also put in my manifest file:
LOGCAT verbose
04-21 15:30:23.388: D/AndroidRuntime(276): Shutting down VM
04-21 15:30:23.388: W/dalvikvm(276): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
04-21 15:30:23.427: E/AndroidRuntime(276): FATAL EXCEPTION: main
04-21 15:30:23.427: E/AndroidRuntime(276): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.locator.demo/com.locator.demo.LocatorDemoActivity}: java.lang.ClassCastException: android.widget.TextView
04-21 15:30:23.427: E/AndroidRuntime(276):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
04-21 15:30:23.427: E/AndroidRuntime(276):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
04-21 15:30:23.427: E/AndroidRuntime(276):  at android.app.ActivityThread.access$2300(ActivityThread.java:125)
04-21 15:30:23.427: E/AndroidRuntime(276):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
04-21 15:30:23.427: E/AndroidRuntime(276):  at android.os.Handler.dispatchMessage(Handler.java:99)
04-21 15:30:23.427: E/AndroidRuntime(276):  at android.os.Looper.loop(Looper.java:123)
04-21 15:30:23.427: E/AndroidRuntime(276):  at android.app.ActivityThread.main(ActivityThread.java:4627)
04-21 15:30:23.427: E/AndroidRuntime(276):  at java.lang.reflect.Method.invokeNative(Native Method)
04-21 15:30:23.427: E/AndroidRuntime(276):  at java.lang.reflect.Method.invoke(Method.java:521)
04-21 15:30:23.427: E/AndroidRuntime(276):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-21 15:30:23.427: E/AndroidRuntime(276):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-21 15:30:23.427: E/AndroidRuntime(276):  at dalvik.system.NativeStart.main(Native Method)
04-21 15:30:23.427: E/AndroidRuntime(276): Caused by: java.lang.ClassCastException: android.widget.TextView
04-21 15:30:23.427: E/AndroidRuntime(276):  at com.locator.demo.LocatorDemoActivity.onCreate(LocatorDemoActivity.java:21)
04-21 15:30:23.427: E/AndroidRuntime(276):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-21 15:30:23.427: E/AndroidRuntime(276):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
04-21 15:30:23.427: E/AndroidRuntime(276):  ... 11 more
04-21 15:35:23.607: I/Process(276): Sending signal. PID: 276 SIG: 9
04-21 15:50:32.127: D/AndroidRuntime(301): Shutting down VM
04-21 15:50:32.127: W/dalvikvm(301): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
04-21 15:50:32.147: E/AndroidRuntime(301): FATAL EXCEPTION: main
04-21 15:50:32.147: E/AndroidRuntime(301): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.locator.demo/com.locator.demo.LocatorDemoActivity}: java.lang.ClassCastException: android.widget.TextView
04-21 15:50:32.147: E/AndroidRuntime(301):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
04-21 15:50:32.147: E/AndroidRuntime(301):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
04-21 15:50:32.147: E/AndroidRuntime(301):  at android.app.ActivityThread.access$2300(ActivityThread.java:125)
04-21 15:50:32.147: E/AndroidRuntime(301):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
04-21 15:50:32.147: E/AndroidRuntime(301):  at android.os.Handler.dispatchMessage(Handler.java:99)
04-21 15:50:32.147: E/AndroidRuntime(301):  at android.os.Looper.loop(Looper.java:123)
04-21 15:50:32.147: E/AndroidRuntime(301):  at android.app.ActivityThread.main(ActivityThread.java:4627)
04-21 15:50:32.147: E/AndroidRuntime(301):  at java.lang.reflect.Method.invokeNative(Native Method)
04-21 15:50:32.147: E/AndroidRuntime(301):  at java.lang.reflect.Method.invoke(Method.java:521)
04-21 15:50:32.147: E/AndroidRuntime(301):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-21 15:50:32.147: E/AndroidRuntime(301):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-21 15:50:32.147: E/AndroidRuntime(301):  at dalvik.system.NativeStart.main(Native Method)
04-21 15:50:32.147: E/AndroidRuntime(301): Caused by: java.lang.ClassCastException: android.widget.TextView
04-21 15:50:32.147: E/AndroidRuntime(301):  at com.locator.demo.LocatorDemoActivity.onCreate(LocatorDemoActivity.java:21)
04-21 15:50:32.147: E/AndroidRuntime(301):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-21 15:50:32.147: E/AndroidRuntime(301):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
04-21 15:50:32.147: E/AndroidRuntime(301):  ... 11 more

CODE:
package com.locator.demo;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class LocatorDemoActivity extends Activity implements OnClickListener {
    EditText editStatus;
    Button buttonUpdate;

     /** Called when the activity is first created. */
     @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.locationstatus);

        editStatus = (EditText)findViewById(R.id.edit_status);
        buttonUpdate = (Button)findViewById(R.id.button_update);
        buttonUpdate.setOnClickListener(this);

                //have button 'listen' for click

    }

    public void onClick(View arg0) {
        // TODO Auto-generated method stub

    }

}

ANDROID Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.locator.demo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_main" >
        <activity
            android:name=".LocatorDemoActivity"
            android:label="@string/app_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

I have;
attempted to do adb kill-server and adb start-server and run it with an without an emulator as suggested in another post.  Please be slightly understanding as my knowledge of eclipse and Java is pretty low and im learning.
Please help

A: As seen from this error:

java.lang.RuntimeException: Unable to start activity
  ComponentInfo{com.locator.demo/com.locator.demo.LocatorDemoActivity}:
  java.lang.ClassCastException: android.widget.TextView

And this one:

Caused by: java.lang.ClassCastException: android.widget.TextView

You are trying to cast a TextView to EditText ( in this line: editStatus = (EditText)findViewById(R.id.edit_status);).
Go to locationstatus.xml, and change the TextView with the id edit_status to EditText.


text:
Q: How to parse JSON into a single nested object with jq? I'm trying to parse a JSON file with jq but I can't get it right. How do I parse the following JSON to:

*

*A single nested object and also add additional top level keys ("cities", "uppsala", and "locations" in the example)

*Use the values for the keys name as keys for the objects?

(shortened version of source json):
{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {
        "name": "Uppsala domkyrka"
      },
      "geometry": {
        "coordinates": [
          17.6336159,
          59.8581466
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {
        "name": "Uppsala moské"
      },
      "geometry": {
        "coordinates": [
          17.6382165,
          59.874003
        ]
      }
    }
  ]
}

I'm trying to parse it to this format:
{
  "cities": {
    "uppsala": {
      "locations": {
        "Uppsala domkyrka": {
          "name": "Uppsala domkyrka",
          "coordinates": {
            "_latitude": 59.854,
            "_longitude": 17.6261
          }
        },
        "Uppsala moské": {
          "name": "Uppsala moské",
          "coordinates": {
            "_latitude": 59.8581,
            "_longitude": 17.6336
          }
        }
      }
    }
  }
}

This is the command I've arrived at so far:
[.features[] | {name: .properties.name, coordinates: {_latitude: .geometry.coordinates[0], _longitude: .geometry.coordinates[1]}}]

To produce this, which is not quite right:
[
  {
    "name": "Uppsala domkyrka",
    "coordinates": {
      "_latitude": 17.6336159,
      "_longitude": 59.8581466
    }
  },
  {
    "name": "Uppsala moské",
    "coordinates": {
      "_latitude": 17.6382165,
      "_longitude": 59.874003
    }
  }
]

I haven't managed to get the values for name as keys for the objects.
Any ideas? I've been reading SO for hours and pulling my hair out..

A: Since you want to hard-code the three top-most keys, the key to a solution is add:
{
  "cities": {
    "uppsala": {
      "locations":
        [.features[]
         | {name: .properties.name,
            coordinates:
              {_latitude: .geometry.coordinates[0],
               _longitude: .geometry.coordinates[1]
              }
            }
         | {(.name): .}
        ] | add
    }
  }
}

If you don't want the redundancy of the name, you could replace {(.name): .} with:
{(.name): del(.name)}

A more compact variant
The critical add gets a bit lost in the above, so you might like to consider this equivalent alternative:
[.features[]
 | {name: .properties.name,
    coordinates:
      { _latitude: .geometry.coordinates[0],
        _longitude: .geometry.coordinates[1]
      }
   } | {(.name): .} ]
| add as $v
| ({} | .cities.uppsala.locations = $v)


text:
Q: Which technique is most appropriate for identifing various sentiments in the same text using python? I'm studying NLP and as example I'm trying to identify what feelings are in customer feedback in the online course platform.
I was able to identify the feelings of the students with only simple sentence, such as "The course is very nice, I learned a lot from it", "The teaching platform is complete and I really enjoy using it", "I could have more courses related to marine biology", and so on.
My doubt is how to correctly identify the various sentiments in one sentence or in several sentences. For example:

*

*A sentiment per sentence:

*

*"The course is very good! it could be cool to create a section of questions on the site."

*More than one sentiment per sentence:

*

*"The course is very good, but the site is not."

*Involving both:

*

*"The course is very good, but the teaching platform is very slow. There could be more tasks and examples in the courses, interaction by video or microphone on the forum, for example."

I thought of splitting text in sentences, but it is not so good for the example 2.

A: You can think that comas, other punctuation marcs and some conjunctions and prepositions actually split sentences. This actually goes beyond code into the field of linguistics as they sometimes, but not always, separate sentences.
In the 2nd case you actually have two sentences: "The course is very good" -, but- "The site is not [very good]".
I believe there are NPL packages that can split sentences (Probably by knowing that most sentences follow the subject/predicate/object structure, so if you wind more than one verb then propbably you'll find the same ammount of sentences) and you could use those to parse your text first. Take a look for libraries doing that for your language of choice.

A: There is a lib specific for multi-label classification:
scikit-multilearn
when you train your model you have to split classes into binary columns.


text:
Q: DateTime stored as US in web app...need to change to UK? A table in my db 'DeliveryRunsHistory' has a column 'date', the user can select a date from the screen and search this table for any records which have the selected date, then display the results.
This works fine from my local machine but when I deploy the web application to the cloud and access it through the URL it doesnt. Result keep coming back as empty. Exactly the same code & DB as its just a copy.
Using Orchard 1.6 for this project I used Ilogger to record the process. After looking through the logs it seems if the date is below 12th of the month it will work. Any over and it wont. So im guessing this is because the time format is set to US, when I need it to be UK.
From the control panel on the cloud I have set it to UK and the date is showing in the bottom right as 03/10/2013.....So why is it checking it against US format.
tried googling it, got a couple of ans, but nothing concrete,
Anyone know how to change it?
ta

A: thanks to How to set Date and time format in IIS 7
I found that I had to change the 'Culture' & 'UI Culture' settings in the IIS from 'invariant' to 'english uk'