text:
Q: Hybris extending Backoffice editing area I know how to add a field to the editing area in the hmc, but I'm kind of despair with the backoffice.

Right now I'm trying to extend the OAuthClientDetailsModel and try to edit it over the backoffice. For that I extende it over the core-items.xml:
<typegroup name="OCC">
    <itemtype code="OAuthClientDetails" autocreate="false" generate="false">
        <attributes>
            <attribute qualifier="brands" type="StringList" autocreate="false">
                <modifiers read="true" write="true" search="true" optional="true"/>
                <persistence type="property"/>
            </attribute>
        </attributes>
    </itemtype>
</typegroup>

Until now everything is fine.
Now to the backoffice. For that I need to edit the backoffice-config.xml.
My current code, which is not working correctly looks like this:
<context merge-by="type" parent="Item" type="OAuthClientDetails" component="editor-area">
    <editorArea:editorArea name="">
        <editorArea:tab name="hmc.tab.category.common" merge-mode="append">
            <editorArea:section name="section.oauthclient.scope" merge-mode="append">
                <editorArea:attribute qualifier="brands"/>
            </editorArea:section>
        </editorArea:tab>
    </editorArea:editorArea>
</context>

This created a new tab and section with equal names, which I don't.
I have the following questions:

*

*is there a easy way to figure out the visible tab and section name?

*how can I add in the first tab, into an existing sextion another list of strings or other fields?

*is there somewhere

A: In every editor area, there two main onglet : essential and administration.
Essential : it's always showing, even when you switch between onglet.
Administration : is the onglet, where all not categorized attributes goes.
If you don't want to create a new onglet, for your attribute, just use the existing onglet/section :
For your type :
sections : hmc.essential, section.oauthclient.basics, section.oauthclient.scope, section.oauthclient.tokenvalidity,section.oauthclient.disabled .
So, lets add it to section section.oauthclient.scope. you need to keep the same tab "hmc.tab.common".
    <context merge-by="type" parent="GenericItem" type="OAuthClientDetails" component="editor-area">
    <editorArea:editorArea xmlns:editorArea="http://www.hybris.com/cockpitng/component/editorArea">
        <editorArea:tab name="hmc.tab.common">
            <editorArea:section name="section.oauthclient.scope" merge-mode="append">
                <editorArea:attribute qualifier="brands"/>
            </editorArea:section>
        </editorArea:tab>
    </editorArea:editorArea>
</context>


text:
Q: What is the best way to set up a Spring JPA to handling searching for items based on tags? I am trying to set up a search system for a database where each element (a code) in one table has tags mapped by a Many to many relationship. I am trying to write a controller, "search" where I can search a set of tags which basically act like key words, giving me an element list where the elements all have the specified tags. My current function is incredibly naive, basically it consists of retrieving all the codes which are mapped to be a tag, then adding those a set, then sorting the codes by how many times the tags for each code is found in the query string.
  public List<Code> naiveSearch(String queryText) {
    String[] tagMatchers = queryText.split(" ");
    Set<Code> retained = new HashSet<>();
    for (int i = 0; i < Math.min(tagMatchers.length, 4); i++) {
      tagRepository.findAllByValueContaining(tagMatchers[i]).ifPresent((tags) -> {
        tags.forEach(tag -> {
              retained.addAll(tag.getCodes());
            }
        );
      });
    }
    SortedMap<Integer, List<Code>> matches = new TreeMap<>();
    List<Code> c;
    for (Code code : retained) {
      int sum = 0;
      for (String tagMatcher : tagMatchers) {
        for (Tag tag : code.getTags()) {
          if (tag.getValue().contains(tagMatcher)) {
            sum += 1;
          }
        }
      }
      c = matches.getOrDefault(sum, new ArrayList<>());
      c.add(code);
      matches.put(sum, c);
    }
    c = new ArrayList<>();
    matches.values().forEach(c::addAll);
    Collections.reverse(c);
    return c;

  }

This is quite slow and the overhead is unacceptable. My previous trick was a basically retrieval on the description for each code in the CRUDrepository

public interface CodeRepository extends CrudRepository<Code, Long> {

  Optional<Code> findByCode(String codeId);
  Optional<Iterable<Code>> findAllByDescriptionContaining(String query);

}

However this is brittle since the order of tags in containing factors into whether the result will be found. eg. I want "tall ... dog" == "dog ... tall"

A: So okay, I'm back several days later with how I actually solved this problem. I used hibernate's built in search library which has a very easy implementation in spring. Just paste the required maven coordinates in your POM.xml and it was ready to roll.
First I removed the manytomany for the tags<->codes and just concatenated all my tags into a string field. Next I added @Field to the tags field and then wrote a basic search Method. The method I wrote was a very simple search function which took a set of "key words" or tags then performed a boolean search based on fuzzy terms for the the indexed tags for each code. So far it is pretty good. My database is fairly small (100k) so I'm not sure about how this will scale, but currently each search returns in about 20-50 ms which is fast enough for my purposes.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Allow only one decimal value float while entering itself in JTable column? I implemented the JTable in my GUI. And make it 3rd column editable by Overriding isCellEditable(int row, int column) in MyTableModel.
Now I'm trying to allow only float value with one decimal location to my editable column. I have tried to implement CellEditorListener, control is coming to method only after all input edited. But I want to restrict while typing itself.
How can I overcome this problem?


text:
Q: In Rails 3, how can I skip validation of the password field when I'm not attempting to update the password? My User model contains :name, :email, and :password fields.  All 3 have validations for length.  An "update account" web page allows the user to update his name and email address, but not password.  When submitted, params[:user] is
{"name"=>"Joe User", "email"=>"user@example.com"}

Note there is no "password" key because the form doesn't contain such an input field.
When I call
@user.update_attributes(params[:user])

the password validation fails.  However, since I'm not attempting to update the password, I don't want the password validation to run on this update.  I'm confused why the password validation is running when params[:user] doesn't contain a "password" key.
Note that I want to have a separate web page elsewhere that allows the user to update his password.  And for that submission, the password validation should run.
Thank you.

A: My application does something like this
attr_accessor :updating_password

validates_confirmation_of :password, :if => should_validate_password?

def should_validate_password?
  updating_password || new_record?
end

so you have to model.updating_password = true for the verification to take place, and you don't have to do this on creation.
Which I found at a good railscast at http://railscasts.com/episodes/41-conditional-validations

A: In your user model, you could just ignore the password validation if it's not set.
validates_length_of :password, :minimum => N, :unless => lambda {|u| u.password.nil? }

A: Using update_attributes will not change the value of the password if there is no key for it in the params hash.
Validation doesn't run against the changed fields only. It validates existing values too.
Your validation must be failing because the password field contains some invalid content that's already saved in the database. I'm guessing it's probably because you're hashing it after validation and you're trying to validate the hashed string.
You can use a virtual attribute (an instance variable or method) that you validate with a custom method, and then assign the hash to the stored password field. Have a look at this technique for ideas.

A: An app that I am working on uses the following:
    validates_confirmation_of :password,
                              :if => Proc.new { |account|
                                                !account.password.blank?
                                                || !account.password_confirmation.blank?
                                                || account.new_record? }

Depending on your requirements, you might want to remove the new_record? check

A: When password is added then only confirmation will be called and presence will call on create action only

   **validates_presence_of :password, :on =>:create**

   **validates_confirmation_of :password**


text:
Q: Get Black and White 2 BIT image using Emgu CV Hi have a image which I need to convert into black and white and in 2 bit depth.
I tried following and it generates an image with 8 bit. Don't see any option to generate image of 2 bit.
Emgu.CV.Image<Gray, Single> image = new Emgu.CV.Image<Gray, Single>("test.jpg");

Can someone please advise?

A: In emgucv you have the following image Depth
Byte, SByte, Single (float), Double, UInt16, Int16, Int32 (int)
(from emgucv)
You do not have an 2 bit depth.
But you can make an images that looks like an 2 bit image like this:
var theImage = new Image<Gray, byte>(@"d:\temp\lena.jpg");
        for (int i = theImage.Rows - 1; i >= 0; i--)
        {
            for (int j = theImage.Cols - 1; j >= 0; j--)
            {
                if(theImage.Data[i,j,0]>byte.MaxValue/2)
                {
                        theImage.Data[i, j, 0] = byte.MaxValue;
                }
                else
                {
                    theImage.Data[i, j, 0] = 0;
                }

            }
        }


text:
Q: How to navigate pages with React Navigator Having trouble moving pages in React Navigator, it worked fine when we had homeStack and would just run through an object but now that we're trying to introduce a stationary button in the header that moves to another page it is running into problem. We still move just fine when we go from first to second page, but I think we're missing something.
OnPress is working when we press the folder icon as we console logged it, but it simply takes us back to our starting screen rather than to the screen we want to get to. I've tried to share the code needed but let me know if other pages are needed.
Below is our Header component, you can see where we're trying to onPress and then navigate.
import React from 'react';
import {StyleSheet, Text, View} from 'react-native';
import {MaterialIcons} from '@expo/vector-icons';
import History from '../History'
import { NavigationContainer, StackActions } from "@react-navigation/native";
import { createNativeStackNavigator } from 'react-navigation-stack';

export default function Header({ navigation }){

    const historyFolder = () => {
        navigation.navigate('History')
    }

    return(
        <View style={styles.header}>
        <View>
            <Text style={styles.headerText}></Text>
        </View>
        <MaterialIcons name='folder' size={28} onPress={historyFolder} style={styles.icon}></MaterialIcons>
        </View>
    )

}

const styles = StyleSheet.create({
    header: {
      width: '100%',
      height: '100%',
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'center',
    },
    headerText: {
      fontWeight: 'bold',
      fontSize: 20,
      color: '#333',
      letterSpacing:1,
    },
    icon:{
      position: 'absolute',
      right: 16,
    }
  })

This is the History page that we're aiming to get to.
import { StyleSheet, Text, View, FlatList, SafeAreaView, Image } from 'react-native'
import Card from './shared/Card';
import React from 'react';
import { NavigationContainer, StackActions } from "@react-navigation/native";
import { createNativeStackNavigator } from 'react-navigation-stack';

