text:
Q: How to fix nav and scroll main? what I wanted is to make a design so that the nav remains fixed on top and main scroll. So when I gave position fixed to nav, it fixed its position, and the main shifted at the bottom of the nav. So to make main visible I gave margin-top 60px. But It shifts complete div instead main. I want to know what breaks my design and how to fix it.
https://codepen.io/kumarmasterpraveen/pen/qBaoZYx?editors=1100
html

     navigation
     main content

css
nav {
    position: fixed;
    background-color: seagreen;
    height: 60px;
    width: 100%;
}

main {
    margin-top: 60px;
}

A: just put  in nav element  ,  top:0;   and will worked

html {
}

body {
overflow:hidden;
}

nav{
  position: fixed;
  background-color: seagreen;
  height: 60px;
  width: 100%;

  top:0;
}

main{
  overflow-y:scroll!important;
  width:auto;
 height:700px;
  min-height:100%;
}

   navigation
   main content

A: To do what you try to do according to the comments (having only the scrollbar for the main-content you can use flexbox and CSS-Grid. I have a solution with using CSS-Grid. You declare the body as box-sizing: border-box; and set a definite height of height: 100vh; to span the entire browser height. Same for width with width: 100vw;. Then you use 2 rows by using grid-template-rows: 60px auto;. Thatw ay, the first element (the navbar) will be 60px height and the main content be the entire remaining height of the browser. Last but not least you add an overflow rule to the main content with overflow-y: auto;

body {
  margin: 0;
  box-sizing: border-box;
  height: 100vh;
  width: 100vw;
  display: grid;
  grid-template-rows: 60px auto;
}

nav {
  padding: 10px;
}

main {
  overflow-y: auto;
  padding: 10px;
}

  Navigation

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

As you cant use grid: You can also do it without grid, however it is more tricky. You can use the calc function to make the height of the content as heigh as the remaining viewport height with `height: calc(100vh - 60px); as in the snippet below.

body {
  margin: 0;
  box-sizing: border-box;
  height: 100vh;
  width: 100vw;
}

nav {
  box-sizing: border-box;
  padding: 10px;
  height: 60px;
}

main {
  box-sizing: border-box;
  overflow-y: auto;
  padding: 10px;
  height: calc(100vh - 60px);
}

  Navigation

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.


text:
Q: Writing a file not performed when writing task is handled in onLocationChanged() I am trying to write the latitude and longitude formed by the location manager to a file but the write operation doesn't work for some reason. The following is the code I have been trying with.
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        File absPath = getFilesDir();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Acquire a reference to the system Location Manager
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

// Define a listener that responds to location updates
        LocationListener locationListener = new LocationListener() {
            public void onLocationChanged(Location location) {

                String filename = "myfile";
                FileOutputStream outputStream;
                try {
                    outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
                    outputStream.write((location.getLatitude()+","+location.getLongitude()).getBytes());
                    outputStream.close();
                }catch (Exception e) {
                    e.printStackTrace();
                }

            }

            public void onStatusChanged(String provider, int status, Bundle extras) {
            }

            public void onProviderEnabled(String provider) {
            }

            public void onProviderDisabled(String provider) {
            }

        };
        locationManager.requestLocationUpdates(NETWORK_PROVIDER, 0, 0, locationListener);
   }
}

Any help is appreciated. Thank You.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Spring boot azure active directory multiple client-id I have a Spring boot app that use azure active directory with front-end authentication here the microsoft page that I used.
This app is the back-end and I would use for many front-end apps.
How can I set in application.properties all different valid client-id for every front-end apps?


text:
Q: AltBeacon - Detect RadiusNetwork USB Beacon - How to get correct BeaconLayout I am trying to use AltBeacon to detect RadiusNetwork beacons. I am aware that i need to use setBeaconLayout() to get beacons(other than AltBeacons) detected. But, I am not sure how to get the Layout for the beacons that i want to use. I am pretty new to beacons.
Right now i have RadiusNetwork beacon, with ID "2F234454-CF6D-4A0F-ADF2-F4911BA9FFA6" (for example), how do i get the Layout for this? I tried googling, but didn't get much help. Is there a way to get the layout pattern for devices? If at a later stage, i want to use some other device, how do i find the layout for that device?
Will this work?
mAllBeaconsRegion = new Region("RadBeacon USB",
                Identifier.parse("2F234454-CF6D-4A0F-ADF2-F4911BA9FFA6"),
                Identifier.parse("1"), Identifier.parse("1"));

A: I have used the following code below for RadBeacon. I am still not sure on how to get the correct BeaconLayout for a beacon, but the following worked for me.
    mBeaconManager
            .getBeaconParsers()
            .add(new BeaconParser()
                    .setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25"));

    mAllBeaconsRegion = new Region("RadBeacon",
            Identifier.parse("2F234454-CF6D-4A0F-ADF2-F4911BA9FFA6"),
            Identifier.parse("1"), Identifier.parse("1"));


text:
Q: How to use STI routes path? I have a STI models
class Fruit < ActiveRecord::Base; end
class Apple < Fruit; end
class Orange < Fruit; end

and routes:
resources :fruits
resources :apples, controller: 'fruits', type: 'Apple'
resources :oranges, controller: 'fruits', type: 'Orange'

the scaffold create the view which use new_fruit_path to create new fruit
when I go to localhost:3000\apples, and click new button, it will go to localhost:3000\fruits\new page.
Is there any way that going to the localhost:3000\apples\new page? I don't want to create a new view that with new_apple_path
Thanks.

A: Just do the following:
#config/routes.rb
resources :fruits #-> url.com/fruits/new

#app/controllers/fruits_controller.rb
class FruitsController < ApplicationController
   def new
      @type = params[:type].constantize if params[:type]
      @fruit = @type.new
   end
end

You'll then be able to use:
<%= link_to "New Apple", new_fruit_path(type: "apple") %>

... it will probably look crappy in the URL though: url.com/fruits/new?type=apple
--
Conversely, this would be prudent to look at your STI structure if you're having an issue like this. You might be better using an enum, removing the "subclass" layer which will just add complication for no reason.

BTW you might be able to use the polymorphic_path helper if you wanted to use a path helper and have it adapt to whichever object you pass.

A: Since you don't want to create a new view for a new specific product, you can just render the common view for new action for the all STI inherited classes, so:
class FruitsController < ApplicationController
   def new
      # do something
      render 'fruits/new'
   end


text:
Q: Pass column name as parameter for MySql function I am trying to write MySql function were I pass  table name used in a select statement this is a toy code explaining the issue I am facing.[Note : I don't want to use procedures !]
DROP FUNCTION IF EXISTS `P_AVG`;
DELIMITER $$
CREATE FUNCTION P_AVG(tblName CHAR(64)) RETURNS INT
BEGIN
    DECLARE cnt INT;
SELECT COUNT(*) INTO cnt FROM tblName;
return cnt;
END$$
DELIMITER ;

And then I try to execute the following
SELECT P_AVG("PARTSUPP");

I get the following error

ERROR 1146 (42S02): Table 'phpmyadmin.tblName' doesn't exist

A: To select the table at runtime - you need to use prepared statements - create the SQL as a string with the required table name. See third example : http://dev.mysql.com/doc/refman/5.7/en/sql-syntax-prepared-statements.html

A: Create a global variable to compose your SQL query dynamically and then let MySQL prepare a statement out of the composed SQL query string and execute it dynamically, in the form of a prepared statement.
As dynamic SQL is not allowed inside a Stored Function, you need to go for a STORED PROCEDURE.
This should do it for you:-
DROP PROCEDURE IF EXISTS `P_AVG`;
DELIMITER $$
CREATE PROCEDURE P_AVG(tblName CHAR(64))
BEGIN
  DECLARE cnt INT DEFAULT 0;
    IF CHAR_LENGTH(tblName) > 0 THEN
       SET @DYNAMIC_QUERY = CONCAT('SELECT COUNT(*) INTO cnt FROM ', tblName);
       PREPARE STMNT FROM @DYNAMIC_QUERY;
       EXECUTE STMNT;
       DEALLOCATE PREPARE STMNT;
    END IF;
  SELECT cnt; /* The return statement becomes a regular `SELECT` statement,
                 although an OUT parameter also can be used instead. */
END$$
DELIMITER ;

CALL P_AVG('ACCOUNT'); -- Example procedure call


text:
Q: Rearranging $\left| \sqrt{x} -\sqrt{y} \right| $ I'm just going through an example of a Holder function ($f(x) = \sqrt{x}$), and a step in the example goes as follows,
$$\left| \sqrt{x} -\sqrt{y} \right| = \frac{\left|x-y\right|}{\sqrt{x}+\sqrt{y}}$$
I've been fiddling around with this for half an hour and cannot see how to get the RHS from the left.
Thanks in advance.

A: $(\sqrt x-\sqrt y)(\sqrt x+\sqrt y) = (\sqrt x)^2 - (\sqrt y)^2 = x - y$


text:
Q: Incorporating Open ID with my current login System? I am currently setting up Open ID authentication in my website and I am having troubles incorporating it with my current Login System and database... I've read the article at Plaxo & it recommends this type of table to store the openid info...
create table user_openids (
  openid_url varchar(255) not null,
  primary key (openid_url),

  user_id int not null,
  index (user_id)
);

This is my current Users-info table
Userid(PRIMARY) | username(UNIQUE) | password | Email

Userid is used to reference user-details for comments, ratings etc. (So it goes into the comments table and the ratings table as a User identifier)

I want a system similar to what Stack overflow uses just login using your Open ID and it gives you an unknown(OPENID-provider) display name.... while keeping my current login system intact.
1) How can I add Open ID details of users to my current Users-Info Table without affecting the current login setup?
2) Currently I use User-id(generated unique for every user) to store in the session to maintain Login. What should I do now in case of Open ID?

*My Thoughts(I don't know if I am right or not)
- Add an open-id field to store the unique open id url provided by the open id provider for each user and set it to null for non-open-id-users.
- Make User-id a text field and store a md5 of the open id url.(store this in session to maintain Login).
- I have no idea how can I handle Display-name/Username which is set to unique for each user because I would like to show unknown(OPENID_provider) (for users using open-id) which can be changed from the profile settings...

Any suggestions would be helpful....Thanks

A: The idea with the table layout you show is to have a 1:many from users:openids.
Thus, no changes to the users table are needed.
When someone logs in with an OpenID, you check if that OpenID is in the openids table.  If so, you have the user_id of the user and you are done.
Otherwise create a new user (with no username/password set) and insert an (openid,user_id) pair for them into the openids table.
You template can display whatever nice placeholder (such as their OP, or whatever) where it would normally display username for users whose username is blank.
Hopefully you already disallow logging in with blank passwords, so there should be no security issue there.

A: What about this?

*

*Add a display_name column to the users table, which doesn't have to be unique.

*Make username and password in users optional

*When somebody registers with OpenID, create a row in users with empty username/password and display name set to "unkonwn (provider)".

*Allow users to set username/password, if they want to switch to password-based login.

*Allow users to manage their OpenIDs, so that existing users can switch to OpenID-based login.

This means that users can have username/password, but they don't have to. They also can have one or multiple OpenIDs, but they don't have to. They can use non-unique display name.

A: Option 1: Only one login type is allowed
Here's my suggestion (UPDATED to prevent the need to edit all business logic related to username):

*

*Create a new column called loginid to allow the storage of OpenIDs and old usernames, Add the UNIQUE INDEX on this column as well.

*Populate loginid with existing data from username

*DELETE INDEX from username to allow them to be non-unique. When creating a new user from OpenID, set username value to unknown(google) as described.

*Keep password for legacy logins, ignore it for OpenID.

*Update only the AUTH portion of your code to look for loginid rather than username.

Option 2: Allow multiple logins (also easily extends to linking multiple profiles from various sources)

*

*Create a new table to stand as a master user table and contain all required fields per user (maybe email from your example above).

*Create a table to store authentication containing: userid (FK to master record), username (stores the username appropriate to the login scheme), password
There are obviously flaws with both of these options, but it will hopefully get you started in the right direction.


text:
Q: Multiple Session Instances Codeigniter So I have an app built using Codeigniter and we are experiencing some trouble when a session is loaded and someone loads another URL that would start a session with the same app.
The problem is that the second session is overwriting the initial session (at least partially) and corrupting the data being sent.
We are using database sessions and encryption.
Looking for help on this. Thanks in advance.

A: Here's a previous thread for you:
Multiple PHP Sessions
Another thing not mentioned in that thread is, if you need multiple sessions for the same data/data placeholders, to prepend the session variables with identifying prefixes, e.g.:
$_SESSION['ss1_name'] = "Session 1 Name";

...

$_SESSION['ss2_name'] = "Session 2 Name";

Hope this helps!


text:
Q: Drag And Drop from Java Swing Application to Windows Explorer I have question about Drag And Drop in Java.
I was able to to implement drag and drop files from Windows Explorer to Swing application.
Now I need to oposite direction.
I have JTable which contains Column with object type File. I just need to detect which file (files) are dragged and where in Windows Explorer.
Thanks in advance.

A: I was working with java<->native DnD couple of years ago and my findings were something like below.
If you need to know to which folder dragged files were dropped (for example) to write them out from database: I am quite unsure this is possible. The best you could do is precreating files on drag start, passing correct file references to drop target app, and hoping that explorer default drop handler does what you need. I suspect that on drag-out of java app you have no control and no callbacks on the drop target application (until you have own fancy super-hook somewhere on the explorer side).
Not sure your scenario is as bad as mine was; the feature was not critical and we deferred it...

A: I guess, all you need can be found here


text:
Q: Keyboard navigation with Android GridView doesn't scroll grid I'm trying to use a keyboard to navigate through a GridView of items.
In the short demo, which only contains a GridView (containing item views with android:focusable="true"), you can see that none of the items gain focus - the grid is the thing that scrolls (the items don't turn orange).

Adding the android:descendantFocusability="afterDescendants" allows each item to be focused first, but still, doesn't continue to scroll the GridView so you can navigate down:

Clicking on an item (with mouse or by pressing Return if the item was focused, after the descendent focusability fix) turns an item blue - indicating it's in pressed state.

@layout/activity_my.xml:
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/listview"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:numColumns="2" />

@layout/dummy_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/dummy_item_parent"
  android:layout_width="match_parent"
  android:layout_height="150dp"
  android:gravity="center"
  android:focusable="true"
  android:clickable="true"
  android:background="@drawable/item_background" />

@drawable/item_background.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_pressed="true" android:drawable="@android:color/holo_blue_light" />
  <item android:state_focused="true" android:drawable="@android:color/holo_orange_light" />
  <item android:drawable="@android:color/holo_red_light" />
</selector>

MyActivity.java (with ListAdapter):
public class MyActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);

        AbsListView listview = (AbsListView) findViewById(R.id.listview);
        listview.setAdapter(new DummyAdapter(getLayoutInflater()));
    }

    private static class DummyAdapter extends BaseAdapter {

        private static final int COUNT = 25;

        private final LayoutInflater layoutInflater;

        DummyAdapter(LayoutInflater layoutInflater) {
            this.layoutInflater = layoutInflater;
        }

        @Override
        public int getCount() {
            return COUNT;
        }

        @Override
        public String getItem(int position) {
            return "Item " + position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            if (view == null) {
                view = layoutInflater.inflate(R.layout.dummy_item, parent, false);
            }
            ((TextView) view).setText(getItem(position));
            return view;
        }

    }

}

Swapping the GridView for a ListView, without changing the adapter, or the item views/item view attributes, will behave as expected - items can be focused and the ListView will scroll to the bottom, so that all items can be focused using just keyboard input. Also, using a RecyclerView with LinearLayoutManager / GridLayoutManager will also work correctly.
I have tried this on API 16 and 22 with the same results. I have tried settings the android:descendantFocusability attribute on the GridView to afterDescendents with the same result.

A: I tried your code and it doesn't work with GridView, as you said, but i have some issue also with ListView. The ListView scrolls correctly, but only the first item of every page is highlighted.
With these little modifications you can achieve the effect you want on both GridView and ListView.
Remove android:descendantFocusability in activity_my.xml:
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/listview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:numColumns="2" />

Remove android:focusable in dummy_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/dummy_item_parent"
    android:layout_width="match_parent"
    android:layout_height="150dp"
    android:gravity="center"
    android:clickable="true"
    android:background="@drawable/item_background" />

Change from android:state_focused to android:state_selected in item_background.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@android:color/holo_blue_light" />
    <item android:state_selected="true" android:drawable="@android:color/holo_orange_light" />
    <item android:drawable="@android:color/holo_red_light" />
</selector>


text:
Q: A new object is detached from a data context I added a new object in background worker, The new object was added successfully, But if try to delete it I got an error because the new object was detached from data context.
Background Worker Do_Work Event
private void _anotherThread_DoWork(object sender, DoWorkEventArgs e)
    {
        testdbEntities context = new testdbEntities();

        _item = new item();
        this.txbItemName.Dispatcher.Invoke(new Action(delegate () { _item.name = this.txbItemName.Text; }));

        context.item.Add(_item);
        Application.Current.Dispatcher.BeginInvoke(new Action(() => this.ocItems.Add(_item)));

        context.SaveChanges();
    }

Delete Button (on the main thread)
,If I attached a new object it works
private void btnDelete_Click(object sender, RoutedEventArgs e)
    {
        Item _selectedItem = (Item)lbItems.SelectedItem;

        if (_context.Entry(_selectedItem).State == EntityState.Detached)
            _context.Item.Attach(_selectedItem);

        _context.Item.Remove(_selectedItem);
        _context.SaveChanges();
    }

My question is why the new object not attached to data context ? Should I attche every new object added in background worker ?
Thanks

A: I would strongly recommend not using Entities, especially tracked entities in your control bindings. A tracked entity should live only as long as it's DbContext, and any DbContext you create should have a defined lifetime scope. (Dispose them)
So in your background job, new-ing up a DbContext should be scoped within a using block to ensure it's disposed.
private void _anotherThread_DoWork(object sender, DoWorkEventArgs e)
{
    using(testdbEntities context = new testdbEntities())
    {
        _item = new item();
        this.txbItemName.Dispatcher.Invoke(new Action(delegate () { _item.name = this.txbItemName.Text; }));

        context.item.Add(_item);
        Application.Current.Dispatcher.BeginInvoke(new Action(() => this.ocItems.Add(_item)));

        context.SaveChanges();
        context.Detach(_item);
    }
}

Then when you go to use the Delete button, if you are dealing with a long-lived DbContext (_context) then check the context to see if that entity is already tracked, if not, attach it (or a proxy to it) and perform your delete. If it is already tracked, delete the tracked one:
private void btnDelete_Click(object sender, RoutedEventArgs e)
{
    Item _selectedItem = (Item)lbItems.SelectedItem;

    Item existingItem = _context.Item.Local.SingleOrDefault(x => x.ItemId == _selectedItem.ItemId);
    if (existingItem != null)
        _context.Item.Remove(existingItem);
    else
    {
        _context.Item.Attach(_selectedItem);
        _context.Item.Remove(_selectedItem);
    }
    _context.SaveChanges();
}

Checking the .Local does not hit the database, it just looks for a tracked entity reference for that Id. If one is found, we remove that. If not, we can attach ours and remove it to issue the Delete.
Long-lived DbContexts can cause you issues because through various operations, an entity with the ID of the list item might be tracked already, so using the attached/detached state of a stale copy that was stored in a List control won't be reliable.
If the list Item returns the ID of the entity to delete rather than an untracked entity reference you can still efficiently delete the entity:
private void btnDelete_Click(object sender, RoutedEventArgs e)
{
    int itemId = lbItems.SelectedItem.ItemId; // Where a simple view model was put in the SelectedItem, not an entity.

    Item existingItem = _context.Item.Local.SingleOrDefault(x => x.ItemId == itemId);
    if (existingItem != null)
        _context.Item.Remove(existingItem);
    else
    {
        var tempItem = new Item { ItemId = itemId };
        _context.Item.Attach(tempItem);
        _context.Item.Remove(tempItem);
    }
    _context.SaveChanges();
}

Not much different, but removes the assumption that your list item contains a complete entity when it really doesn't. The list view model can also be a lot more compact than the entire entity, requiring less memory & time to load. The risk of dealing with attached and detached entities is that these entities still need to be assessed against a context in case another entity for that ID is already tracked (due to edits, etc.) and for operations like edits, these entities can be stale. Other applications/users/processes could have updated the data behind the entity. By attaching and doing something like editing and saving changes, that entity only held that user's last known state which can, and will overwrite changes made by other users. When dealing with concurrent edits, it's preferable to load the entity, check the row version or timestamp to see if it's been modified since last retrieved, and handle the scenario if/where it has. You can also run into issues where the underlying record could have been deleted since your current session retrieved it, in which case an attach, update, and SaveChanges would result in an "expected 1, found 0" error or similar. (Not sure, but that could happen in the Delete scenario as well.)


text:
Q: When to use composite index and covering index in SQL Server? I have 2 tables tb_player1 and tb_player2.
CREATE TABLE tb_player1
(
    pk_id INT PRIMARY KEY IDENTITY (1,1) NOT NULL,
    first_name CHAR(16),
    last_name CHAR(16),
    age INT
)

CREATE NONCLUSTERED INDEX ix_nonclustered_name ON tb_player1(first_name, last_name)

CREATE TABLE tb_player2
(
    pk_id INT PRIMARY KEY IDENTITY (1,1) NOT NULL,
    first_name CHAR(16),
    last_name CHAR(16),
    age INT
)

CREATE NONCLUSTERED INDEX ix_nonclustered_name ON tb_player2(first_name)
INCLUDE (last_name)

The tb_player1 has a composite index and the tb_player2 has included column (covering index).
I run the following SQL statements against the tb_player1 and tb_player2, but the actual execution plan of tb_player1 and tb_player2 are the same.
INSERT INTO tb_player1 VALUES('kenny', 'lee', 29)
INSERT INTO tb_player1 VALUES('rose', 'chao', 27)
INSERT INTO tb_player1 VALUES('mark', 'chao', 25)

INSERT INTO tb_player2 VALUES('kenny', 'lee', 29)
INSERT INTO tb_player2 VALUES('rose', 'chao', 27)
INSERT INTO tb_player2 VALUES('mark', 'chao', 25)

select first_name, last_name from tb_player1 where first_name = 'kenny'
select first_name, last_name from tb_player2 where first_name = 'kenny'

select first_name, last_name from tb_player1 where last_name = 'lee'
select first_name, last_name from tb_player2 where last_name = 'lee'

select first_name, last_name from tb_player1 where first_name = 'kenny' AND last_name = 'lee'
select first_name, last_name from tb_player2 where first_name = 'kenny' AND last_name = 'lee'

select first_name, last_name from tb_player2 where last_name = 'lee' AND  first_name = 'kenny'
select first_name, last_name from tb_player1 where last_name = 'lee' AND  first_name = 'kenny'

When to use composite index and covering index in SQL Server? What's the differences between them? Why the execution plan of them looks no different.

A: *

*The composite index (where all of the columns are "key" columns) will carry the data in all levels of the index; the INCLUDE index will only carry the "non key" columns in the leaf node.  Take away: The INCLUDE index will be smaller than the equivalent composite index.

*The INCLUDE columns(non-key) will not count towards the max index size (900 bytes).

*Updates to non-key columns in INCLUDE indexes will not contribute to index fragmentation; updates to unused "key" columns in the composite index will result in fragmentation…  IMO, this is a biggie.

*Assuming low index fragmentation, both composite and INCLUDE indexes will perform comparably.  All columns in the composite index need not be in the query predicate.


text:
Q: Pop Up Box Automatic Closing I need to automatically close the popup box in 3 seconds.
Please help me out guys
html:

<form id="Reject118" name="Reject118" method="post" action="#" onsubmit="return reject_validation(this.name);">
        <input type="submit" class="Reject" name="Reject" id="Reject" value="Reject" title="Click here to Reject this product item & send back for Moderator's Review" />

        <textarea name="reject_reason" id="reject_reason" rows="3" cols="9" onblur="if(this.value == '')
{ this.value = 'Type Reject Reason Here';
this.style.color = '#8f8484';}" onfocus="if(this.value == 'Type Reject Reason Here'){ this.value = ''; this.style.color = '#8f8484';}" style="color:#8f8484;">Type Reject Reason Here</textarea>
</form>

My FIDDLE
FIDDLE

A: Im guessing getElementById is the popup element, in which case the below JS should work:
setTimeout(function(){
   document.getElementById('validationPopup').style.display='none';
},3000)

A: function Hidepopup() {
            document.getElementById('validationPopup').style.display = "none";
        }
        setTimeout("Hidepopup();", 3000);

A: Please add below code
function hideautomatic {
  setTimeout(function () {

    setTimeout(function () {
        $("#yourpop").hide();

    }, 3000);
}, 1000);
};

A: Just add:
window.setTimeout(function() {
    toggle('blanket');
    toggle(windowname);
}, 3000);

to your popup method, and here is your fiddle


text:
Q: Proper place for initialization code in non-HTTP WCF service hosted in IIS/WAS? It is my understanding that a WCF service configured for net.msmq will not run as an HttpApplication when hosted in IIS/WAS, which means you don't get the events in Global (Application_Start being the important one). Am I correct in this regard?
Does using Windows Server AppFabric to auto-start the service hit the service over HTTP, causing the Application_Start event to fire? If so, is this reliable?
I guess my real question is, where is the "proper" place for initialization code for a non-HTTP WCF service?
Particularly (since the right place may be different for different stuff):

*

*IoC registrations

*log4net initialization

*Verifying the MSMQ queue exists locally (as Juval Lowy suggests in his WCF book)

Follow-on question: Do the events in a custom IServiceBehavior fire on every request or only once at startup? What about ServiceHost.OnOpening() - every request or only once at startup? (My testing shows it's only once, but does anyone know where the WCF "lifecycle" is documented, because I can't seem to find it anywhere.)

A: I can't verify that WCF services hosted in IIS/WAS can't be configured to support Application_Start but it is not required to do what you want. I'd recommend you create a custom ServiceHost in conjunction with a custom ServiceHostFactory (for WAS). This approach is documented in an MSDN article and this blog post. Using this approach, you can host your service in IIS/WAS, a Windows Service or a console app because the initialization process will be the same.


text:
Q: How to provide write permission for specific tables in PostgreSQL? I have a user with read-only access in my PostgreSQL 11.
How can I give them access to write/edit data in some of the database tables, e.g. Table1 and Table2 only?
I don't want them to change the DB schema or table structure.

A: Use GRANT:
GRANT INSERT, UPDATE, DELETE ON table1 TO some_user;

You may want to read about basics of the Postgres privilege system in the manual. One essential quote:

The right to modify or destroy an object is inherent in being the
object's owner, and cannot be granted or revoked in itself. (However,
like all privileges, that right can be inherited by members of the
owning role; see Section 22.3.)


text:
Q: Why does extracting file a file using TZipFile in iOS Simulator raise access violation? I'm using TZipFile to extract a zip file and it's works ok in win32 but raise this exception in ios simulator. I dont know why , i've checked the location for the extraction is ok, passed the open file but when come to the extract it still raise that exception. Currently i'm not having any ios device for the real testing but please help on simulator, i'm frustrating with this.
ZipFile.Open(filePath, zmRead);//this line passed,
ZipFile.Extract(0,dirPath );//raise EAccess exception in this line
ZipFile.Close;
//the filePath and the dirPath is the location of file and location i want to extract, it's all correct.

Or use
Zipfile.ExtractZipFile(filePath,dirPath) //still that exception

Update:
OH i think i'm missing the information about my project, my working is to download a zip file  which contain a .csv file from a server. I've downloaded it to the a folder(create at run time) in the ios simulator, the directory of folder i put in to variable dirPath = Tpath.GetHomePath()  + SeparatorChar + 'csv' and the variable 'fileName' is the dirPath' + name of file zip i downloaded. And i about to extract it right in that folder. So i use TZipFile to extract it and it cause up the access violation error in ZipFile.Extract line. I putted my download and extract section code to a new project and it works perfectly. I dont know why but my main project is a large prj which contain many functions and come up before my download section.Thanks

A: Problem solved, in my Download.pas is a separated class and i use library System.Zip in there and i use another class to call it. So my work around is put uses System.Zip right in the Main form when project start and problem solved, there is no logical here and i think it's a bug from System.Zip. Thanks


text:
Q: What is John Hammond's "one in Kenya"?
"I own an island.  Off the coast of Costa Rica.  I leased it from the government and spent the last five years setting up a kind of biological preserve down there.  Really spectacular.  Spared no expense.  It makes the one I had in Kenya look like a petting zoo."
— John Hammond, Jurassic Park (emphasis mine)

When John Hammond meets Dr. Ellie Darker and Dr. Alan Grant, he lets slip that he had owned a preserve in Kenya.
Is there any information as to the nature of this preserve? Not from the film, obviously, but perhaps from the book or from other materials.

A: I don't think it's a reference to the book as Hammond's background deviated from the books. The movie seems to be implying he's some rich eccentric into making biological preserves, and Jurassic Park was his ultimate biological preserve. In the book he was characterized as much more of a ruthless business man that at some point got into cloning and genetics.
As an example of how different the two characterizations are, book Hammond would carry around a tiny elephant in a cage to convince investors of the miracles his people could perform so that they would want to invest. This was done without regard to things like his exaggerations as to the level of technology used to create the tiny elephant, and the fact that the elephant(s) turned out to be very sickly, and it had to be regularly (and secretly) replaced with a new animal when the previous one inevitably died a very premature death.
The one relevant detail is that the Kenyan biological preserve provides a minimum backstory for Muldoon, who was supposed to be from Kenya. The likely implication is that it was a similar tourist attraction featuring dangerous but totally natural African animals, and that Muldoon performed a similar job function there of managing the dangerous animals. Hammond then decided to use Muldoon's expertise for his new dinosaur park.
In the book, Muldoon was from Nairobi, and probably hired by Hammond due to his reputation as a consultant for wildlife preserves rather than due to having worked with him before.

A: John Hammond had Wildlife Preserve 'Animal Kingdom' opened at 1969 in Nairobi, Kenia. [1]


text:
Q: how do I get a consistent javascript window.outerHeight cross browser? Maybe this is a noob question but...
I have a site where I want the footer to appear in the same place all the time. Assuming my users are all on >= IE8, Chrome and Firefox I figured it was just a question of getting the Window.outerHeight.
But when I measure the window.outerHeight it returns different values in FF v. Chrome v. IE.
Plus, just doing some basic measurements visually, it's clear that a 500px DIV is not the same height on my monitors in Chrome as in FF as in IE.
SO: Is there some 'formula' one can reliably use to convert pixel size cross browser so that one can set a proper 'max-height' for a certain div and know it will be the same height in my monitor on IE, Chrome and FF?
Again... I'm not really concerned about truly 'universal'. 99% of my users will have those 3 browsers so if I can get those OK, I'd be more than happy.
TIA,
---JC

A: for IE8 you could use document.body.offsetHeight.
but I would suggest to use only CSS:

(example: http://jsfiddle.net/5h8zj/)


text:
Q: passing mySQL full-text search relevance values back to PHP generated form I'm using php generated forms to do mySQL full text queries on a database.  Matches are ordered according to weighted relevances and returned to the form. My question is:
Is there any way to pass the relevance values as well back to the form?
I'd like to pass the relevance values to JS so that the client might reorder the match list without re-submitting the form back to the server.

A: I think you're finding this:
http://w3schools.com/ajax/ajax_database.asp


text:
Q: binary code with constant hamming distance I want as many 80-bits words as possible with the constraint that the hamming distance between any couple of words is exactly 40. How many can I generate? Is there a generic formula telling me how many n-bits words I can generate with the constraint that any couple of words is at hamming distance exactly n/2? Any general algorithm to generate them?
For 2 bits codewords, "00, 01" are at HD=1. For 4-bits codewords, "0000, 0011, 0101, 1001" are all at HD=2. And then?
Thank You,
JMC

A: There cannot be more than $n$ such words. To see this, consider the words as elements of $\{-1,1\}^n$. If two such words have Hamming distance $\Delta$, then their scalar product in $\mathbb R^n$ is $n-2\Delta$. In particular, if they all have distance $n/2$, then they are orthogonal, hence linearly independent, hence there are at most $n$ many.
An array of  $n$ $\pm 1$ vectors such that every two are orthogonal is called a Hadamard matrix. Such a matrix does not exist unless n=1,2 or n is a multiple of 4. The famous Hadamard conjecture asserts that when $n$ is a multiple of 4, there exists a Hadamard matric of order $n$, This is known to be true in many cases and, in particular, when $n<668$.
An important special case is when $n=2^k$ is a power of two. Then you can construct a set of $n$ such words as follows. We identify bits with elements of the field $\mathbb F_2$, and coordinates $x< n$ with elements of $\mathbb F_2^k$, and thus consider words as functions $f\colon\mathbb F_2^k\to\mathbb F_2$. For any $x,y\in\mathbb F_2^k$, let $f_x(y)=\langle x,y\rangle:=\bigoplus_{i< k}x_iy_i$, where $\oplus$ denotes addition in $\mathbb F_2$ (i.e., modulo $2$). Then $\{f_x:x\in\mathbb F_2^k\}$ is a set of words of size $2^k$, and pairwise Hamming distance $2^{k-1}$, as for any distinct $x,x'$, we have $f_x(y)=f_{x'}(y)$ iff $\langle x\oplus x',y\rangle=0$, which holds for exactly one half of all $y$'s.


text:
Q: Zip Code Boundary Maps for Commercial Use? I need images of cities with features, streets, zip code names and zip code boundaries.  For example, take this screen shot:

This is very close to what I need, except not every zip code name is listed in each boundary.  If I could get city images like this, with complete zip code names and that allows commercial use, that would be perfect.
I don't need zooming or tiling.  Static images like the above are perfectly fine.  I don't even mind capturing the images myself if there's a service that will let me get this data, provided I can use the images commercially.
Do you know of any sources? I googled, but what I found was either lacking some features (as in the above) or did not allow commercial use.

A: TIGER ZIP Code boundaries and TIGER Streets(sorted by FIPS codes) free from the U.S. Census Bureau and should have all the data you need.

A: I found a source: http://www.maptechnica.com/
To use maps for commercial purposes, you have to buy pre-made or custom maps.  But to simply view zip code area maps, you can use their zip code area map feature: http://www.maptechnica.com/us-zip-code-area-map/zip/
If you type in any zip code (eg: 45030) it will show a zip code area map that includes that zip code -- and all zip codes are annotated.


text:
Q: Problem with state in jetpackCompose and Flow I have a problem for now in JetpackCompose.
The problem is, when I'm collecting the Data from a flow, the value is getting fetched from firebase like there is a listener and the data's changing everytime. But tthat's not that.
I don't know what is the real problem!
FirebaseSrcNav
suspend fun getName(uid: String): Flow<Resource.Success<Any?>> = flow {
    val query = userCollection.document(uid)
    val snapshot = query.get().await().get("username")
    emit(Resource.success(snapshot))
}

NavRepository
suspend fun getName(uid: String) = firebase.getName(uid)

HomeViewModel
fun getName(uid: String): MutableStateFlow<Any?> {
    val name = MutableStateFlow<Any?>(null)
    viewModelScope.launch {
        navRepository.getName(uid).collect { nameState ->
            when (nameState) {
                is Resource.Success -> {
                    name.value = nameState.data
                    //_posts.value = state.data
                    loading.value = false
                }
                is Resource.Failure<*> -> {
                    Log.e(nameState.throwable, nameState.throwable)
                }
            }
        }
    }
    return name
}

The probleme is in HomeScreen I think, when I'm calling the collectasState().value.
HomeScreen
val state = rememberLazyListState()
        LazyColumn(
            state = state,
            verticalArrangement = Arrangement.spacedBy(10.dp)
        ) {
            items(post) { post ->
                //val difference = homeViewModel.getDateTime(homeViewModel.getTimestamp())
                val date = homeViewModel.getDateTime(post.timeStamp!!)
                val name = homeViewModel.getName(post.postAuthor_id.toString()).collectAsState().value
                QuestionCard(
                    name = name.toString(),
                    date = date!!,
                    image = "",
                    text = post.postText!!,
                    like = 0,
                    response = 0,
                    topic = post.topic!!
                )
            }
        }

I can't post video but if you need an image, imagine a textField where the test is alternating between "null" and "MyName" every 0.005 second.

A: Check official documentation.
https://developer.android.com/kotlin/flow
Flow is  asynchronous
On viewModel
private val _name = MutableStateFlow<String>("")
    val name: StateFlow<String>
        get() = _name

fun getName(uid: String) {
    viewModelScope.launch {
        //asyn call
        navRepository.getName(uid).collect { nameState ->
            when (nameState) {
                is Resource.Success -> {
                    name.value = nameState.data
                }
                is Resource.Failure<*> -> {
                    //manager error
                    Log.e(nameState.throwable, nameState.throwable)
                }
            }
        }
    }
}

on your view
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    ...
    lifecycleScope.launch {
        viewModel.name.collect { name -> handlename
        }
    }
}


text:
Q: Passing geolocation fetched from the app to the UIWebView I'm developing the iOS app and in one of the views I would like to include UIWebView with a page that contains a map (the address is: https://carsharing.mvg-mobil.de). The website requires location permission so as soon as the user is presented with this view, an alert appears: "https://carsharing.mvg-mobil.de/ would like to use your current location. OK/Don't allow".
In my app I have the location of the user fetched from the CoreLocation framework. Is there a way to pass this location to this webview to avoid this alert view? Would it be somehow possible by injecting some JavaScript code or maybe somehow including geolocation in the URL?

A: OK, I found the solution in the source code of PhoneGap how to inject JavaScript code to a standrad webview with the location fetched from CoreLocation:
int epoch = [newLocation.timestamp timeIntervalSince1970];
float course = -1.0f;
float speed  = -1.0f;
NSString* coords =  [NSString stringWithFormat:@"coords: { latitude: %f, longitude: %f, altitude: %f, heading: %f, speed: %f, accuracy: %f, altitudeAccuracy: %f }",
                        newLocation.coordinate.latitude,
                        newLocation.coordinate.longitude,
                        newLocation.altitude,
                        course,
                        speed,
                        newLocation.horizontalAccuracy,
                        newLocation.verticalAccuracy
                     ];

NSString * jsCallBack = [NSString stringWithFormat:@"navigator.geolocation.setLocation({ timestamp: %d, %@ });", epoch, coords];

[webView stringByEvaluatingJavaScriptFromString:jsCallBack];

Hopefully somebody else can profit from this code as well.

A: You can call JavaScript on the page with UIWebView's
 stringByEvaluatingJavaScriptFromString:(NSString *)script


text:
Q: Android:Implementing twitPic This topic seems to be really tricky for me. I want a right head start to uploading images onto twitPic from my android application. I have no clue of where to start from.

A: You can find what you're looking for at http://code.google.com/p/twitpic4j/


text:
Q: Rails Elasticsearch with conditions I use Elasticsearch in my Rails application (elasticsearch-model, elasticsearch-rails gems). I wrote a simple search:
def search
    @posts = params[:term] ? Post.search(params[:term]) : []
    render json: @posts
end

It works good. But I made some fixes in order to do search among 'deleted=false' and 'enabled=true' subset then :
def search
    @posts = params[:term] ? Post.existing.enabled.search(params[:term]) : []
    render json: @posts
end

Post
class Post < ActiveRecord::Base
  include Elasticsearch::Model
  include Elasticsearch::Model::Callbacks

    scope :existing, ->{ where(deleted: false) }
    scope :enabled,  ->{ where(enabled: true) }
end
Post.import

It doesn't work - I see the same results as in the previous case(with any value in 'deleted' and 'existing' columns. How can I fix it? Thanks in advance.

A: Change how your search method works.
@posts = params[:term] ? Post.search(params[:term], existing: true, enabled: true) : []

Post model
def self.search query, options = {}
  __add_filter = lambda do |f|
    search_definition[:filter][:and] ||= []
    search_definition[:filter][:and] |= [f]
  end
  search_definition = {
    query: {},
    filter: {}
  }
  if options[:existing]
    __add_filter.({ term: {'deleted' => false}})
  end
  if options[:enabled]
    __add_filter.({ term: {'enabled' => true}})
  end
  unless query.blank?
    search_definition[:query] = {
      # add your query logic
    }
  else
    search_definition[:query] = { match_all: {}}
  end
  __elasticsearch__.search(search_definition)
end

You could also check elastic_search example

A: def self.search query, options = {}
  search_definition = {
    query: {},
    filter: {}
  }
  __add_filter = lambda do |f|
    search_definition[:filter][:and] ||= []
    search_definition[:filter][:and] |= [f]
  end
  if options[:existing]
    __add_filter.({ term: {'deleted' => false}})
  end
  if options[:enabled]
    __add_filter.({ term: {'enabled' => true}})
  end
  unless query.blank?
    search_definition[:query] = {
      # add your query logic
    }
  else
    search_definition[:query] = { match_all: {}}
  end
  __elasticsearch__.search(search_definition)
end


text:
Q: Why the arrow can not show up in IE7? I find the below code can run perfectly on IE8,IE9 and firefox,but can not run well on IE7,the up arrow can not show up,why?
CSS:
.arrow_box {
    position: relative;
    background: #88b7d5;
    border: 4px solid #c2e1f5;
}
.arrow_box:after, .arrow_box:before {
    bottom: 100%;
    border: solid transparent;
    content: " ";
    height: 0;
    width: 0;
    position: absolute;
    pointer-events: none;
}

.arrow_box:after {
    border-color: rgba(136, 183, 213, 0);
    border-bottom-color: #88b7d5;
    border-width: 30px;
    left: 50%;
    margin-left: -30px;
}
.arrow_box:before {
    border-color: rgba(194, 225, 245, 0);
    border-bottom-color: #c2e1f5;
    border-width: 36px;
    left: 50%;
    margin-left: -36px;
}

HTML:

css arrow please!

A: :before and :after selectors are not supported on IE7.
You would either have to change your CSS to not use :before and :after, or you can use a js shiv that will basically emulate the behavior of those selectors using javascript. Here's a post about how to do that.


text:
Q: What are the command line tool for Magento? I find a Question here but I am looking for command line tool for Magento  development tools like Drupal have Drush and Drupal console to clear cache or create module or config.
Is there any similar tool for Magento ?


text:
Q: window.__proto__ equivalent for IE10 I am wondering how to enumerate window functions like setTimeout or alert in IE10. In all other "modern" browsers (inluding IE11) I can get them with:
Object.getOwnPropertyNames(window.__proto__)

But in IE10 window.__proto__ is not defined. As in all other browthers
Object.getOwnPropertyNames(window)

does contain many functions, but not all (including the two mentioned above).
How do I enumerate those in IE10?

A: You can get enumerable and non-enumerable properties of the Window object with:
var properties = Object.getOwnPropertyNames(Object.getPrototypeOf(window))

the getPrototypeOf method is available in IE9+.


text:
Q: SQL Snapshot Isolation limits For my database application, employing snapshot isolation for certain of its queries' transactions seems perfect for solving one of the critical requirements.
I'm worried, though, how choosing snapshot isolation (which I believe must be enabled database-wide) now will bite us once we start getting very high volumes.  What is the cost of snapshot isolation?  Is it a fixed cost, linear, or geometric?
If I'm right to be concerned about high volumes, are there strategies/patterns for application-level functionality similar to snapshot isolation that might have better overall performance, but take more time/expertise to implement?
Thanks,
Jason

A: For anyone who's not already an expert on locking and database implementations, this can be a surprisingly difficult subject to wrap your mind around.
I highly recommend reading this series of posts on snapshot isolation by Hugo Kornelis (SQL Server MVP).  So far it's the most complete analysis I've seen of practical considerations when using snapshots.
To summarize the main issues:

*

*When a particular combination of concurrent transactions would make it possible to violate a constraint (UNIQUE, FOREIGN KEY, etc.), SQL Server will fall back to the old way of doing things.  This is good for reliability, obviously, but not for performance.  Snapshots aren't a panacea, they aren't a replacement for good database/query design and intelligent lock management.

*Snapshots and triggers may not play nice together.  It's especially dangerous if you use triggers to protect data integrity, but even if you don't, pretty much all of your triggers will have to be made snapshot-aware.

Depending on how you write your queries, you may not even need to be using triggers in order to end up with unexpected or inconsistent results.
I don't know if the costs are fixed or linear, although they're definitely not geometric; I do know that it's a bit of a headache regardless.  It's often talked about as a fire-and-forget option, but the truth is, it's not, if you don't know what you're doing you can end up with breaking changes (ones that you probably won't find out about until it's too late!).
By all means do use it if you're sure that it won't cause any other problems.  But if any of your logic doesn't care about dirty reads (and this applies to more than half the SELECT queries in many systems), you'll get far better results with READ UNCOMMITTED (which does involve more "expertise" - you have to think very carefully about what can happen and when).
Update: On application-level alternatives
The only one that springs to mind is caching.  Some data frameworks can do this for you (NHibernate, EF), and in some cases you might even have a 3rd tier of caching, such as web services that cache results based on the message input, results that might be based on several queries.  I wouldn't really call this an "alternative" but I imagine that some form of caching would be effective in your case if these are read-only queries and the underlying data doesn't change frequently.  The design consideration is, of course, how much you data you can afford to cache relative to the amount you need to serve; if the system is massively concurrent then this might not scale.
Beyond that, I personally would not choose to try to implement my own app-level transactional "tier".  Maybe some people have done this, but I don't think there's any way that my limited experience can compete with hundreds or thousands of the brightest designers working on a DBMS for 20 years.

A: Snapshot isolation is meant to be more read performant than other isolation levels.  By segregating the data into a snapshot, the transaction does not need to acquire locks on the rows, which prevents blocking and deadlocks.
However, it does have to write row versioning information into the tempdb database.  So for each transaction, some write-time should be expected.
Just like everything else, your circumstances will dictate whether or not this will be more or less performant for you.  If your application is OLTP style, then it could be a large increase in performance if your transactions are prone to deadlocking.


text:
Q: How to repeat an element n times using JSX and Lodash I am using React/JSX and Lodash in my app in order to accomplish what I want.
I need to repeat an element a certain amount of times depending on a condition. How should I do that?
Here is the element:
♦;

And I am assigning it like this:
let card;
if (data.hand === '8 or more cards') {
  card = ♦;
}

So in this case, I need to repeat the element 8 times. What should be the process using Lodash?

A: I'm using this and works for me.
[...Array(10)].map((elementInArray, index) => (

      Text in Loop

))

A: Using _.times: https://jsfiddle.net/v1baqwxv/
var Cards = React.createClass({
    render() {
        return
cards {
          _.times( this.props.count, () => ♦ )
        }
;
    }
});

A: solution without lodash or ES6 spread syntax:
Array.apply(null, { length: 10 }).map((e, i) => (

    ♦

));

A: You could do it like this (without lodash):
var numberOfCards = 8; // or more.

if (data.hand >= numberOfCards) {
    var cards = [];

    for (var i = 0; i < numberOfCards; i++) {
        cards[i] = (♦);
    }
}

A: The shortest way to do this without any external libraries:
const n = 8; // Or something else

[...Array(n)].map((e, i) => ♦)

A: Here you go:
let card = [];
_.times(8, () => {
  card.push(♦);
});

You may want to add key to each span element so React won't complain about missing the key attribute:
let card = [];
_.times(8, (i) => {
  card.push(♦);
});

For more info about .times, refer here: https://lodash.com/docs#times

A: Straight forward options ways to do that without any external libraries (2021):
// straight forward but without key index. Not so good for react but work fine with worning
Array(X).fill(♦)
// with index
Array(X).fill().map((v,i)=> ♦)

Array.from( Array(X), (v,i) => ♦ )
// same thing basically
Array.from( {length:X}, (v,i) => ♦ )

[...Array(3)].map( (_,i)=> ♦ )

A: Implementing this without Lodash

      {Array.from({ length: 10 }, (_, i) => Your text)}

How does this work?
Array.from() is used in two contexts:

*

*Creating an array from an array-like data structure. For example, we can convert a map into an array using Array.from()
const map = new Map([ [1, 2], [3, 4], [4, 5] ])
console.log(Array.from(map)) //gives an array - [[1, 2], [3, 4], [4, 5]]

*Creating an array and filling out the values (This can be handy when we need to create an array containing more elements)
Array.from() accepts an object and a callback function.
Array.from({ length: 7 }, (() => 10)) // gives [10,10,10,10,10,10,10]
We can take advantage of the index (second parameter) inside the callback function to provide unique array elements
Array.from({ length: 4 }, ((_, i) => i + 1)) // [1,2,3,4]

A: You can create an array with as many items as you need rendered and then map through the array to render the correct number of elements you need.
const totalItems = 8;

const items = new Array(totalItems).fill(null);

// .... then
return (
    {items.map((_, idx) => ♦)}
);

A: You can use Lodash range.
_.range(20).map((_n, i) => <MyComponent key={i}/>)

A: I thought, that if someone would like to use it in many places in the code, it would be a good idea to make it an npm package: https://www.npmjs.com/package/repeat-component. I think it will help someone :)


text:
Q: pdfbox error - Colorspace can't be determined at this time, about to return NULL from unhandled branch I am using the following code to get a list of jpegs attached to one of my objects "PrintDocument" wich references a "Document" which references a "Page" Object. The path is being combined from Document and Page. But this is not the Problem. When I use this code and run it in simple java on the jvm, the pdf is being built without any error...
    public File createPDFtoPrint(PrintDocument pdocument)
        throws IncompleteDocumentException, IOException, FSException {
    File tmp = null;
    if(validatePrintDocument(pdocument)){

        PDDocument document = new PDDocument();
        Iterator<Page> iterator = pdocument.getDocument().getPageList().iterator();

        while(iterator.hasNext()){
            Page page = iterator.next();
            PDPage pdpage = new PDPage(PDPage.PAGE_SIZE_A4);
            document.addPage( pdpage );

            PDPageContentStream contentStream = null;
            try {
                contentStream = new PDPageContentStream(document, pdpage);
            } catch (IOException e) {
                String message = "Error while creating contentStream for Page" + page.getPageNumber();
                logger.error(message);
                logger.debug(e.toString());
            }
            PDJpeg ximage;
            try {
                File imgFile = new File(docDir+"/"+pdocument.getDocument().getName()+"/"+page.getPageNumber()+".jpg");
                System.out.println("*************** FILEPATH IS "+imgFile.getPath());
                ximage = new PDJpeg(document,new FileInputStream(imgFile));
            } catch (FileNotFoundException e) {
                String message = "File not found for Document " + pdocument.getDocument().getName() + "! Try uploading the PDF for this product!";
                logger.error(message);
                throw new FileNotFoundException(message);
            } catch (IOException e) {
                String message = "Error while reading input file for document " + pdocument.getDocument().getName();
                logger.error(message);
                throw new IOException(message);             }

            if(ximage.getWidth()>ximage.getHeight()){
                AffineTransform at = new AffineTransform(pdpage.getMediaBox().getWidth(), 0, 0, pdpage.getMediaBox().getHeight(), pdpage.getMediaBox().getWidth(), 0);
                at.rotate(Math.toRadians(90));
                contentStream.drawXObject(ximage,at);
            }
            else{
                AffineTransform at = new AffineTransform(pdpage.getMediaBox().getWidth(), 0, 0, pdpage.getMediaBox().getHeight(), 0, 0);
                contentStream.drawXObject(ximage,at);
            }

            PDFont font = PDType1Font.HELVETICA_BOLD;

            //Pixel per Point
            float ppp = page.getPpp();

            Iterator<Field> cbIterator = pdocument.getCheckBoxMap().keySet().iterator();

            while(cbIterator.hasNext()){
                Field field = cbIterator.next();
                if(pdocument.getCheckBoxMap().get(field)){
                    contentStream.beginText();
                    contentStream.setFont( font, 14 );
                    contentStream.moveTextPositionByAmount(field.getPosx()/ppp, field.getPosy()/ppp );
                    contentStream.drawString("x");
                    contentStream.endText();
                }
            }

BUT, when I use this in a EJB within the Glassfish Container I get the following errors, and the pages are blank:
[2015-05-05T01:57:59.739+0200] [glassfish 4.0] [INFO] [] [] [tid: _ThreadID=22 _ThreadName=Thread-3] [timeMillis: 1430783879739] [levelValue: 800] [[2015-05-05 01:57:59 DEBUG PDXObjectImage:398 - Colorspace can't be determined at this time, about to return NULL from unhandled branch. filter = COSName{DCTDecode}]]

[2015-05-05T01:57:59.740+0200] [glassfish 4.0] [INFO] [] [] [tid: _ThreadID=22 _ThreadName=Thread-3] [timeMillis: 1430783879740] [levelValue: 800] [[2015-05-05 01:57:59 DEBUG PDXObjectImage:400 - Can happen e.g. when constructing PDJpeg from ImageStream]]

Does anybody have any clue, why this is happening and how this can be solved?
Regards

A: My Problem was, that the PDFs I am generating seemed to be empty. All white. But the error mentioned in the topic has nothing to do with that. It seems that this is a kind of error nobody, that not really cares about the colorspace should care about. The error, why my Documents seemed empty was that I was not closing the ContentStream after finishing a page. So ContentStream#close solved the problem in my case.


text:
Q: Count associations in sqlite database query? I have a sqlite database with three tables: Notes, Lists, and Notes-in-Lists.
Both Notes and Lists have an autogenerated id column and some extra data columns like title. Notes-in-Lists is an association table with an autokey, and two foreign keys that point to a Note id and a List id.
I have a query that returns all notes in a given list:
Select _id, title From Notes
Join Notes_in_Lists On Notes._id=Notes_in_Lists.note_id
Where Notes_in_Lists.list_id=2

This would return all note titles and ids from List 2 for example.
However, notes can be in multiple lists and I need to be able to tell if a note is associated with multiple lists.  This is indicated by the same Notes_in_Lists.note_id being listed multiple times in the Notes_in_Lists table.
Easy enough to do by itself:
Select Count(note_id) From Notes_in_Lists Where note_id=2

But I need to combine the two queries above into one query and I have not idea where to begin.
Edit
Sample data
Notes:
_id title
1   "Note 1"
2   "Note 2"
3   "Note 3"
4   "Note 4"

Note_in_Lists
_id note_id list_id
1   1       2
2   1       3
3   2       2
4   3       1
5   4       2
6   4       4
7   4       5

Sample output (query for contents of list 2):
_id  title      numberOfLists
1    "Note 1"   2
2    "Note 2"   1
4    "Note 4"   3

A: Select Notes._id, Notes.title, Count(Nil2.list_id)
From Notes
Inner Join Notes_in_Lists NiL1 On Notes._id=NiL1.note_id
Inner Join Notes_in_Lists NiL2 On Notes._id=NiL2.note_id
Where NiL1.list_id=2
Group By Notes._id, Notes.title;

It can seem wasteful to do two joins, but that's what you need to basically run two queries.

A: SELECT n._ID, Title, Count(*) numberOfLists
FROM Notes n, Notes_In_Lists l
where n._id = l.note_id
  AND NOT EXISTS (Select 1
              from notes_in_lists l2 where
              l2.note_Id = n._id
              AND l._Id = 2)
group by n._ID, n.Title


text:
Q: How do I remove leading and trailing text in Autohotkey I know this is basic but for the life of me, I am having difficulty. Can someone explain how I can change the following in Autohotkey:
Change:

VAR = Leading string of text @TEXT I WANT TO KEEP@ Trailing String
  of Text...

To:

TEXT I WANT TO KEEP

In other words I want to keep only what's in between the "@" symbols and then save the result as a variable.
What's the easiest way to do that?

A: Stores TEXT I WANT TO KEEP in variable match1
VAR := "Leading string of text @TEXT I WANT TO KEEP@ Trailing String of Text"
if RegExMatch(VAR, "@(.*?)@", match) > 0
  MsgBox Found "%match1%"

Reference

*

*RegExMatch

A: Regular expression is:
@(.*?)@

The output of which will be stored in $0

A: Try:
VAR = Leading string of text @TEXT I WANT TO KEEP@ Trailing String of Text...

MsgBox % StrSplit(var, "@").2


text:
Q: Circuit design considerations using N-FET for a High Brightness UV-LED? I'm designing a circuit to power a high-brightness UV LED. I'd like to safely drive it as close as possible to maximum irradiance, and I'm having trouble figuring out whether all the components are properly chosen to avoid damaging/stressing anything (especially the LED, which is relatively expensive).
A Raspberry PI will be used to provide the on/off logic. The PI is powered separately, but shares a common ground with the LED power system.
Ideally I'd like the LED to be driven directly by a N-FET, where the gate is hooked up to a raspberry pi GPIO pin:

simulate this circuit – Schematic created using CircuitLab
The first question I have is: am I reading the UV-LED spec (here) correctly?

*

*Forward Voltage: 3.45V

*Maximum Current: 1400mA

*Electrical Power (Max): 4830mW

The above three make sense, because 3.45V * 1400mA = 4830 mW. Then I see some peculiar items:

*

*LED Output Power: 1500mW (min), 1700mW (Typical)

*Test Current for Typical Power: 1400mA

How can the "Typical" LED output power be 1700mW when the test current for "typical" power is 1400mA?
Essentially, I'm not sure whether my resistor value should be calculated based on the 1400mA figure (5V-3.45V / 1400 mA = 1.11 Ohms) or whether I should be deriving a current from the 1700mW figure (1700mW = 3.45V X I; I = 492mA; R = 3.1 Ohms) and then using a larger resistor.
The second question I have is regarding the NFET. The NFET I have is rated for 1.7A and 30V (datasheet here). But the package is scarily tiny (SOT-23) and my gut feeling says I should ask before proceeding. I will be running this at 1.4A which is pretty close to the 1.7 rating. Will it work, and do I actually need to get a tiny heatsink for this NFET? Or is it better to get a beefier NFET?
Other than that, I'm making sure to get a hefty power resistor rated at 1-2 Watts, all wires will be 22 gauge, and all PCB traces will be nice and fat. Any other power-related gotchas I should be aware of? Power source details also listed below.
Thanks so much!

Datasheet for the NFET (1.7A / 30V):
https://www.fairchildsemi.com/datasheets/ND/NDS355AN.pdf
Datasheet for the UV LED:
https://www.thorlabs.com/drawings/ca01256cc12b40f8-35473EF6-5056-0103-7951A15FE4DCB58B/M405D2-SpecSheet.pdf
2A+ Power Board and battery:
https://www.adafruit.com/product/2465
https://www.adafruit.com/products/353

A: You probably want to consider the recommendation in the datasheet: "We recommend using Thorlabs' DC2200 or LEDD1B LED current drivers"
If you still want to use voltage mode control, I would ask: do you really need to run it at full power?
VF is a typical number than can fluctuate with temperature and vary part to part. So if your application permits it, I would run at lower currents (maybe 700mA).
The LED output power number quoted is for light output power. Since the test current used to generate this output is stated as 1400mA you can estimate the efficiency of your LED and plan for the generated heat accordingly.
Your NFET is close to max rated spec. I would double the current rating if possible. If you don't then I would definitely use a heat sink with some thermal paste.
One last thing that occurs to me is to add a resistor in series with the gate of the FET. Since you will be running high currents (relative to the drive capability of the GPIO), you don't want any glitches in your LED or power supply to shove a ton of current into the GPIO. A 10K resistor should do.

A: 3.45 volts is given as the typical forward voltage but the data sheet doesn't explicitly say that this forward voltage is measured at such and such a forward current. The table that gives this number (page 1 of the DS) kind of implies it might be at 1 amp (given that the peak wavelength measurement uses that current) so where are you with deciding what value of resistor to current limit the device?
Not close unfortunately - your circuit shows a supply of 5.1 volts in series with a 1.1 ohm resistor. If the forward voltage is exactly 3.45 volts then the current will be 1.5 amps and bang your LED is likely to die after a short while.
The 3.45 volt could be at a test current of 1 A and therefore a resistor of 1.65 ohms is more appropriate. Better still, use a constant current source as recommended - you can make your own quite easily - they are not rocket science.

How can the "Typical" LED output power be 1700mW when the test current
  for "typical" power is 1400mA?

If the current (NOT power) is 1.4 A then the power into the LED is 1.4 A X 3.45 V = 4.83 watts. With 1.5 watts output light power, that's an efficiency of 31% and pretty good.


text:
Q: Corona SDK multitouch run and jump I think this should be very easy to do, but I'm not able to find any solution. It's always just system.enable("multitouch") and then something with setFocus() method.
I have a right button, that responds to touch event and makes player run right when held. Then I have a jump button, that responds to tap event, making player jump.
Running works, jumping works, but when I run and try to jump nothing happens.
Here is some code:
local speed = 3
local motionx = 0
-- When right arrow is touched, move character right
    function right:touch()
        if string.find(player.sequence,"jump") then
            player:setSequence("jumpRight")
            motionx = speed;
        elseif string.find(player.sequence,"duck") then
            player:setSequence("duckRight")
        else
            player:setSequence("goingRight")
            motionx = speed;
        end
        player:play()
    end
    right:addEventListener("touch",right)

    -- When up arrow is tapped, jump character
    function jump:tap()
        if not isJumping then
            if string.find(player.sequence, "goingRight") then
                isJumping = true
                player:setSequence("jumpRight")
                player:setLinearVelocity(0,-120)
            end
            if string.find(player.sequence, "goingLeft") then
                isJumping = true
                player:setSequence("jumpLeft")
                player:setLinearVelocity(0,-120)
            end
            if string.find(player.sequence, "duckLeft") then
                player:setSequence("goingLeft")
            end
            if string.find(player.sequence, "duckRight") then
                player:setSequence("goingRight")
            end
            player:play()
        end
    end
    jump:addEventListener("tap",jump)

    -- Move character
    local function movePlayer (event)
        player.x = player.x + motionx;
    end
    Runtime:addEventListener("enterFrame", movePlayer)

I don't knowh where, how or why should I use the setFocus() method. But so far when running, I cannot jump until I release the right button.

A: It was my mistake, that I wanted to use TAP event for jump. I guess since it is called multiTOUCH it only works with multiple TOUCH events :) I changed TAP events to TOUCH events and added:
if event.phase == "began" then
        display.getCurrentStage():setFocus( event.target, event.id )
        --other code
end
if event.phase == "ended" or event.phase == "cancelled" then
        display.getCurrentStage():setFocus( event.target, nil )
end

Now it works nicely.


text:
Q: How to select part of an image, then paste the selected part of the image in a checkerboard pattern into another image using JES? I am using Jython, or JES, and I want to repeatedly copy, in a checkerboard pattern, part of one image into another image. I am wondering how that might be done?
So far I have this:
def checkerboard(pic):
  p = makeEmptyPicture(500,500)
  targetX = 100
  for sourceX in range(81,123):
    targetY = 100
    for sourceY in range(99,126):
      color = getColor(getPixel(pic,sourceX,sourceY))
      setColor(getPixel(p,targetX,targetY),color)
      targetY = targetY + 1
    targetX = targetX + 1
  show(p)

Pic is the user selected image, and picX and picY are the ranges of the picture.
The issue is that this just pastes part of an image once into the empty picture (p). I want the part of the image to be pasted repeatedly into the empty picture in a certain area of the empty picture.


text:
Q: Select return more value than one to main select Can you please help me? I have one main (SELECT), where I'm using more next select commands but inferior select return me more value than one.
SELECT table1.column1
AS table.refer, table2.column2 AS table.value,
    --Here is my problem:
    (select count(table.column.id) FROM table1
    left outer join table1 on table1.column1 = table.column
    LEFT outer join table2 on table2.column2 = table1.column1
    LEFT OUTER JOIN table3 on table3.column3 = table2.column2
    WHERE table1.column1 = (23212 " This value contains more data) AND table2.column2 = value AND YEAR(table1.column1) = YEAR(GETDATE() GROUP BY table.refer)

FROM table1 left outer join table1 on table1.column1 = table.column
LEFT outer join table2 on table2.column2 = table1.column1
LEFT OUTER JOIN table3 on table3.column3 = table2.column2

WHERE table1.name1 in (23210, 23211, 23212, 4882525, 67735166, 74605160) AND table2.name2 in (15739, 15744, 15743, 15741, 15735, 15745)
GROUP BY table.refer, table.value

Important value from main select is table.refer. I need take only one table.refer for second select. But for all data.
I check cursor function for this or create new table for this select data or field[] but I don't know how do it. Please help me.

A: So, part of the problem is that you have a Group By int the subquery (the "inferior select). This would allow the select to have a single column (count(table.column.id)) but multiple rows for that column, one for each table.refer. If you think about it, you're asking for the results of the sub select to be a field in higher select. So it can only return a single value.
So I think you may want to just remove the Group By. This would return a single Count result for the sub query.
If that is not what you wanted but are expecting multiple values, then the subquery as a field would not be the way to go and would need better description of what you're trying to achieve.


text:
Q: test System field on Batch class I have a batch that automatically archives any articles with a Status (Fixed) and published for more than 30 days (using a custom setting to verify the number of days).
But I struggle to cover the execute method in my test class

When doing a system.debug on the article (Knowledge__kav) field LastPublishedDate in my test class.
The field returns null.
Also, when trying to set a value to LastPublishedDate, I have another error:
field is not writeable LastPublishedDate.
How can I test LastPublishedDate and increase my test coverage?
Thanks
here is my test class:
@isTest

public class BatchArticleTest {
@testSetup
static void setup() {
    Account acct = new Account(Name = 'test Account');
    insert acct;

    Case c = new Case(Status = 'New', AccountId = acct.Id, Type = 'Feature');
    insert c;

    Contact con = new Contact(LastName = 'test contact');
    insert con;

    //Create article
    Knowledge__kav kav = new Knowledge__kav(Title = 'test', UrlName = 'test', Related_Problem__c = c.Id, Affecting__c = 'test',
                                            Known_Error_Status__c = 'In Review');

    insert kav;
    System.debug('kav ' +kav);

    Known_Error_Subscription__c kes = new Known_Error_Subscription__c(Contact__c = con.Id, KnowledgeKA__c = kav.KnowledgeArticleId,
                                                                      Article_Status__c = kav.Known_Error_Status__c,
                                                                      Article_Title__c = kav.Title);
    insert kes;

}

 // test BatchArticleArchive
 @isTest static void archiveTest() {
    //test PublishingService Class to publish article
    Knowledge__kav kav = [SELECT KnowledgeArticleId, LastPublishedDate FROM Knowledge__kav WHERE Title = 'test'];
    String articleId = kav.KnowledgeArticleId;
    System.debug('articleId ' +articleId);
    KbManagement.PublishingService.publishArticle(articleId,true);

    //test custom setting
    DaysToArchive__c setting = new DaysToArchive__c();
    setting.Name = 'test Setting';
    setting.Number_of_Days__c = 1;
    insert setting;

    Double dbl = setting.Number_of_Days__c;

    //test PublishingService Class to archive article
    System.debug('LastPublishedDate ' +kav.LastPublishedDate);
    KbManagement.PublishingService.archiveOnlineArticle(kav.knowledgeArticleId,null);

    Test.startTest();
    BatchArticleArchive batchArchv = new BatchArticleArchive();
    Id batchId = Database.executeBatch(batchArchv);
    Test.stopTest();
}

}


text:
Q: Customize Devise user JSON response on creation of a user account How do I customize the JSON output on creation of a devise User?
### User.rb ###
class User < ActiveRecord::Base
  devise :database_authenticatable,
         :registerable, ...
  ...
end

### Routes.rb ###
...
devise_for :users, :controllers => {:registrations => "registrations"}
...

I've got some extra fields in my User table that are secret, but they get returned in the JSON response when I do a User creation via JSON like this:
$ curl -H "Content-Type: application/json" -d '{"user" : {"username":"someone","email":"someone@somewhere.com","password":"awesomepass"}}' -X POST http://localhost:3000/users.json

which returns:
{"user":{"secret_field_1":"some value","secret_field_2":"some value","created_at":"2013-07-25T21:24:50-05:00","email":"someone@somewhere.com","first_name":null,"id":3226,"last_name":null,"updated_at":"2013-07-25T21:24:50-05:00","username":"someone"}}

I'd like to hide those secret fields, but don't know how to customize the JSON response.
I've tried a standard ActiveRecord serializer:
class UserSerializer < ActiveModel::Serializer
  attributes :id, :created_at, :updated_at, :email, :first_name, :last_name, :username
end

to no avail, I'm guessing because of Devise.

A: I recently ran into this and overriding respond_with didn't fix the issue. I ended up overriding to_json in user.rb like so:
def to_json(arg)
  UserSerializer.new(self).to_json
end

Not sure what the extra arg is, but that seems to be required by one of the devise mixins.
I'm using the following:

*

*Rails 4.2.0

*Devise 3.4.1

A: I just ran into the same issue. I haven't pinpointed exactly why but it looks like respond_with in Devise's SessionsController (tested on Devise 3.0 and active_model_serializers 0.8.1) doesn't trigger the ActiveModel::Serializer.
So I overrode respond_with in my controller:
class SessionsController < Devise::SessionsController

  def respond_with(resource, opts = {})
    render json: resource # Triggers the appropriate serializer
  end

end

It is, however, working in my RegistrationsController with respond_with.  There I needed to do the following:
class RegistrationsController < Devise::RegistrationsController

  respond_to :json
end

A: Just a guess, but it sounds like rails is not finding your serializer and is using to_json(). Did you define active_model_serializer() in your model?

A: I just had the same problem, below is how I resolved it, very simple.
All these passed in active_model_serializers (0.9.5)
Override Devise registration method, and in your customize action:
def registration
  //Some process, and you get a @user when registration is successful.

  render :json => UserSerializer.new(@user)
end

If you want to pass some parameters to your customized Serializer(token for example), you can pass it in your action:
render :json => UserSerializer.new(@user).as_json({auth_token: your_token})

And in your serializer, just use:
class UserSerializer < ActiveModel::Serializer
  attributes :id, :name, :avatar_url, :auth_token

  def auth_token
    serialization_options[:auth_token]
  end
end

A: Depending on what you are doing with that JSON, you simply have to remove attributes you don't want from your serializer.
For example :
class UserSerializer < ActiveModel::Serializer
  attributes :id, :email, :username
end

I presume that, in your case, you just want to do that.
But you also have the possibility to include an attribute on a specific condition :
class PostSerializer < ActiveModel::Serializer
  attributes :id, :title, :body, :author

  def include_author?
    current_user.admin?
  end
end

And finally you can override the attributes method to return the hash you need :
class PersonSerializer < ActiveModel::Serializer
  attributes :first_name, :last_name

  def attributes
    hash = super
    if current_user.admin?
      hash["ssn"] = object.ssn
      hash["secret"] = object.mothers_maiden_name
    end
    hash
  end
end

See README of ActiveModel::Serializers for more informations.


text:
Q: Form Organization In a Rails 4 App I'm building a new Rails app for a client and one of the requirements is to allow people to fill out service request forms. There are 10 request forms so far and they're all different. To implement this I was thinking of creating a separate Model, View and Controller for each one to keep everything simplistic and RESTful. I'm kind of worried though about having 10+ different MVCs and routes just for the forms. Is there potentially and better way to achieve this?
Also the data submitted just gets emailed. No saving to a database.
Thanks for any help! :)

A: You're correct to make them all separate resources, controllers, models, etc.
If possible, you can DRY the code that is similar among them. For example, if some of the forms have similar validations, or parameter filtering, or scopes, etc.

I'm kind of worried though about having 10+ different MVCs and routes just for the forms

In my opinion, 10+ different MVCs are fine for 10+ different resources. You may be interested to read about "DAMP" coding. I personally recommend DRY underpinnings and DAMP resources.


text: Q: Can't import projects into Eclipse So, I'm able to import my project fine onto my desktop computer, but when I try on my laptop, there is a problem.  Basically, when I open the import wizard (by just clicking file, import) a window comes up that says "import, select, choose import source, select an import source:" but then, below "select an import source" there is just nothing to choose from.  There are some buttons that says back, next, and finish, but those are all grayed out.  The ONLY thing I can do is cancel.  There's supposed to be a text box that says "type filter text" and some things to choose from like the "general" folder so I can choose to import an archive file, but just none of that is there, there is nothing to do but cancel.  What gives?  This is rather frustrating.


text:
Q: Why does Python call both functions? I have some problems to understand what happens here.
This is my source:
class Calc():

    def __init__(self,Ideal,Limit,Value,Debug=None):

        self.Ideal = Ideal
        self.Limit = Limit
        self.Value = Value
        self.Debug = Debug
        self.Grade = self.GetGrade()
        self.LenGrade = self.GetLenGrade()

    def GetGrade(self):
        if self.Debug:
            print('calling GetGrade')
        return Grade

    def GetLenGrade(self):
        if self.Debug:
            print('calling GetLenGrade')
        return Grade

When calling it with
GradeMinLen += Calc(TargetLen, LimitMinLen, Length ,Debug=1).LenGrade

I get always the output
calling GetGrade
calling GetLenGrade

Why is python calling GetGrade?

A: You create an instance of Calc(), and whenever you do that, Calc.__init__() is called for that new instance.
Your Calc.__init__() method calls both self.GetGrade() and self.GetLenGrade():
self.Grade = self.GetGrade()
self.LenGrade = self.GetLenGrade()

It doesn't matter here that after you created the instance you only access the LenGrade attribute; the above two lines in __init__ do not store method references, they store the results of the method calls. The Calc(...).LenGrade then returns one of those results; the other result is also there however.

A: In your object initialisation code, you have the following:
self.Grade = self.GetGrade()
self.LenGrade = self.GetLenGrade()

This means "set the value of the data member Grade to the value obtained by calling the method GetGrade" and the same for LenGrade.
It should not be surprising that they're called, it would be more surprising if they were not.


text:
Q: Сохранение изображений из гугл картинок C# Здравствуйте. Имеется в компоненте webbrowser загруженная страница с определенными картинками из гугл картинок. Как можно сохранить выбранное мной изображение, если я, допустим, открыл его для просмотра (кликнув по нему)?
Думал сделать так:
после нажатия на изображение, если оно удовлетворяет требованиям, нажать кнопку "в полном размере" и тут же как-то перехватить ссылку на это изображение, а затем сохранить на диск. Но понятия не имею как это делать. Может кто подсказать способ решения этой проблемы?

A: Именно на C#, как вариант, вы можете использовать фантомбраузер, переходить по нужной ссылки в гугл картинках , получать страницу с нужными картинками и парсить  используя косвенные признаки для выбора нужной картинки. Я выкладывал пример в этом ответе


text:
Q: Checkbox insert 1 or 0 into SQL database I am setting up a system that has many answers from a question. Therefore the user can click a button to dynamically add answers. I want the user to be able to tick a checkbox next to the answers which are correct and then insert this into the database (1 being correct).
Here is what I have:
HTML:
<div id="answers">
 <label class="answer">
  Answer:
   <input type="text" name="ab_name[]" value=""/>
    Correct?
   <input type="checkbox" name="ab_correct[]" value="0">
 </label>
</div>

PHP
$ab_name = $_POST['ab_name'];
$ab_correct = $_POST['ab_correct'];

$sql = "INSERT INTO answers_bank (`ab_name`, `ab_correct` ) VALUES (:ab_name, :ab_correct )";
$stmt = $db->prepare($sql);

foreach ($_POST['ab_name'] as $ab_name) {
$stmt->bindValue(':ab_name', $ab_name);
$stmt->bindValue(':ab_correct', $ab_correct);
$stmt->execute();
}

Like this:

The SQL inserts the ab_name but the ab_correct is ALWAYS set to 1 if it is ticked or unticked. Any guidance on this please?

A: You could use a for loop instead of the foreach. Well, first of all, you need to make sure both arrays has the same amount of elements.
if(count($_POST['ab_name']) != count($_POST['ab_correct']))
    exit('Not same amount of elements.');

Then, loop through each of them.
for($i=0; $i<count($_POST['ab_name']); $i++){
    $stmt->bindValue(':ab_name', $_POST['ab_name'][$i]);
    $stmt->bindValue(':ab_correct', $_POST['ab_correct'][$i]);
    $stmt->execute();
}

A: if(isset($_POST['$ab_correct'])){$update = 1;}else{$update = 0;}

foreach ($_POST['ab_name'] as $ab_name) {
$stmt->bindValue(':ab_name', $ab_name);
$stmt->bindValue(':ab_correct', $update);
$stmt->execute();

}


text:
Q: Using the generic type 'System.Collections.Generic.IReadOnlyList' requires 1 type arguments public IReadOnlyList POIs
{

    get
    {
        throw new NotImplementedException ();
    }
}

Exception:
C:\Users\Nouman Aslam\Documents\Projects\POIApp\POIApp\POIJsonService.cs(10,10): Error CS0305: Using the generic type 'System.Collections.Generic.IReadOnlyList' requires 1 type arguments (CS0305) (POIApp)

A: IReadOnlyList is a generic.  You need to specify the type it is using, like
IReadOnlyList<string> or IReadOnlyList<int> or IReadOnlyList<MyClass>


text:
Q: Flyway migrations don't work when the version is 0 When I have a file with 0 as the version number, Flyway won't pick it up.
Maven dependency:
<dependency>
    <groupId>org.flywaydb</groupId>
    <artifactId>flyway-core</artifactId>
    <version>3.2.1</version>
</dependency>

Spring Configuration:
<bean id="flyway" class="org.flywaydb.core.Flyway" init-method="migrate">
    <property name="dataSource" ref="dataSource" />
    <property name="baselineOnMigrate" value="true" />
    <property name="locations" value="classpath:/META-INF/db/" />
    <property name="placeholders">
        <map>
            <entry key="username" value="" />
        </map>
    </property>
</bean>

Files in classpath:/META-INF/db/

*

*sql/V0_1__INITIAL_BUILD.sql (creates a table)

*sql/V1_3__from-0.1.sql (adds a column)

*sql/V1_4__from-1.3.sql (adds indexes to the table)

When I start my service, I get this error
java.sql.SQLSyntaxErrorException: ORA-00942: table or view does not exist

This is what gets inserted into the schema_version table:

COLUMN          |ROW1               |ROW2
version_rank    |1                  |2
installed_rank  |1                  |2
version         |1                  |1.3
description     |Flyway Baseline    |from-0.12
type            |BASELINE           |SQL
script          |Flyway Baseline    |sql/V1_3__from-0.1.sql
checksum        |-993203535         |
installed_by    |DBUSER2            |DBUSER2
installed_on    |25-AUG-15          |25-AUG-15
execution_time  |0                  |120
success         1                   |0

It looks like it's ignoring the sql/V0_1__INITIAL_BUILD.sql file that actually creates the table and moves immediately to sql/V1_3__from-0.1.sql and fails.
The command line tool doesn't seem to have this issue.
Is it just not possible to use 0 as the version number using Spring or am I missing something obvious?

A: Thats correct by default 1 is the baselineversion from which it starts executing all scripts in sequence. And in order to override the default version from 1 to 0 pls use following on the flyway config at XML :-
<property name="baselineVersion" value="0" />

Thanks.


text:
Q: Best way to share code between WPF and Silverlight I have a solution that contains both a Silverlight 4 and a WPF 4 solution. One is the web version of the app and one is the desktop version.
Both projects have similar domain classes and interfaces and both access the cloud for storage and other stuff.
I wanted to create a common Interfaces and Classes project, so I created a Class Library, but wouldnt you know it, Silverlight cannot add a reference to a Class Library. So I created the common project as a Silverlight Class Library, but when I reference that from the WPF project I get warnings:
Warning    The project 'Interface.Common.Silverlight' cannot be referenced.  The referenced project is targeted to a different framework family (Silverlight)
and I even get class loading runtime errors when I use any class from that library because "System.Windows cannot be found at runtime"
I want to share code between the two projects, how can this be achieved in a clean way?
Thanks for any help you can give

A: Create two parallel projects one for WPF and one for Silverligth.  For one of the projects, add the files as links instead of files.
I have done this sucessfully for the Microsoft Silverlight Analytics Framework with one code base for Silverlight 4, WPF, and Windows Phone 7.

A: What about xaml sharing code with silverlight and WPF

A: Create a "Portable" project.
that can be referenced from both WPF and Silverlight


text:
Q: Object as queryParams in Angular 7 I have an object:
let paramsObj = {
    mode: "resetPassword",
    oobCode: "dsaSdsxSFXx",
    apiKey: "OQPzWYkFNe",
    lang: "en"
   }

I want to use this object as queryParams for router navigate:
this.router.navigate(['/action', { queryParams: paramsObj}]);

But this is doesn't work. What is the correct way to do this?

A: My bad, I wrote this.router.navigate(['/action', { queryParams: paramsObj}]);,
but this is should be this.router.navigate(['/action'], { queryParams: paramsObj});
, and then it work as expected.