export default function History({navigation}) {
    const present = [{
        id: 1,
        name: 'PresentOne',
        slug: 'PresentOne Slug',
        image: require('../assets/present.jpeg')
    },
    {
        id:2,
        name: 'PresentTwo',
        slug: 'PresentTwo Slug',
        image: require('../assets/present2.jpeg')
    },
    {
        id:3,
        name: 'PresentThree',
        slug: 'PresentThree Slug',
        image: require('../assets/present3.jpeg')
    },
    {
        id:4,
        name: 'PresentFour',
        slug: 'PresentFour Slug',
        image: require('../assets/present4.jpeg')
    },
    {
        id:5,
        name: 'PresentFive',
        slug: 'PresentFive Slug',
        image: require('../assets/present5.jpeg')
    },
];

const onePresent = ( { item } ) => (
<Card>
    <View style={styles.item}>
        <View style={styles.avatarContainer}>
            <Image source = {item.image} style={styles.avatarContainer}/>
        </View>
            <Text style={styles.name}> {item.name}</Text>
            <Text style={styles.slug}>{item.slug}</Text>
    </View>
</Card>
)

const headerComponent = () => {
  return <Text style={styles.listHeadline}>Presents</Text>
}

const itemSeperator = () => {
    return <View style = {styles.seperator}/>
}

return (
    <View>
            <FlatList
            ListHeaderComponentStyle={styles.listHeader}
            ListHeaderComponent={headerComponent}
            data = { present }
            renderItem = { onePresent }
            ItemSeperatorComponent = { itemSeperator }
            ListEmptyComponent = { <Text>Empty</Text>}
            />
    </View>

    );
}

const styles = StyleSheet.create({
    slug:{
        transform: [{translateX: -100}],
        // alignContent: 'center',
        flexDirection: 'column',
        alignItems: 'center',
    },
    name:{
        transform: [{translateY: -30},{translateX: 10}],
        fontSize: 20,
    },
    listHeadline:{
        color:'#333',
        fontSize: 21,
        fontWeight: 'bold',
    },
    item: {
        flex:1,
        flexDirection:'row',
        alignItems:'center',
        paddingVertical:13,
    },
    avatarContainer:{
        backgroundColor:'#D9D9D9',
        borderRadius:100,
        height:89,
        width:89,
        justifyContent:'center',
        alignItems: 'center',
        margin:10,
    },
    listHeader:{
        height:55,
        alignItems:'center',
        justifyContent: 'center'
    },
    seperator: {
        height: 1,
        width: '100%',
        backgroundColor: '#CCC',
    }
})

And this is the homeStack we're running the page from.
import React from 'react';
import {StyleSheet, View, Text} from 'react-native';
import { createStackNavigator } from 'react-navigation-stack'
import { createAppContainer } from 'react-navigation'
import PositiveCollectForm from '../Components/PositiveCollectForm';
import NegativeCollectForm from '../Components/NegativeCollectForm';
import Swipe from '../Components/Swipe';
import History from '../Components/History';
import Header from '../Components/shared/Header';

const screens = {

    PositiveCollectForm: {
        screen: PositiveCollectForm,
        navigationOptions: ({ navigation }) => {
            return {
                // headerTitle: () => <Header navigation={navigation} />
            }
        }
    },
    Swipe: {
        screen: Swipe,
        navigationOptions: {
            title: '',
            headerTitle: () => <Header navigation={navigation} />
        },
    },
    History: {
        screen: History,
        navigationOptions: {
            title: '',
            headerStyle: {backgroundColor: '#555'}
        }
    },

}

const HomeStack = createStackNavigator(screens);

export default createAppContainer(HomeStack);


text:
Q: what's the difference between search_after and range query in elasticsearch It seems that search_after is equivalent to {range:{"gt":xxx}} when used in iterating an index.
I wander that's their difference in terms of semantics and performance.

A: They serve different purposes. With search_after you can paginate over 10K results (whatever the query), whereas the range query will only allow you to select a subset of your index and if there are more than 10K documents matching that range, you'll not be able to get them all.


text:
Q: How to change URL of pagination in CakePHP I click on the next link. It shows me the URL like
http://www.domainname.com/fj_messages/index/page:2

I want to change it like change this to
fj_messages/index/page:2

Like
message/inbox/2
Can I do like this?

A: @gaioshin WTF.. That is the worst thing I've seen with regards to custom routes.
Router::connect('message/inbox/:page', array('controller' => 'fj_messages', 'action' => 'index'), array('pass' => array('page')));

Something like that should do it just the way you want.  Check out routing for more information.
The page will be in $this->params['page'] if I remember correctly.


text:
Q: Drupal menu activation I have a probably common question. For example whe have material type "news" and page made by views that displaying news teasers. We have menu item "news", that link to our view page and have url example.com/news. Each news page have url like example.com/news/[news title]. How could we set menu item "News" to be active on such pages /news/[news title]?

A: The Menu Trail By Path module does exactly that:

This module sets the active-trail on menu items according to the current url.

I've used it for ages and it works great

A: I recommend the context module. It allows you to set the active trail based on url, view, content type, etc. Very powerful interface.


text:
Q: How do I include the CLDR.js library in my Ember application? I'm building an Ember application which started using the ember-skeleton (which means I'm using Rake Pipeline as my build toolchain). I'm using ember-i18n, and that constantly throws warnings about not having the CLDR.pluralForm function.
I've added the CLDR plural functions which ember-i18n uses to the app/vendor/ directory and added that file to my Assetfile. I've verified that the code is included in my app.js before the ember-i18n code. I've also added the appropriate require lines in my main.js:
require('plurals');
require('ember-i18n');

Still, ember-i18n is giving warnings. This is the code where it's happening:
if (typeof CLDR !== "undefined" && CLDR !== null) {
  pluralForm = CLDR.pluralForm;
}

if (pluralForm == null) {
  Ember.Logger.warn("CLDR.pluralForm not found. Em.I18n will not support count-based inflection.");
}

How do I make sure CLDR is defined in my app?

A: Because no-one else has, I will suggest a few things I might look at if I were debugging the problem myself.
If the message you see in your site is the same as in the fiddler, it is due to the files just load out of order.  Pretty much "plural" must load before the "i18n" plugin.  If you flip the order of the linked files it will work (I forked the error-ing example).
I would try validating I am wrong by throwing some debugger; statements into each file to see which actually gets loaded first on the browser.
Because of your require('plurals') I am going to assume you are using requirejs (github is down for maintenance so I can't actually examine ember-skeleton at the moment... so this might get an edit in the future).  If this assertion is true, you need to declare that 'plurals' is a dependency of 'i18n'.

"If you do not express the dependencies, you will likely get loading errors since RequireJS loads scripts asynchronously and out of order for speed." - RequireJS API

This means you probably will end up wrapping the two calls into one, adding a define or making a "shim"; these (and more) examples can be found on the RequireJS site.
Sorry if this does not help you but without seeing it actually broken; it is hard for me to debug the problem.
EDIT: Looking at the ember-skeleton, I don't see requireJS.  I have never used rake (we ended up writing our pipeline in nodeJS) so I am not quite sure if you were actually trying to concat the files with require "blaw" in rake or if you actually trying to use both.... So now I assume this answer might not be super helpful.


text:
Q: How to write topography function for eeg I am writing a HW neurofeedback app. Which wotks like this:
https://www.youtube.com/watch?v=pjCghiq5FoQ
In this case it is a demo which is not actually working. I have data from EEG and I want to plot them on the surface by LEDs. The technique is similar to this output:
http://www.fieldtriptoolbox.org/_media/tutorial/natmeg_temp/natmeg_freq11.png?w=400&tok=6e5a3c
But I need to write it on my own because I need to light the LEDs instead to show 2D image. Basically I have no clue where to start.
My goal is to vizualize spectral density for each EEG channel by each LED as you can see demo on youtube. I would appritiate any help, even teoretical one.
I know I need signal and electrodes position in x, y, z e.g. indentifiation of LED number on the sculpture.¨
Thank you,
Michael

A: you have multichannels EEG recordings. I suspect you have the positions of these channels. You also have the (rough) position of your LEDs on the head.
Interpolate your data to find the power at the LED positions.
ledInput = interp2(Xeeg,Yeeg,EEGpower,Xled,Yled),

to find the RGB colors corrisponding to the power values:
ledInput = rand(32); % create fake data for testing
colorResolution = 256; % choose a color resolution
colors = jet(colorResolution); % creates a colorbar of 256 elements. (you can change "jet" with any other colorbar of matlab)
ledInput = (ledInput-min(ledInput))/range(ledInput); % change range btwn 0 and 1
ledInput = round(ledInput*(colorResolution-1))+1; % turn the power values into index for the colormap
ledInput = colors(ledInput,:); % find the colors for your leds


text:
Q: How can I generate a consistent entity graph (say from 10 tables) from a database fetch Suppose I have many tables in a database that need to be joined together to get a single consistent view of the entire entity graph. Am I forced to do this as a single query? I don't care about locks, I just want to ensure the graph is consistent as of the time of the query execution.
My concern is one of performance of joining a large number of entities together in a single query. Is it possible to do this in multiple queries but still realize the same level of consistency as having performed these individual selects as a single query?

A:
Is it possible to do this in multiple queries but still realize the same level of consistency as having performed these individual selects as a single query?

It depends on the RDBMS.
In SQL Server you can use a transaction with SNAPSHOT transaction isolation level to get a consistent view of the database across multiple queries.
The isolation level Oracle calls SERIALIZABLE does the same thing.

My concern is one of performance of joining a large number of entities together in a single query

This is a valid concern because most RDBMS engines only return tabular results from queries. The strategies to generate a single tabular result for a complex object graph can lead to large resultsets and complex queries.  This has always been a problem for ORMs.


text:
Q: How can I use the 'try' and 'except' for positive scalars and positive vectors in python? Imagine I have a function in python having 4 arguments, a,b,c,d. Now the variable 'a' should be a numpy array, 'b' should be either zero or a posive scalar, 'c' should be a strictly positive scalar and 'd' should be a strictly positive numpy array;
Now I would like to use the 'try' and 'except' syntax to create custom error messages, if the inputs do not fit; I managed it for the general numpy array but I failed to do something similar for the other variables - can someone maybe help me?
The function so far is given by:
import numpy as np

def test(a,b,c,d):
    try:
        n=np.size(a,0)
        d=np.size(a,1)
    except:
        raise Exception('a must be a numpy n x d array')


text:
Q: How to search through a JSON feed I'm using the code below and make a call to the Google Maps API and parse some JSON data.
def getLocalityFromPostCode(postcode):
    import urllib, json
    import pprint
    url = "http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false" % postcode
    googleResponse = urllib.urlopen(url)
    jsonResponse = json.loads(googleResponse.read())
    return jsonResponse

This works fine. However, i only need the value from['results']['address_components'] where the 'type' is  [ "locality", "political" ] however, the index of this value differs depending on how precise the given postcode string is.
If i give a straight poscode (like XX10) the value appears in the 0th item in the address_components list. However, if i give a city and postcode it appears in the 1st item.
Can someone help me please. I need to search through address_components for the [ "locality", "political" ] value.
EDIT
You can view te feeds at http://maps.googleapis.com/maps/api/geocode/json?address=sy4&sensor=false (just postcode) and http://maps.googleapis.com/maps/api/geocode/json?address=47%20High%20Street%20Shrewsbury,%20SY4&sensor=false (full address).
As you can see in example 1 the data I'm looking for is in index 1, whereas in the second example the data I'm looking for is in index 2.

A: This looks like what you want :)
results = json.load(googleResponse)['results']

for result in results:
    for address_component in result['address_components']:
        if address_component['types'] == ['locality', 'political']
            # address_component['long_name'] and
            # address_component['short_name'] are your data
            break

The cool thing about JSON and Python dicts is that you don't need to index by number, you index by name. In this case, your object (or at least the data you care about) breaks down like this:
'results': # a list of resulting dicts
[
    { # one of those resulting dicts
        'address_components':  # a key, representing some other data
        [ # which, in this case, is a list of address component dicts
            { # like this
                'long_name': 'A String. The Long Name.'
                'short_name': 'Another String. The Short Name.'
                'types': # a list of type strings
                [
                    'locality', # one of the types
                    'political' # the other type
                ]
            }
        ]
    }
]

A: Create an object from the json and access the values by the keys
import json
obj = json.loads(jsonString)


text:
Q: UIImage setImage: cause memory leak I got a memory leaking problem from a very simple function. Here is my code:
  -(void) drawPuzzle
 {

      gameView.image=nil;

      UIGraphicsBeginImageContext(gameView.frame.size);

      [gameView.image  drawInRect:CGRectMake(0,
                                             0,
                                             gameView.frame.size.width,
                                             gameView.frame.size.height)];

       CGContextRef con=UIGraphicsGetCurrentContext();
       CGContextMoveToPoint(con, 20,0);
       CGContextAddLineToPoint(con,20, gameView.frame.size.height);
       CGContextStrokePath(con);

       UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
       UIGraphicsEndImageContext();
       [gameView setImage:newImage];

  }

The instruments report as below:
Event Type    RefCt      Responsible Caller

Malloc        1          +[UIImage imageWithCGImage: scale: orientation:]
Autorelease              +[UIImage imageWithCGImage: scale: orientation:]
Retain        2          -[UIImageView setImage:]
Release       1          -[NSAutoreleasePool drain]

A: setImage: method retained your newImage. To avoid memory leak you need to release newImage after setImage
   UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();
   [gameView setImage:newImage];
   [newImage release];


text:
Q: NSOperation running on main thread I've used this guide to make my app use NSOperationQueue and NSOperations. But my code still runs on the main thread regardless :S? I must say that I'm new to NSOperation, I think it is a small thing that I missed.
class CountryFetcher: NSObject{
    var operation: NSOperation?
    var alamoFireQueue: NSOperationQueue{
        let val = NSOperationQueue()
        val.maxConcurrentOperationCount = 10
        val.name = "Alamofire Downloading Queue"
        return val
    }

    func getCountries(){
        operation = CountryProcessor(URLString: (BASE_URL + "countries/"+CAT_STAMPS))
        alamoFireQueue.addOperation(operation!)
    }
}

class CountryProcessor : ConcurrentOperation {
    let URLString: String
    weak var request: Alamofire.Request?

    init(URLString: String) {
        self.URLString = URLString
        super.init()
    }

    override func main() {
        request = Alamofire.request(.GET, URLString).responseJSON { response in
            if let dataResponse = response.data{
                var test: NSArray?
                do{
                    test = try NSJSONSerialization.JSONObjectWithData(dataResponse, options: NSJSONReadingOptions()) as! NSArray
                }catch let error as NSError{
                    print(error.localizedDescription)
                }
                for _ in 1...100{
                        NSLog("main thread? %@", NSThread.isMainThread() ? "YES" : "NO");
                }
            }
            self.completeOperation()
        }
    }

    override func cancel() {
        request?.cancel()
        super.cancel()
    }
}

This is the ConcurrentOperation class. I copied it from the post in the link above.
class ConcurrentOperation : NSOperation {

    override var asynchronous: Bool {
        return true
    }

    override var concurrent: Bool{
        return true
    }

    private var _executing: Bool = false
    override var executing: Bool {
        get {
            return _executing
        }
        set {
            if (_executing != newValue) {
                self.willChangeValueForKey("isExecuting")
                _executing = newValue
                self.didChangeValueForKey("isExecuting")
            }
        }
    }

    private var _finished: Bool = false;
    override var finished: Bool {
        get {
            return _finished
        }
        set {
            if (_finished != newValue) {
                self.willChangeValueForKey("isFinished")
                _finished = newValue
                self.didChangeValueForKey("isFinished")
            }
        }
    }

    /// Complete the operation
    ///
    /// This will result in the appropriate KVN of isFinished and isExecuting

    func completeOperation() {
        executing = false
        finished  = true
    }

    override func start() {
        if (cancelled) {
            finished = true
            return
        }

        executing = true

        main()
    }
}

When I execute this code, it keeps saying that it runs on the main thread: 2016-08-12 18:25:45.799 Stamp Catalague Preloader[1807:31357] main thread? YES.
How is this happening? Thanks for your help;

A: The issue is that Alamofire dispatches its completion handlers to the main queue (the theory being that they want to make it easy for you to update the UI and/or model).
If you want to use a different queue for the completion handlers, supply the queue parameter to the response or responseJSON methods.
For example, have some property:
var completionHandlerQueue = dispatch_queue_create("com.domain.completionhandler", nil)

And then, when you perform the request:
Alamofire.request(.GET, URLString).responseJSON(queue: completionHandlerQueue) { response in
    guard let test = response.result.value else {
        print("no data")
        print(response.result.error)
        return
    }

    // do something with `test` here
    print(test)

    NSLog("main thread? %@", NSThread.isMainThread() ? "YES" : "NO");
}

This raises the question of whether you really care if the completion handlers are called on the main queue or not. Sure, if you're doing something computationally intensive there, then, by all means, specify a different queue. But there's no reason why an operation can't perform some of its tasks on the main queue. In fact, it's awfully useful at times to just have the completion handlers run on the main queue, saving you from needing to synchronize your model updates and/or dispatch your UI updates to the main queue.
To step back even further, we have to ask what the intent of using NSOperation is. If the goal is merely to enjoy asynchronous processing of requests, NSOperation is not needed. But if (a) you're using NSOperation to manage dependencies of different operations; and (b) you're not using background sessions, then, by all means, wrap your requests in operations.


text:
Q: SQL update using its update information With the goals to optimize queries in a legacy application, I came across the following query which aims to update the Materialized Path of hierarchical data.
UPDATE data child
            SET child.MATERIALIZED_PATH = CONCAT((
               SELECT parent.MATERIALIZED_PATH FROM data parent
               WHERE child.PARENT_ID = parent.OBJECT_ID
            ), CONCAT('/', object_id))
            WHERE EXISTS (
            SELECT * FROM data parent
            WHERE child.PARENT_ID = parent.OBJECT_ID);

This empirically works and is coupled with another trivial query to set the roots (which paths are the nodes themselves).
This query is by far the fastest of the other methods I tried (RBAR is obviously slow, I was expecting better from a recursive CTE but it still is about 6x slower).
I can see in the query plan why this is faster and from the looks of it, it can't be further optimized.
What I do not understand is why this works without "explicit recursion". Setting the MATERIALIZED_PATH's value looks like it is only taking into account and concatenating two levels, the parent and the child.
It is obvious that if the parent has already gone through the update, it will be correct, and the query can use its value. But what if the update took a row for which the parent has not been updated? then the parent's value would be incorrect, propagating this incorrect value to the child. Why doesn't this happen? Why is Oracle smart enough to update the values in a hierarchical fashion, which I would guess has nothing to do with a hierarchy, but is simply updating rows using rows that will not receive further updates.
I'd like to know more about this feature so that I can read about it, because had I not seen that legacy query, I wouldn't have known this was an option.

A: As mentioned in the comments (thank you!), there is no predefined order of row processing, and the kindly provided fiddle directly shows the script's output is incorrect.
The question is void since it was based on a false assumption. The snippet produces incorrect data. This also explains why the algorithm is faster, since there is no recursion involved.


text:
Q: Put data-id value into form action I have a button to pass data in an array.
Edit

When i click the button, runs the below javascript code into a modal with a form. My intention is to pass certain value to the form's input textbox. and also pass a value in  action="".
$(document).on("click", ".open-EditNetworkDialog", function () {
    var varAccountDetail = $(this).data('id');
    $(".modal-body #network").val( varAccountDetail[0] );
    $(".modal-body #name").val( varAccountDetail[1] );
});

I am able to send the value "abcde" to the form's input.
How do i replace the form action with the value "id12345"?
eg. <form action="id12345">

Edit

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

        <form action="">

Name: <input class="form-control" type="text" name="Name" id="name" value="">

                <button class="btn btn-lg btn-primary btn-block">Submit</button>

        </form>

A: Just use attr to change the action of form tag
JS Code -
$('form').attr('action', '<Value that you want to put in action>');

In your case, it should look something like below
$('form').attr('action', varAccountDetail[0]);

A: Welcome to the community..!
You can change the actions of form by using this single line of code.
$('form').attr('action', 'id12345');

id12345 can be changed with your variable, like this:
$('form').attr('action', varAccountDetail[0]);

A: If you want to edit your form action
$('form').attr('action', varAccountDetail[0]);


text:
Q: Create a copy of string I have a class variable my_set which is a set, and into which I am adding strings:
MyClass.my_set.add(self.some_string_property)
My problem is that the instance of the class that runs the above may get garbage collected at any time, and when that happens I think I lose its some_string_property in my_set class variable.
In order to preserve some_string_property in my_set for each instance, I need to create a copy of it and store that copy into my_set. What is the right way to do so? I've tried the  copy module but it doesn't work on strings.

A: As long as you keep at least one reference to the string, it will not be garbage collected (and if you have no references left, then you have no way of accessing it anyway).


text:
Q: how to compare current and last element iterated from numpy without loop In 2d array get the last column and compare current value with its last iterated value and if the difference is == 1 then get row indexes of both of them . I able to do it using for loop but it gets slow when array grows as there are multiple conditions next after getting indexes
x=np.array ([[79, 50, 18, 55, 35],
            [46, 71, 46, 95, 80], #1
            [97, 37, 71,  2, 79], #2
            [80, 96, 60, 85, 72],
            [ 6, 52, 63, 86, 38],
            [35, 50, 13, 93, 54], #5
            [69, 21,  4, 40, 53], #6
            [18, 34, 91, 67, 89],
            [82, 16, 16, 24, 80]])

last_column = x[:,[-1]]
for kkk in range(1,len(last_column)):
    if last_column[kkk] == last_column[kkk-1] + 1 \
    or last_column[kkk] == last_column[kkk-1] - 1 :
        print('range',last_column[kkk],last_column[kkk-1])

ouput is -
[80]
[79]
range [79] [80]
[72]
[38]
[54]
[53]
range [53] [54]
[89]
[80]

A: I don't think there is a way of doing this in python that doesn't use a loop (or a function that utilizes a loop). But I would suggest something like this, it worked quite well for me:
import numpy as np

x = np.array([[79, 50, 18, 55, 35], [46, 71, 46, 95, 80], [97, 37, 71, 2, 79],[80, 96, 60, 85, 72], [ 6, 52, 63, 86, 38], [35, 50, 13, 93, 54], [69, 21,  4, 40, 53], [18, 34, 91, 67, 89], [82, 16, 16, 24, 80]])

last_column = x[:,-1]

for kkk in range(1,len(last_column)):
    if abs(last_column[kkk] - last_column[kkk-1]) == 1:
        print('range',last_column[kkk],last_column[kkk-1])

This performed quite well on my device in about, 0.00023s possibly less.

A: You can use np.diff to compute the difference between all the numbers, and select those that are 1 or -1, and use np.pad to shift the resulting mask to get the n-1 items, and finally zip them together:
diff = np.insert(np.diff(x[:, -1]), 0, 0)
ix = (diff == -1) | (diff == 1)
z = zip(x[:,-1][ix], x[:,-1][np.pad(ix, (0,1))[1:]])

for first, second in z:
    print('range', first, second)

Output:
range 79 80
range 53 54


text:
Q: Host ::1 resolves to remote IP /etc/hosts files usually have this line, ::1 localhost. I thought ::1 was the equivalent of 127.0.0.1/localhost, and from my reading it seems to be the IPv6 version. So I was using it in Apache for firewalling, "Allow from ::1" and it only allowed local. Then suddenly that stopped working, so I pinged ::1 and got a remote IP address. I tracerouted it and it went through my ISP, through some Microsoft server, then another half dozen steps of asterisks...
I'm not sure why this would be (the remote IP), but it doesn't seem good. I grep'd my hard drive for the remote IP and it doesn't appear anywhere. Is this some indicator that I'm being hacked, or normal behavior? Maybe my IPv6 settings are wrong? (This is a brand new MacBookPro with Snow Leopard.)
Any ideas about this would be great - what is ::1 supposed to be, why would it be remote, should I be worried, how do I get it back to localhost? Thank you!

A: The problem is probably that ping doesn't handle IPv6, it's a tool from the good old IPv4 days. Since it doesn't recognize ::1 as a valid IPv4 address, it'll try to resolve it like a domain. For some reason, the DNS server you're using responds with a valid IPv4 address for this "domain".
To ping the IPv6 address, use ping6 ::1, which should yield answers from your localhost.
To trace where the DNS answer is coming from, try running dig ::1 +trace.


text:
Q: db2 select distinct rows, but select all columns Experts, I have a single table with multiple columns. col1, col2, col3, col4, col5, col6
I need to select distinct (col4),  but I need all other columns also on my output.
If I run, this ( select distinct(col4 ) from table1 ), then I get only col4 on my output.
May I know, how to do it on db2?.
Thank you

A: You simply do this...
Select * From Table1 Where col4 In (Select Distinct(col4) From Table1)

A: I'm not sure if you will be able to do this.
You might try to run group by on this column. You will be able to run some aggregate functions on other columns.
select count(col1), col4 from table1 group by (col4);

A: none of the answers worked for me so here is one that i got working. use group by on col4 while taking max values of other columns
select max(col1) as col1,max(col2) as col2,max(col3) as col3
  , col4
  from
    table1
  group by col4

A: At least in DB2, you can execute
SELECT
  DISTINCT *
FROM
<YOUR TABLE>

Which will give you every distinct combination of your (in this case) 6 columns.
Otherwise, you'll have to specify what columns you want to include.  If you do that, you can either use select distinct or group by.


text:
Q: Study the convergence of this series of functions: $\sum_{n=1}^{\infty }n^x\left ( \tan\frac{x^n}{n}-\sin\frac{x^n}{n} \right )$ I tried to study the convergence of this series:
$$\sum_{n=1}^{\infty }n^x\left ( \tan\frac{x^n}{n}-\sin\frac{x^n}{n} \right )$$
I started to study the pointwise convergence with the limit for $n \to \infty$ of the argument, but without success.
Can you help me to solve this excercise?

A: Since $\sin x = x+O(x^3)$ and $\tan x = x+O(x^3)$ you get $\tan x - \sin x\sim x^3$ and thus the terms asymptotically equivalent to
$$
n^{x-3}·x^{3n}.
$$


text:
Q: distance distribution in Poisson point process Consider a homogeneous Poisson point process in 2D space with density $\lambda$ per unit area. Let $\mathcal{B}(o,R)$ denote a disk centered at origin with radius $R$. Let $n$ be the number of points inside the disk $\mathcal{B}$. Given $n \geq 1$, let $\{d_1, d_2, \ldots, d_n\}$ be the set of radial distances of points inside the disk respect to the origin.
(1) What is the distribution of $n$? Is it a Poisson random variable with density $\lambda \pi R^2$?
(2) What is the distribution of $d_i$, given $n$. Given $n$, are $d_i$s i.i.d random variables with uniform distribution in $[0,R]$?

A: (1) Yes, the Poisson point process is homogeneous (constant intensity $\lambda$ throughout $\mathcal{B}$) so the distribution of $n$ is Poisson with parameter: $\lambda\times(\text{Area of $\mathcal{B}(0,R)$}) = \lambda\pi R^2.$
(2) Given $n,\;$ the $n$ points are uniformly distributed throughout $\mathcal{B}$. Since a circle's circumference is proportional to its radius, the common density $f_D\;$ of $d_i$ for all $i$ is also proportional to its radius. That is, $f_D(d) = ad$, for some constant $a$. We find $a$ as follows:
\begin{align}
1 &= \int_{r=0}^R ar\;dr \\
&= \left[ \dfrac{ar^2}{2}\right]_{r=0}^R \\
&= \dfrac{aR^2}{2}. \\
\therefore\quad a &= \dfrac{2}{R^2}
\end{align}
So $f_D(d) = \dfrac{2d}{R^2}.$


text:
Q: When (if) to consolidate ActiveRecord migrations? As I move through the iterations on my application*(s) I accumulate migrations. As of just now there are 48 such files, spanning about 24 months' activity.
I'm considering taking my current schema.rb and making that the baseline.
I'm also considering deleting (subject to source control, of course) the existing migrations and creating a nice shiny new single migration from my my current schema? Migrations tend to like symbols, but rake db:schema:dump uses strings: should I care?
Does that seem sensible?
If so, at what sort of interval would such an exercise make sense?
If not, why not?
And am I missing some (rake?) task that would do this for me?
* In my case, all apps are Rails-based, but anything that uses ActiveRecord migrations would seem to fit the question.

A: I think that there are two kinds of migrations:

*

*those you made during design/development, because you changed your mind on how your db should be like;

*those you made between releases, reflecting some behaviour changes.
I get rid of the first kind of migrations as soon as I can, as they do not really represent working releases, and keep the second kind, so that it is possible, in theory, to update the app.
About symbols vs strings: many argue that only strings should be used in migrations: symbols are meant to be "handles" to objects, and should not be used to represent names (column and table names, in this case). This is a mere stylistic consideration, but convinced me, and I'm no more using symbols in migrations.
I've read of another point for using strings: "ruby symbols are memory leaks", meaning that, when you create a symbol, it never gets disposed for all the application life time. This seems quite pointless to me, as all your db columns will be used as symbols in a Rails (and ActiveRecord) app; the migrating task, also, will not last forever, so I don't think that this point actually makes sense.

A: The top of schema.rb declares:
# This file is auto-generated from the current state of the database. Instead of editing this file,
# please use the migrations feature of Active Record to incrementally modify your database, and
# then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your database schema. If you need
# to create the application database on another system, you should be using db:schema:load, not running
# all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended to check this file into your version control system.

I must endorse what [giorgian] said above about different migrations for different purposes. I recommend cleaning up development-oriented migrations along with other tasks you do when you branch for a release. That works for well for me, for myself and small teams. Of course my main app sits atop and between two other databases with their own schemas which I have to be careful of so we use migrations (rather than schema restore) for a new install and those need to survive release engineering.

A: Having lots of migrations are a good thing.  Combined with your version control system, they allow you to see what developer made a change to the database and why.  This helps with accountability.  Removing them just makes this a big hassle.
If you really want to get a new database up and running quickly you can just load the schema with rake db:schema:load RAILS_ENV=your_environment and if you want to get your test database setup quick you can just use rake db:test:prepare
That being said, if you really want to consolidate your migrations then I'd create a new migration that checks to see if the very last migration in your set has been performed (ex: does the column you added exist?) and if not, then it will fire.  Otherwise the migration will just add itself to the schema table as completed so it doesn't attempt to fire again.
Just communicate what you're doing to the rest of your team so that they understand what is going on lest they blindly fire off a rake db:migrate and screw up something they already had.

A: Yes, this makes sense. There is a practice of consolidating migrations. To do this, simply copy the current schema into a migration, and delete all the earlier migrations. Then you have fewer files to manage, and the tests can run faster. You need to be careful doing this, especially if you have migrations running automatically on production. I generally replace a migration that I know everyone has run with the new schema one.
Other people have slightly different ways to do this.
I generally haven't done this until we had over 100 migrations, but we can hit this after a few months of development. As the project matures, though, migrations come less and less often, so you may not have to do it again.
This does go against a best practice: Once you check in a migration to source control, don't alter it. I make a rare exception if there is a bug in one, but this is quite rare (1 in 100 maybe). The reason is that once they are out in the wild, some people may have run them. They are recorded as being completed in the db. If you change them and check in a new version, other people will not get the benefit of the change. You can ask people to roll back certain changes, and re-run them, but that defeats the purpose of the automation. Done often, it becomes a mess. It's better left alone.

A: Although I'm sure everyone has their own practices, there's a few rules implied by the way the migration system works:

*

*Never commit changes to migrations that may have been used by other developers or previous deployments. Instead, make an additional migration to adjust things as required.

*Never put model-level dependencies in a migration. The model may be renamed or deleted at some point in the future and this would prevent the migration. Keep the migration as self-contained as possible, even if that means it's quite simplistic and low-level.

Of course there are exceptions. For example, if a migration doesn't work, for whatever reason, a patch may be required to bring it up to date. Even then, though, the nature of the changes effected by the migration shouldn't change, though the implementation of them may.
Any mature Rails project will likely have around 200 to 1000 migrations. In my experience it is unusual to see a project with less than 30 except in the planning stages. Each model, after all, typically needs its own migration file.
Collapsing multiple migrations into a single one is a bad habit to get into when working on an evolving piece of software. You probably don't collapse your source control history, so why worry about database schema history?
The only occasion I can see it as being reasonably practical is if you're forking an old project to create a new version or spin-off and don't want to have to carry forward with an extraordinary number of migrations.

A: You shouldn't be deleting migrations.  Why create the extra work?
Migrations essentially are a set of instructions that define how to build the database to support your application.  As you build your application the migrations record the iterative changes you make to the database.
IMHO by resetting the baseline periodically you are making changes that have the potential to introduce bugs/issues with your application, creating extra work.
In the case where a column is mistakenly added and then needs to be removed sometime later, just create a new migration to remove extra column.  My main reason for this is that when working in a team you don't want your colleagues to have to keep rebuilding their databases from scratch.  With this simple approach you (and they) can carry on working in an iterative manner.
As an aside - when building a new database from scratch (without any data) migrations tend to run very quickly.  A project I am currently working on has 177 migrations, this causes no problems when building a new database.


text:
Q: Using Construct Points on all lines in shapefile using ArcPy? I need to use the editing tool 'Construct Points' on several shapefiles that each have ~1300 polylines. I need to do this to create points every 1km along each of the polylines, which represent the orbits of a satellite. I've tried several other methods such as densify but none of them solve my problem as well as 'Construct Points'. The only problem is that you can only edit one line at a time, which would obviously take too long to do manually.
So I'm wondering, is there a way to implement 'Construct Points' in python so that it loops through all polylines and applies the tool with the same parameters?
I feel like it should be possible, but I've never used editing tools in arcpy so I'm not sure.
The output of 'construct points' is a point shapefile for the points that were constructed along the line used as an input. I'm wondering if I could do it in python such that it constructs the points on the line, then appends the output points to a larger point shapefile.
The following is pseudo code of what I have in mind, although the syntax is of course not correct. If anyone could shed any light, that would be great. I really would like to know if this is even possible with arcpy before I spend time trying to pursue it.
# using just one shapefile as an example (pseudo code, incorrect syntax):

orbitshapefile = (shapefile with ~1300 polylines)
pointshapefile = (empty shapefile to store points)

StartEdit(orbitshapefile) # open editing on the shapefile
for orbitline in orbitshapefile:
    editor.ConstructPoints(orbitline, 1km, ..(other parameters).., outputpoints) # call editing function
    pointshapefile.append(outputpoints) # append output points to 'big' shapefile

I just did construct points manually on just 2 lines in editor and found that using the same point shapefile on the second line that was used with the first adds those points to that shapefile, doesn't overwrite them. However, I need an indication of which line these points came from. There is an 'Id' attribute in the resulting table,  but everything is 0. Would there be a way to carry over the line's FID to all the points that came from it (alt. I could do a separate script after that uses intersect b/w line and points to come up with a lineID attribute). An updated version of the above code:
for orbitline in orbitshapefile:
    lineID = orbitline.FID
    editor.ConstructPoints(orbitline, 1km, ..(other parameters).., outputpoints)
    outputpoints[pts that were just created in this iteration].SetAttribute(lineIDField = lineID)

Some additional thoughts: I'm not sure how to subset the points that were just created-- maybe I could subset by saying something like: points in outputpoints s.t. lineID == 0 (because all points that were created in previous iterations will have their lineID attribute set to something other than 0)
Any thoughts on this rationale?
Can anyone AT LEAST tell me if using an editor tool iteratively in python is even possible?

A: I made a custom Create Points on Lines Toolbox you can download here:
Create Points on Lines Toolbox
View the Source Code
The tool creates points on lines at a specified distance, interval, or percentage value. The value can be fixed or field based. There is also an option to add the starting point, end point, or both to the output Point feature class.
You can also choose a Starting Location. So, if you want a point created 10 feet from the end of the line, change the Starting Location parameter to END.
The output Point feature class contains a field called LineOID, which is the OID of the line the point was created from. This allows data to be joined back to the point. There is also a field called Value, which contains the value that was used to create the point.
Here's a screenshot of the parameters:

A: If I am not totally wrong, a new Tool has been integrated in the Data Management Toolbox which exactly does what you were asking about:
http://desktop.arcgis.com/en/arcmap/latest/tools/data-management-toolbox/generate-points-along-lines.htm


text:
Q: Compactness in Sobolev spaces I was wondering whether the set $\lbrace f\in H_0^1(\Omega)|\|f\|_{L^\infty(\Omega)}\leq 1\rbrace$ is compact in $H_0^1(\Omega)$ or not. Here $\Omega$ is a convex domain in $\mathbb{R}^3$ with Lipschitz boundary.
Thanks.

A: No.  As a general rule, in order to obtain compactness in some norm, one needs control of a higher regularity than what is associated to that norm, in order to shut down an "escape to frequency infinity".  For instance, $H^1_0$ has one degree of regularity, so one needs to control a norm involving more than one derivative in order to obtain compactness.  (But in many cases one only needs an epsilon more regularity; for instance, Arzela-Ascoli tells us that equicontinuity, which can be thought of as an infinitesimal amount of regularity, is enough (together with some additional hypotheses) to obtain compactness in the uniform norm, which has zero degrees of regularity.)
In this specific case, a concrete counterexample can be obtained by considering the unit cube $\Omega = [0,1]^3$ and the sequence $f_n := \frac{1}{n} \sin(2\pi n x) \sin(2\pi y) \sin(2\pi z)$, which  goes to zero in $L^\infty$ but stays away from zero in $H^1_0$, and so cannot have any $H^1_0$ convergent subsequence.


text:
Q: Google sign up pop-up does not appear for choosing accounts I have made a google sign up button using the link
However, on execution, the pop-up window that usually appears for choosing a google account does not appear.
I have added an onClick option on the google sign-in button and used the function googleSignUp().
Below, I have put code I have used
package com.example.testapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

    MediaPlayer mp;
    int index = R.drawable.picture1_1;

    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .build();
    private static final int RC_SIGN_IN = 007;

    FirebaseAuth mAuth;

    @Override
    public void onStart() {
        super.onStart();
        // Check if user is signed in (non-null) and update UI accordingly.
        FirebaseUser currentUser = mAuth.getCurrentUser();
        updateUI(currentUser);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//will hide the title
        getSupportActionBar().hide(); //hide the title bar
        setContentView(R.layout.activity_main);

        mAuth = FirebaseAuth.getInstance();

        SignInButton signInButton = findViewById(R.id.sign_in_button);
        signInButton.setSize(SignInButton.SIZE_STANDARD);

        final ImageView imageView = findViewById(R.id.imageView);

        mp = MediaPlayer.create(this, R.raw.click);

        final int resId[] = {R.drawable.picture1_1, R.drawable.picture1_2, R.drawable.picture2_1, R.drawable.picture2_2, R.drawable.picture3_1, R.drawable.picture3_2, R.drawable.picture4_1, R.drawable.picture4_2, R.drawable.picture5_1, R.drawable.picture5_2, R.drawable.picture6_1, R.drawable.picture6_2, R.drawable.picture7_1, R.drawable.picture7_2, R.drawable.picture8_1, R.drawable.picture8_2, R.drawable.picture9_1, R.drawable.picture9_2, R.drawable.picture10_1, R.drawable.picture10_2};

        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Random rand = new Random();
                        index = rand.nextInt((resId.length- 1)  + 1);

                        imageView.setImageResource(resId[index]);
                    }
                });
            }
        }, 300000, 300000);

    }
    public void Clicked(View view){
        Toast.makeText(this,"Hello User",Toast.LENGTH_SHORT).show();
        mp.start();
    }

    public void googleSignUp(View view) {

        GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
        Intent signInIntent = mGoogleSignInClient.getSignInIntent();
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
        if (requestCode == RC_SIGN_IN) {
            // The Task returned from this call is always completed, no need to attach
            // a listener.
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            handleSignInResult(task);
        }
    }

    private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
        try {
            GoogleSignInAccount account = completedTask.getResult(ApiException.class);

            // Signed in successfully, show authenticated UI.
            updateGUI(account);
        } catch (ApiException e) {
            // The ApiException status code indicates the detailed failure reason.
            // Please refer to the GoogleSignInStatusCodes class reference for more information.
            Log.w("null", "signInResult:failed code=" + e.getStatusCode());
            updateGUI(null);
        }
    }

    private void updateGUI(Object o) {
        Toast.makeText(this,"SignUP by google Successful?",Toast.LENGTH_SHORT).show();
    }

    private void updateUI(FirebaseUser account) {
        if(account==null)
            Toast.makeText(this,"NULL",Toast.LENGTH_SHORT).show();
        else
            Toast.makeText(this,"SignUP Successful?",Toast.LENGTH_SHORT).show();

    }
}

I am getting no errors but the code does not give the desired result.

A: In the official documentation example:
https://github.com/firebase/quickstart-android/blob/8262596a009b50b6c99191001f7e5470391bcc4a/auth/app/src/main/java/com/google/firebase/quickstart/auth/java/GoogleSignInActivity.java#L71-L75
The code that declares and configures the GoogleSignInOptions is in the onCreate() method rather than in the class like your example shows. Perhaps instead of
public class MainActivity extends AppCompatActivity {
    // you declared it here

    public void onCreate() {
        // rather than here
    }
}

try putting it in the onCreate method
public class MainActivity extends AppCompatActivity {
    public void onCreate() {
        // declare and build it here

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .build();
    }
}


text:
Q: HTML Content to Right of Google Map I'm trying to add a menu to my Javascript program that will allow a user to do a variety of different things. I'm not much of an HTML guru so I don't know how to keep the menu at the top and right of the page. I tried using a div, but it just put it under the map instead of right of it. Here's a screenshot of what it looks like in the browser:

The whitespace on the right is where I would like to put the menu. Can anyone provide an example of how I would put a table there? Here's how the body of my HTML is now:

A: To get two DIV's side by side (touching), I usually set both to float:left. Something like this:

If you specify float:right on the second div, it will "stick" to the right side of the browser window instead of to the div next to it.

A:

A div would be a better solution here than a table...try the above and let me know how you make out.
The float:right will stick the menu to the right side of the screen. I always set my total width to be slightly less than 100% -- this way, when you inevitably add padding/margins, you'll have a bit of wiggle room.


text:
Q: push associative array error? I have to push elements in an associative array from another array after some processing and I'm doing something  this:
for(var i in this.aNames) {
    var a = this.aNames[i];
    // some processing on a
    aList[i] = a;
    aList.push(i);
}

But it's not giving me the proper array.
EDIT :
Here aNames is an associative array like this
'1232':'asdasdasd',
'6578':'dasdasdas'
...... and so on of about 100 elements.

I'm using for here as I want to do some changes in every element of the array.
Then I'm displaying the result array on the page but it's showing the key value together with the array data.
I.e. it should only display asdasdasd or asdasdasd but it's displaying keys too, like 1232 asdasdasd 6578 dasdasdas.

A: There are multiple things which may go wrong...
Primarily, make sure that this is pointing to the correct context and that this.aNames is actually returning a complex object (associative array).
Also, what's aList?  Is it an array?  If it is, push should append your array with the key of the current member (the member's name).
If you want to append the values of the members on your source object, you need to do something like this:
var obj = {name: 'dreas'},
    arr = []; // arr is an array

arr.push(obj["name"]); // arr now contains a single element, 'dreas'

In your for..in construct, you are both adding elements to an alleged array (aList) with push but also creating new members on your array (with the subscript notation, aList[i] = "asd" since i in this case (for..in iteration) refers to the member's name).
So, what you need to do is decide if you want to add elements to an array or members to an object, not both.
If you just want to clone an array, use a for loop.  If on the other hand you want to clone an object, it's not that trivial because members can also be complex objects containing their own members, and simply doing arr[i] = obj.member will only copy a pointer to arr[i] if member is a complext object, not a value type.

Just to make sure my terminology is understandable:
var anObject = {name: "dreas"},
    anArray = [1,2,3];

    anObject["name"] <= member (results in "dreas")
    anArray[1]       <= element (results in 2)


text:
Q: Make a view highlightable in a linearlayout I wish to make views highlighted like items in a listview(I use linearlayout instead because listview cannot use addchild() to dynamically add new items)
When a listview item is touched,the item is usually highlight green.How do I implement this feature into views in a linearlayout?
I tried view.requestfocus in the view's ontouchlistener.this returns true but nothing can be observed.
Thanks in advance!

A: You can add items to a listview dynamically....
public class MainActivity extends ListActivity {

/** Items entered by the user is stored in this ArrayList variable */
ArrayList<String> list = new ArrayList<String>();

/** Declaring an ArrayAdapter to set items to ListView */
ArrayAdapter<String> adapter;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    /** Setting a custom layout for the list activity */
    setContentView(R.layout.main);

    /** Reference to the button of the layout main.xml */
    Button btn = (Button) findViewById(R.id.btnAdd);

    /** Defining the ArrayAdapter to set items to ListView */
    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);

    /** Defining a click event listener for the button "Add" */
    OnClickListener listener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            EditText edit = (EditText) findViewById(R.id.txtItem);
            list.add(edit.getText().toString());
            edit.setText("");
            adapter.notifyDataSetChanged();
        }
    };

    /** Setting the event listener for the add button */
    btn.setOnClickListener(listener);

    /** Setting the adapter to the ListView */
    setListAdapter(adapter);
}

}


text:
Q: stream audio via UDP by using CocoaAsyncSocket in swift I have a problem to send audio by CocoaAsyncSocket via UDP in swift.
First of all I run below code to start listening 4444 UDP port.
vlc --demux=rawaud --rawaud-channels=1 --rawaud-samplerate=48000 udp://@:4444

after that I run my application in iPad2 and press connect.
import UIKit
import CocoaAsyncSocket
import AVFoundation
class ViewController: UIViewController , GCDAsyncUdpSocketDelegate {

var avAudioEngine : AVAudioEngine?

@IBAction func btnAction(sender: UIButton) {

    avAudioEngine = AVAudioEngine()
    let input = avAudioEngine?.inputNode

    let socket = GCDAsyncUdpSocket(delegate: self, delegateQueue: dispatch_get_main_queue())
    do {
        try socket.bindToPort(4445)
        try socket.connectToHost("192.168.0.137",onPort : 4444)
        try socket.beginReceiving()

        input?.installTapOnBus(0, bufferSize: 2048, format: input?.inputFormatForBus(0), block: { (buffer : AVAudioPCMBuffer, timeE: AVAudioTime) -> Void in
            socket.sendData(self.toNSData(buffer), withTimeout: 0, tag: 0)
        })

        avAudioEngine?.prepare()
        try avAudioEngine?.start()

        // with nc -l -u -p 4444 and uncomment below block I can get "someText"
       //socket.sendData("someText\n".dataUsingEncoding(NSUTF8StringEncoding), withTimeout: 0, tag: 0)
       // socket.close()

    }

    catch{
        print("err")
    }

}

    //socket.sendData just accepts NSData, So I think that we must convert it to NSData!

func toNSData(PCMBuffer: AVAudioPCMBuffer) -> NSData {
    let channelCount = 1  // given PCMBuffer channel count is 1
    let channels = UnsafeBufferPointer(start: PCMBuffer.floatChannelData, count: channelCount)
    let ch0Data = NSData(bytes: channels[0], length:Int(PCMBuffer.frameCapacity * PCMBuffer.format.streamDescription.memory.mBytesPerFrame))
    return ch0Data
}

Any Idea?


text:
Q: How can i detect amplitude from FFT on Time-Domain signal I have a signal of wave song and I have a problem with amplitudes.
%graph 1 time domain
song2 = song(1:size(song));
fs = 44100;
dt = 1/fs;
t = 0:dt:(length(song2)*dt)-dt;
figure();
plot(t,abs(song2)); xlabel('Seconds'); ylabel('Amplitude');

Then I put signal in FFT, because I want to get amplitude of detecting peaks(for example; 164Hz).
%graph 2 fft
L = length(song2);
NFFT = 2^nextpow2(L);
f = fs/2*linspace(0,1,NFFT/2+1);
X = fft(song2,NFFT)/L;
X = 2*abs(X(1:NFFT/2+1));
figure();
plot(f,X);

The problem appear when I get the amplitude of the signal (for example; 0.0103) but if I compare with the amplitude of the (time domain) is not the same.
My question is How in the time domain(graph 1) I detect amplitude of the of a frequency(for example; 164 with amplitude 0.0103)?
EDIT:
Hm, I will rather ask in this way. I detect frequency in frequency domain spectrum as the graph link
For example Let us take the the first signal (82hz)(amplitude:0.0075) And my question if is posible to detect position of this first signal in time-domain as the graph in link
Any help would be helpful.

A: Have you tried the code with a sinusoidal input?
Make a sinusoid of length 512 (any reasonable length) with amplitude 1 and frequency equal to 164 Hz.
When you run the program, I'm sure you'll see the gain at the frequency bin corresponding to 164 Hz close to one, as long as your frequency resolution isn't too bad (meaning you haven't used too few FFT points).
If the above works, then your code should work for a song too. How you're judging/verifying time-domain amplitude in the case of a multi-tonal time domain signal like music is something I don't know.

A: If I understand your question correctly, you can find what you want by taking the inner product of the time domain signal with a complex sinusoid at the frequency of interest. For example, using the information from your post we would something like the following:
% graph 1 time domain
song2 = song(1:size(song));
fs = 44100;
dt = 1/fs;
t = 0:dt:(length(song2)*dt)-dt;
x_164 = exp(-1j * 2*pi * 164 * t);
f_164 = x_164(:).' * song2(:);       % Spectral content of the signal at 164(Hz).

If you think about what a DFT is, you'll see it's just the above process but with the frequencies chosen such that they from an orthogonal basis. However, you can use the same process to estimate the spectral content at any frequency you want.


text:
Q: Softmax + CE vs Sigmoid + BCE for batched training with negative sampling, for training similarity properties This is a follow up to this question
Machine Learning: Should I use a categorical cross entropy or binary cross entropy loss for binary predictions?
I am training cos similarity properties for question and answers, and I am wondering what are the advantages and disadvantages to using softmax + CE vs sigmoid +BCE.
Say that in a batch, I have the following questions and answers, each represented by a vector
Questions:
What's in the sky?
What appears at night?
What's hot?
Answers:
Moon
Sun
Fire
Correct Combinations:
What's in the sky? Moon, Sun
What appears at night? Moon
What's hot? Fire, Sun.
In this batch, 'Moon' and 'Sun' are both answers to 'What's in the sky?', so the cos similarity of the question vector to the answer vectors should be trained equal to 1. But 'Fire' is not an answer to that question, so the cos similarity should be trained to equal to 0.
There are two approaches for this, one using sigmoid + BCE, another using softmax + CE.
Sigmoid + BCE:
After taking the dot products of all combinations, pass them through a sigmoid, and doing binary cross entropy loss with the correct label , 0 or 1.
For example:
partialLoss1 = 1 * Log ( Sigmoid( DotProduct( Vector{What's in the sky}, Vector{Moon} ) ) )
partialLoss2 = 0 * Log ( Sigmoid( DotProduct( Vector{What's in the sky}, Vector{Fire} ) ) )
and do this for all the combinations of questions and answers.
Softmax + CE:
In this approach, a softmax is taken over each question and their answers combinations. For questions that have two correct answers, the softmax output should be .5 for each of correct answers.
If doing the softmax over all possible dot products of answers for 'What's in the sky?', the softmax probabilities should be .5 for 'Moon' , .5 for 'Sky', and 0 for 'Fire'.
And this the loss for the output labels and the softmax probabilities can be calculated with regular cross entropy.
For example:
partialLoss1 = .5*Log( SoftmaxProbability{  Vector{What's in the sky}, Vector{Moon} } )
partialLoss2 = .5*Log( SoftmaxProbability{  Vector{What's in the sky}, Vector{Sun} } )
partialLoss3 = 0*Log( SoftmaxProbability{  Vector{What's in the sky}, Vector{Fire} } )
Are both these approaches correct? If so, what are the advantages and disadvantages to each one?


text:
Q: Element is already the child of another element I get the folowing error in my Silverlight application. But i cant figure out what control it is that is the problem. If i debug it don't break on anything in the code, it just fails in this framework callstack with only framework code. Is there any way to get more information on what part of a Silverlight app that is the problem in this case.

Message: Sys.InvalidOperationException: ManagedRuntimeError error #4004 in control    'Xaml1': System.InvalidOperationException: Element is already the child of another element.
at MS.Internal.XcpImports.CheckHResult(UInt32 hr)
at MS.Internal.XcpImports.Collection_AddValue[T](PresentationFrameworkCollection`1 collection, CValue value)
at MS.Internal.XcpImports.Collection_AddDependencyObject[T](PresentationFrameworkCollection`1 collection, DependencyObject value)
at System.Windows.PresentationFrameworkCollection`1.AddDependencyObject(DependencyObject value)
at System.Windows.Controls.UIElementCollection.AddInternal(UIElement value)
at System.Windows.PresentationFrameworkCollection`1.Add(T value)
at System.Windows.Controls.AutoCompleteBox.OnApplyTemplate()
at System.Windows.FrameworkElement.OnApplyTemplate(IntPtr nativeTarget)

The XAML for the AutoCompeletBox that is in the context is:
<tk:AutoCompleteBox
    x:Name="acName"
    Grid.Row="0"
    Grid.Column="1"
    LostFocus="acName_LostFocus"
    Height="20"
    Width="80"
    HorizontalAlignment="Left"/>

A: The error is a generic catch-all exception that has many many causes.  I've written a debugger utility that can help to identify which part of the XAML is actually causing the error.  You can download it from my blog: http://whydoidoit.com/2010/08/30/debug-xaml-element-is-already-the-child-of-another-element/

A: Your items may be visual elements, instead of data objects.
If you provide the XAML, I can help make sure that is the case.

A: Usually this error occurs when the said Element is already attached to an existing Parent and somewhere in your code you're attempting to re-parent it (ie via just straight "add" when you in turn must remove the child from the parent first, then Add it to the children etc).
Where specifically the control is failing the above isn't enough info to digest.

A: Simple and stupid solution:
public class AutoCompleteTextBox : AutoCompleteBox
    {
        public override void OnApplyTemplate()
        {
            try
            {
                base.OnApplyTemplate();
            }
            catch { }
        }
    }


text:
Q: Firebase onDisconnect taking too much time to update realtime database when user suddenly lost network I am working on making a chat app using firebase, where I need to know instantly that user is online or offline. But when user lost his network suddenly then onDisconnect method comes in the picture. But it is taking too much time to update realtime database.
Here is my Code. Please share better solution to this problem.
        DatabaseReference infoConnected = FirebaseDatabase.getInstance().getReference(".info/connected");
        final DatabaseReference UpdateRef = FirebaseDatabase.getInstance().getReference("/Status/"+mAuth.getUid());
        infoConnected.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                boolean isCon = dataSnapshot.getValue(Boolean.class);
                if(isCon)
                {
                   DatabaseReference reference = UpdateRef.child("Status");
                   reference.setValue("Online");

                   reference.onDisconnect().setValue("Offline");

                }
            }

Thanks in advance.


text:
Q: Nginx cache, redis_pass I have been banging my head against a wall all day.
I am using the following nginx configuration to test something
location  /help {
  set $redis_key "cache:$scheme://$host$request_uri";
  default_type   text/html;
  redis_pass 127.0.0.1:6379;
  error_page 404 = @upstream;

}
There is a key and value inside my redis instance for the cache:$scheme.... (in my case cache:http://localhost/help)
I know they exist because I can monitor redis-cli for the nginx redis request, copy the "get" "cache:http://localhost/help", paste it into another redis-cli window and get the expected response.
The problem comes with nginx, it's not getting the response. Again I can see it connect from inside redis-cli -> monitor and I know the key and value exist.
From the nginx error log I can see this
2016/04/08 16:52:42 [notice] 9304#0: worker process 6328 exited with  code 0
2016/04/08 16:52:42 [notice] 9304#0: signal 29 (SIGIO) received
terminate called after throwing an instance of 'std::length_error'
  what():  basic_string::append
2016/04/08 16:52:49 [notice] 9304#0: signal 17 (SIGCHLD) received
2016/04/08 16:52:49 [alert] 9304#0: worker process 7328 exited on signal 6 (core dumped)
2016/04/08 16:52:49 [notice] 9304#0: start worker process 7516
2016/04/08 16:52:49 [notice] 9304#0: signal 29 (SIGIO) received
terminate called after throwing an instance of 'std::length_error'
  what():  basic_string::append
2016/04/08 16:52:50 [notice] 9304#0: signal 17 (SIGCHLD) received
2016/04/08 16:52:50 [alert] 9304#0: worker process 7335 exited on signal 6 (core dumped)
2016/04/08 16:52:50 [notice] 9304#0: start worker process 7544
2016/04/08 16:52:50 [notice] 9304#0: signal 29 (SIGIO) received
terminate called after throwing an instance of 'std::length_error'
  what():  basic_string::append

Has this appened to anyone else or can someone kick me in the right direction?
Thanks in advance

A: For anyone reading this in the future.
Firstly, Hello from the past!
Secondly, turns out nginx pagespeed module and this kind of caching are incompatible.


text:
Q: Interpreting over/underdispersion of data with Poisson GLM in R I have count data that I have fit a GLM to using the Poisson distribution and the default log link function.
I have run a couple tests for over/under dispersion:

*

*Dividing the residual deviance by its degrees-of-freedom returns 1.41. Since this is greater than one, it indicates my data is over-dispersed. However, I do remember reading that over-dispersion is not to be of concern if this ratio is less than 1.5.

*I have seen another source use

pchisq(residual deviance, df, lower.tail =
    FALSE)

test, which returned a non-significant p-value for my data (indicating a lack of evidence against equidispersion)
3. I also ran the dispersiontest function in the AER R package which returned a non-significant result, also indicating a lack of evidence against equidispersion.
So, it seems my model is fine in terms of dispersion ...?
Fitting a Quasipoisson GLM in R returns an estimated dispersion parameter of approximately 1.40 (interestingly enough this is very similar to my estimation in Point 1). However, I thought a Quasipoisson GLM is supposed to fix any dispersion issues. How exactly should I interpret this - is it also indicating over-dispersion?
Is implementing a Quasipoisson model here over-kill; should I just keep my Poisson model?


text:
Q: Find the domain, $x$ intercepts, $y$ intercepts Let $f(x)=\dfrac{x^2+1}{x^2-9}$
So to find the $y$ intercept I take $f(0)$ correct? So when I substitute $0$ for $x$ I got $-\frac{1}{9}$ so is the $y$ intercept $(0,-\frac{1}{9})$
Also to find the $x$ intercept I set the numerator equal to $0$. So then I got $x^2+1=0$ but wouldn't that make $x^2=-1$ which is imaginary? I'm a little confused what I am doing wrong..

A: Yes your $y$-intercept is correct, and you are correct that the only solution is where $x^2=-1$ which would mean there are no real solutions, only imaginary solutions. So you would simply say that you're function has no $x$-intercept!

A: Yes. This is correct. To find the $y$ intercept of a function, $f(x)$, find $f(0)$.
Your approach for the $x$ intercept is also correct. Assuming that you are only trying to find intercepts in the real numbers, taking $x^2+1=0$ means that there are no $x$ intercepts.
You calculated your derivative incorrectly. The derivative of $f(x)$ is given by: $$\frac{df}{dx}=\frac{(x^2-9)(2x)-(x^2+1)(2x)}{(x^2-9)^2}=\frac{-20x}{(x^2-9)^2}$$
Setting $\frac {df}{dx}=0$ yields $0=-20x$. However, you must also consider the points at which the derivative is undefined. To do this, solve $0=x^2-9$. Finally, consider where $\frac {df}{dx}$ is positive and negative using various values.

A: What you have done so far is exactly right. In some sense you could say it is a trick question.
If you plot the function you'll find there is no $x$-intercept. The fact that $x^2+1$ has no roots in $\mathbb{R}$ tells you exactly that.

A: You are correct about the $y$-intercept, though the terminology is a little ambiguous. It can mean the intersection point on the $y$-axis with the graph of the function, in which case it is $(0,-1/9)$ as you said. It can also mean just the $y$-coordinate of that point, which is $-1/9$.
Your reasoning about the $x$-intercepts is also basically correct. You have shown that there is no $x$-intercept. That happens for many functions, so don't worry about this function being an exception. A function may have no $x$-intercept, one, two, many, countable infinitely many, uncountable infinitely many.
A function can have only one or no $y$-intercepts, however, due to the definition of a function.


text:
Q: Visual Studio, Sync namespaces except particular files I really like new productivity tool Sync namespaces in Visual Studio 2022 but sometimes there are rare cases when I need to exclude some file or folder when I synchronize namespaces.
Example 1
By convention, DI extensions should be created in the Microsoft.Extensions.DependencyInjection namespace. From the ASP.NET Core Guide :

We recommended that apps follow the naming convention of creating extension methods in the Microsoft.Extensions.DependencyInjection namespace. Creating extension methods in the Microsoft.Extensions.DependencyInjection namespace:

*

*Encapsulates groups of service registrations.

*Provides convenient IntelliSense access to the service.

Example 2
I have .NET Standard 2.0 project where I want to use constructor-based record declaration and according to this solution Testing C# 9.0 in VS2019 - CS0518 IsExternalInit is not defined or imported ... How do I define/import it? I'm adding the following file to my project:
namespace System.Runtime.CompilerServices;

internal static class IsExternalInit { }

Obviously after doing 'Sync namespaces' this file will be changed and the trick will not work.

A: Found this issue since I have the same problem with Extensions.DependencyInjection.
I would like to mention something that may help you with the external init in that case: There is a nuget package for that internal init: https://www.nuget.org/packages/IsExternalInit.
Hope that at least helps you with that problem.

A: You said .NET Standard 2.0 project but not confirmed that its CORE or Framework?
VS2022 and its successor will support mainly CORE version preferably. I don't know why but trying to be universal is the primary goal of Microsoft.
Instead creating parallel world they modifying its own.
Try to install / Add framework minimum 4.8.xx else go back to old visual studio IDE.


text:
Q: Users with high reputation on several Stack Exchange network sites It's easy to track down the users with most reputation on a particular network site. I am much more interested in those universal geniuses who have earned a lot of reputation on many different sites. Is there a way to ask the Stack Exchange Data Explorer about, say, people with more than 5k reputation on at least two sites?

A: I have created a query to find your definition of universal geniuses, which is available here.
The query basically loops through all available databases (excluding meta sites where user reputation is the same as on its corresponding site) and picks users with more than n reputation (default 5000) on at least n different sites (default 2).
It reveals that by your definition, Gilles is currently the "most universal genius", as s/he has more than 5000 reputation on the 11 different sites: Unix:211723, Meta:50246, StackOverflow:37746, SuperUser:30930, French:26017, Ubuntu:22065, Scifi:19700, Security:17464, Cs:14029, Travel:8984, ServerFault:6149.
Query:
-- Select all valid databases.
select dbid, name
into #dbs
from master..sysdatabases
where name not in ('Data.StackExchange', 'master', 'model', 'msdb', 'tempdb')
  and right(name, 5) <> '.Meta'
   or name = 'StackExchange.Meta'

-- Loop through databases to find all users with high enough reputation.
create table #topusers (
  accountid int,
  userid int,
  rep int,
  site varchar(40)
)
declare @id int, @db varchar(40), @sql varchar(max)
while (select count(*) from #dbs) > 0
begin
  select top 1 @id = dbid, @db = name from #dbs
  set @sql = '
    insert into #topusers
    select AccountId, Id, Reputation, ''' + @db + '''
    from [' + @db + ']..[Users]
    where Reputation > ' + cast(##MinReputation:int?5000## as varchar(max))
  exec (@sql)
  delete from #dbs where dbid = @id
end

-- Summarize the results nice and clean.
select
  'https://stackexchange.com/users/' + cast(accountid as varchar(15))
    + '|' + cast(accountid as varchar(15)) as [Account Link],
  count(accountid) as [Site count],
  stuff (
    (select ', ' +
     case when left(site, 14) = 'stackexchange.'
       then substring(site, 15, len(site))
       else site
     end + ':' + cast(rep as varchar(max))
       from #topusers
       where (accountid = u.accountid)
       order by rep desc
       for xml path(''),type
       ).value('(./text())[1]','varchar(max)')
    ,1,2,'') as [Site:rep]
from #topusers u
group by accountid having count(accountid) >= ##OnMinSites:int?2##
order by count(accountid) desc


text:
Q: Questions on the Related/Linked Sidebar do not indicate if an accepted answer exists
From here, notice how the sidebars for these three sites are a tad different, notably, Math.SE.  I'm not sure if it's just me, but Math.SE clearly shows whether or not a question has been accepted or not in the sidebar.
I decided to have a gander at the other sites, because I wasn't sure if it was just a bug that wasn't properly affecting Arqade or StackOverflow. These are the sites I noticed don't have the questions in the sidebar properly "marked":

Linked sidebar:

*

*Arqade

*Stack Overflow

*English.SE

*TravelAnswers

*Drupal

*Mi Yodeya
Related sidebar:

*

*Arqade

*Stack Overflow

*English.SE

*TravelAnswers

*Drupal

*Mi Yodeya

Sites that do reflect if questions are answered or not (in sidebar):

*

*Math.SE

*Programmers

I'll update this list as I find more, but can this be fixed?

A: Stack Overflow (and the other sites that don't have the questions with accepted answers marked) are just missing a bit of CSS that the other sites have:
.answered-accepted {
    background-color: #D2EAC1 !important;
}

Or, if you're a purist who is offended by the use of !important:
.show-votes .sidebar-related .answered-accepted {
    background-color: #D2EAC1;
}

All of the plumbing is already there in the generated HTML, there's just no styles provided to differentiate it for display purposes.
Presumably, this feature was introduced with the new custom-designed themes for the Stack Exchange 2.0 sites, but never got back-ported to Stack Overflow's crusty old design.


text:
Q: How to swap minus sign from last position in a string to first position in hive? How to swap negative sign from last position to first in a string  or integer to first position in hive and/ spark?
example:  22-
required:  -22
My code is:
val Validation1 = spark.sql("Select case when substr(YTTLSVAL-,-1,1)='-' then cast(concat('-',substr(YTTLSVAL-,1,length(YTTLSVAL-)-1)) as int) else cast(YTTLSVAL- as int) end as column_name")

A: scala> Seq("-abcd", "def", "23-", "we").toDF("value").createOrReplaceTempView("values")
scala> val f = (x: String) => if(x.endsWith("-")) s"-${x.dropRight(1)}" else x
scala> spark.udf.register("myudf", f)
scala> spark.sql("select *, myudf(*) as custval from values").show
+-----+-------+
|value|custval|
+-----+-------+
|-abcd|  -abcd|
|  def|    def|
|  23-|    -23|
|   we|     we|
+-----+-------+

EDIT
On second thought, since, UDF's are discouraged unless you absolutely need them (since they create a black box for spark's optimisation engine), please use below way that uses regex_replace instead. Have tested this and it works:
scala> spark.sql("select REGEXP_REPLACE ( value, '^(\\.+)(-)$','-$1') as custval from values").show

A: You could try REGEXP_REPLACE. This patter searches for a number followed by - at the end and puts it before the number if found.
SELECT REGEXP_REPLACE ( val, '^(\\d+)-$','-$1')

Column functions


text:
Q: Updating knockout variable value I have the below model
var CountryScopeVM = function (data, root) {
    CountryScopeVM.call(this, data);
    var self = this;
    this.isSelected = ko.observable();
    this.centralImpLowHeadCount = ko.observable();
    this.load(data);
    }
};
 this.countryScopes = ko.observableList(CountryScopeVM, data.countryScopes, this);

And I have the below code which gets called when a checkbox is selected. What I am trying to do here is have all the  centralImpLowHeadCount inside the countryscope array get updated when the main checkbox is checked but it is not updating and I don't see the change in the UI.
 selectAllLOWImplementation: function (data, event) {
        var select = $(event.target).is(':checked');
        ko.utils.arrayForEach(model.countryScopes() || [], function (countryScope) {
            countryScope().centralImpLowHeadCount == select;
        });
        return true;
    }

HTML
 <input type="checkbox" data-bind="checked: hasSelectedLOWImplementation, click: selectAllLOWImplementation" />

 <input type="checkbox" data-bind="checked: centralImpLowHeadCount, enable: isOn"  />


text:
Q: Terraform local_file inconsistent final plan I am using local_file to generate ansible inventory from template like this:
ansible.hosts
[workers]
%{ for worker in workers ~}
${worker.name} ansible_host=${worker.private_ip} ansible_user=${ssh_user}
%{ endfor ~}

Resource definition
resource "local_file" "ansible_inventory" {
  count = 1

  filename ="${path.cwd}/ansible.hosts"
  content  = templatefile(
    "${path.module}/templates/ansible/ansible.hosts", {
      workers               = var.workers
    })
}

When I resize infrastructure one worker is removed , than I apply and terraform crashes with:
log
When expanding the plan for module.provisioner.local_file.ansible_inventory[0]
to include new values learned so far during apply, provider
"registry.terraform.io/-/local" produced an invalid new value for .content:

was cty.StringVal("[workers]\n
shswarm-worker-0-saving-wombat ansible_host=*.*.*.1 ansible_user=centos\n\n
shswarm-gpu-worker-0-superb-sculpin ansible_host=*.*.*.2 ansible_user=centos"),

but now cty.StringVal("[workers]\n
shswarm-worker-0-saving-wombat ansible_host=*.*.*.1 ansible_user=centos")

This is a bug in the provider, which should be reported in the provider's own
issue tracker.

After terraform plan file content is changed because one worker node is removed.
Is there any way to fix that ?
I commented on related github issue:
https://github.com/hashicorp/terraform-provider-local/issues/79


text:
Q: How to create pagination with numbers? I have this code where i display posts from one category, but i want to add pagination with number. Any suggestion how can i do that?
 <?php $args3 = array(
            'post_status' => array('publish'),
            'orderby' => 'date',
            'order' => 'DESC',
            'cat' => 1,
            'offset' => 4,
            'posts_per_page' => 4
            );
            query_posts($args3); ?>

                    <?php while ( have_posts($args2) ) : the_post(); ?>

<?php the_post_thumbnail('homeSlider'); ?>

<?php echo the_title(); ?>

<?php if(get_field("adresa")){ ?>
                                <?php echo get_field( "adresa" ); ?>,
                           <?php } ?>
                           <?php echo get_the_time(); ?>

<a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( '%s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><img src="<?php echo get_bloginfo('template_directory');?>/images/more2_icon.png?>" class="more_icon" />

                      <?php endwhile; ?>


text:
Q: Egulias\EmailValidator\EmailValidator does not exist, but exists egulias/email-validator/src/EmailValidator.php Laravel is trying to include this file Egulias\EmailValidator\EmailValidator, but this file doesn't exists Egulias\EmailValidator\EmailValidator. But exists egulias/email-validator/src/EmailValidator.php. How can i solve this Problem?
composer.json
"require": {
        "php": ">=7.1.3",
        "laravel/framework": "5.8.*",
         .........................
        "egulias/email-validator": "~2.0",
        "swiftmailer/swiftmailer": "^6.0",
         .........................
    },

Error
local.ERROR: Class Egulias\EmailValidator\EmailValidator does not exist {"userId":68,"exception":"[object] (ReflectionException(code: -1): Class Egulias\\EmailValidator\\EmailValidator does not exist at /var/www/projectTest/vendor/swiftmailer/swiftmailer/lib/classes/Swift/DependencyContainer.php:325)
[stacktrace]
#0 /var/www/projectTest/vendor/swiftmailer/swiftmailer/lib/classes/Swift/DependencyContainer.php(325): ReflectionClass->__construct('Egulias\\\\EmailVa...')
#1 /var/www/projectTest/vendor/swiftmailer/swiftmailer/lib/classes/Swift/DependencyContainer.php(339): Swift_DependencyContainer->createNewInstance('email.validator')
#2 /var/www/projectTest/vendor/swiftmailer/swiftmailer/lib/classes/Swift/DependencyContainer.php(115): Swift_DependencyContainer->createSharedInstance('email.validator')
#3 /var/www/projectTest/vendor/swiftmailer/swiftmailer/lib/classes/Swift/DependencyContainer.php(385): Swift_DependencyContainer->lookup('email.validator')
#4 /var/www/projectTest/vendor/swiftmailer/swiftmailer/lib/classes/Swift/DependencyContainer.php(362): Swift_DependencyContainer->lookupRecursive('email.validator')
#5 /var/www/projectTest/vendor/swiftmailer/swiftmailer/lib/classes/Swift/DependencyContainer.php(132): Swift_DependencyContainer->resolveArgs(Array)
#6 /var/www/projectTest/vendor/swiftmailer/swiftmailer/lib/classes/Swift/DependencyContainer.php(328): Swift_DependencyContainer->createDependenciesFor('mime.headerfact...')
#7 /var/www/projectTest/vendor/swiftmailer/swiftmailer/lib/classes/Swift/DependencyContainer.php(113): Swift_DependencyContainer->createNewInstance('mime.headerfact...')
#8 /var/www/projectTest/vendor/swiftmailer/swiftmailer/lib/classes/Swift/DependencyContainer.php(385): Swift_DependencyContainer->lookup('mime.headerfact...')
#9 /var/www/projectTest/vendor/swiftmailer/swiftmailer/lib/classes/Swift/DependencyContainer.php(362): Swift_DependencyContainer->lookupRecursive('mime.headerfact...')
#10 /var/www/projectTest/vendor/swiftmailer/swiftmailer/lib/classes/Swift/DependencyContainer.php(132): Swift_DependencyContainer->resolveArgs(Array)
#11 /var/www/projectTest/vendor/swiftmailer/swiftmailer/lib/classes/Swift/DependencyContainer.php(328): Swift_DependencyContainer->createDependenciesFor('mime.headerset') ```