text:
Q: Como adicionar um array dentro de um array? Estou criando uma aplicação em ReactJS que bate na API do GitHub e traz o user e os repositórios.
Mas eu queria trazer também os commits de cada repositório e não estou conseguindo.
Meu código é esse:
async handleSubmit(e) {
    e.preventDefault();

    let user = await this.getUser(this.refs.username.value);
    let repo = await this.getUserRepo(this.refs.username.value);

    for(let i = 0; i < repo.length;i++){
       let commitao = []
       var comitasso = []
       commitao = await this.getReposCommit(this.refs.username.value, repo[i].name);
       comitasso.push(commitao)
       console.log(commitao)

    }
    console.log(comitasso)
    this.setState({
      avatar_url: user.avatar_url,
      username: user.login,
      id: user.id,
      url: user.html_url,
      message: user.message,
      reponame: repo,

    });

O problema é que quando faço console.log(comitasso), ele me traz apenas o último registro.

A: O problema é que você esta definindo a variável comitasso dentro do for, a cada interação ele vai redefinir, apenas a ultima interação não será redefinida e por isso ela você é a unica que aparece no console, para solucionar basta definir a variável fora do for como mostrado abaixo:
var comitasso = [];      /// ; <- defina aqui por exemplo
for(let i = 0; i < repo.length;i++){
   let commitao = [];
   // var comitasso = [] /// ; <- comentado
   commitao = await this.getReposCommit(this.refs.username.value, repo[i].name);
   comitasso.push(commitao)
   console.log(commitao)

}

A: Uma maneira ainda mais eficiente de fazer esse loop seria enviar a requisição para buscar todos os commits primeiro, e então esperar a resolução deles simultaneamente, ao invés de enviar a requisição para buscar um commit de cada vez, e então esperar a resolução de cada um antes de buscar o próximo.
var promiseComitasso = repo.map(r => this.getReposCommit(this.refs.username.value, r.name))
var comitasso = await Promise.all(promiseComitasso)

Não há a necessidade de um for aqui pois a iteração do array é feita no map.


text:
Q: Python printing text: Highlight or mark some text in the string with indicators I want to print a string buffer (or byte array) which could contains some special characters, such as \t and \n, besides that, I need to print some indicators below the line to indicate some special part of the string, something like below:
a b c d \t , e f g \n
  ~~~~~~~~   ^^^^^

Here is the questions:
1, the escape char  and the normal char should be printed in a fixed width, but I see that repr() function can not.
2, some indicator below the first line should be printed.
3, if we still use repr() function, then I think the marker in the second line should be calculated dynamically, because repr() don't print texts in a fixed width format, thus a \t takes two chars.
Any one can help?
BTW: the whole idea is that I want to create a python pretty printer for GDB to show a token when debugging a parsing algorithm.
EDIT:
Here is an example:
print (repr("abcd\t,efg\n"))

when you run the code, you get a printed string which has 12 element instread of 10, for me, ff I want to hight the token "efg", which is the index 6,7,8 in the string, if I draw a markers in the second from the index 6,7,8, I get the following.
abcd\t,efg\n
      ~~~

Because the "\t" has two chars not the one, which means the function repr() don't print fixed witdh chars, in this case, I would like to see:
abcd\t,efg\n
       ~~~

redpajama_set_name: RedPajamaStackExchange


text:
Q: Office for Mac Excel app doesn't show thousand separator I'm using OS X Mountain Lion 10.8.2, with Microsoft Office 14.2.4.
Problem: Ever since I installed new updates of OS X, Excel can no longer display the thousands separator.
How can I get it back?

A: A temporary workaround is always simply Command-A to select all cells and clicking this convenient button in the ribbon under the Home tab in the Number section:

A more permanent solution is as follows:
Go into System Preferences > Language and Text and click the "Region" tab.  If the first region dropdown menu is United States (Computer), this might be your problem.  Looking below shows that this region formats numbers without a thousands separator.

This appears to be the result, as you stated, of an OS X update. Instead, set the Region to United States (without the Computer part).

From the Excel Help window:

Display or hide the thousands separator
Select the cells that you want to adjust. On the Home tab, under
Number, click Display the value of a cell with a thousands separator.
Note: Excel uses the Mac OS system separator for thousands. You can
specify a different system separator by changing the regional settings
in Mac OS X International system preferences.

We have just done that, but it appears that Excel continues to ignore the change.  Re-install Office and update us with the results.

A: Formatting palette
Number
Custom
Edit format of the prototype number (I removed the dollar sign, but kept the commas)
I have Mountain Lion and Excel 2008 for mac

A: Setting the System Region Setting from 'United States (Computer)' to 'United States' worked for me!
Running Mavericks 10.9.5 and Office 14.4.5.

A: I had the same problem and just applied the solution recommended, to change the region from US Computer to US, and know what? It worked! But don't forget to close Excel and open it again to see the result.


text:
Q: Create New Macro (Shortcut) to Copy Paste and Execute Code in the Integrated Terminal The Problem
An operation I do a lot is to highlight/select code on the editors and then paste it on the integrated terminal to execute it. While I got pretty fast at using Ctrl + c, Ctrl + backtick, Ctrl + Shift + v and Enter, it's very annoying and repetitive. Is there a way to configure a macro or shortcut for this?
A Solution (failed) Attempt
This Github thread and this StackOverflow Question show how to create a shortcut to toggle between different Integrated Terminals. I would like for something similar to happen in my case (I used Ctrl + Shift + u in the example below), e.g.:
[
    {
        "key" : "ctrl+shift+k",
        "command" : "workbench.action.terminal.focusNext"
    },
    {
        "key" : "ctrl+shift+j",
        "command" : "workbench.action.terminal.focusPrevious"
    },
    {
        "key" : "ctrl+shift+u",
        "command" : "ctrl+c+ctrl+`+ctrl+shift+v+enter"
    },
]

A: Without VS Code Extensions
There is a command : workbench.action.terminal.runSelectedText which does what you want already and is not bound to any keychord by default.
[Just to see the sendSequence command]:
If you don't go another route, this keybinding will run the selected text in the terminal:
{
    "key": "alt+t",
    "command": "workbench.action.terminal.sendSequence",
    "args": {
        "text": "${selectedText}\u000D"
    }
},

The \u000D is a return.
** [Added by Phillippe] :::
With a VS Code Extension (Macro Sequence Configurations)
VS Code currently doesn't allow concatenating shortcuts, so, if you want to execute the code on the Integrated Terminal and focus on it, you will have to install a macro extension.
There are several options for this. However, the suggested one is to use the multi-command (don't go for first results like macros, some of them are very outdated).
To create the shortcut mentioned above, create a sequence of commands in your settings.json file:
"multiCommand.commands": [ // Copy Paste to the Integrated Terminal and also Focus on it
    {
        "command": "multiCommand.copyPasteTerminalAndFocus",
        "sequence": [
            {
                "command" : "workbench.action.terminal.sendSequence",
                "args" : {"text" : "${selectedText}\u000D"}
            },
            "workbench.action.terminal.focus"
        ]
    },
]

And then create a shortcut for it in the keybindings.json file:
{
  "key": "alt+y",
  "command": "extension.multiCommand.execute",
  "args": { "command": "multiCommand.copyPasteTerminalAndFocus" }
},


text:
Q: Handling royalty fees payments when trading semi-fungible SPL Tokens We are building a Solana based application which will mint Semi-Fungible tokens (for Fungible Assets) let people trade them.
What we want next is to add metadata to this mint through which we are also going to set the creators and the seller fee basis points for royalty payments. We know how to do this and we have done it.
Anyway, the problem is the following: all the docs available on Metaplex we've seen are revolving around NFTs, Master Editions, Printing Editions, Auctions, etc. - which is not the case for us as we need to mint more than one token from the same mint.
The most important thing is to manage to benefit from the royalty fees each time shares are being traded on the secondary market. So we don't need auctions, vaults or other mechanisms like these.

*

*Initially, we were thinking about Serum, but we don't know whether
Serum also takes care of transferring the royalty fee to the
creators when the funds are settled.

*After Serum, we've looked at the examples in the Metaplex
documentation about Metaplex Storefronts, but, as I said above, that
was really focusing on NFTs, Master Editions, Printing Editions,
Auctions, etc. - which don't seem to fit our use case of Fungible
Asset. Maybe can this be customized for our Fungible Assets use case
somehow?
Would you be so kind to help us clear up a little bit what approach is the best for our use case and our needs?

A: Serum v4 (not released on mainnet yet) does support Metaplex royalties (see this commit). It should be released on mainnet in the coming weeks/month.
I am not aware of any other smart contract on Solana which supports this feature. However, you could probably create your own fork of an open source AMM and add a logic similar to the commit above.


text: Q: Does Virtual DOM used by React slows down browser as it maintains 2 copies of DOM in memory I know that React updates the DOM in batches which makes react pretty fast by skipping whole DOM updation, but I have a doubt that does maintaining two in-memory representation of DOM makes browser slow. Suppose if I open 10 tabs with react apps so each app will maintains its own copies of virtual dom in memory.


text:
Q: correct usage with commas in this example While introducing someone, we use commas.
·         This is Jane, my sister.
·         The distinguished scientist, Mr. Stephen, of AKL University, will be addressing the crowd tomorrow.
In the second sentence, the comma before and after the name indicates we are talking about a specific scientist of AKL University. The comma after the name also tells us that the information after the name is essential to identify the person.
https://www.grammar.com/the_correct_way_to_use_commas_with_names_and_titles
Doesn't the comma before the title of the University define it as non-essential not essential to identify the person in this example?
Not least because there would likely be many distinguished scientists within any given University but were talking about a specific one.

A: The first sentence could be phrased without a comma as

This is my sister Jane.

which is now phrased in a way similar to the second sentence. Here, it is the first comma which should go.

The distinguished scientist Mr. Stephen, of AKL University, will be addressing the crowd tomorrow.

It is precisely because Mr Stephen's university is non-essential, that it can be separated by commas (or parentheses).
The important information is that Mr Stephen will be speaking, not "the distinguished scientist" – which describes Mr Stephen.
Alternatively the sentence could be phrased as

Mr. Stephen, the distinguished scientist from AKL University, will be addressing the crowd tomorrow.

Here, the part within commas informs who Mr Stephen is and where he is from, for those who might not know of him.


text:
Q: Assigning latitude and longitude to a particular pixel in satellite image Pixel of a satellite images can be assigned latitude and longitude, but how this is done as each pixel represent certain area depending on the resolution of image that can be too high to assign latitude and longitude?

A: That all depends on the dataset and software you are using. GDAL for instance refers to the top left corner of the top left pixel when showing the origin. But given the affine transformation you can also calculate the position of the center of the pixel.
Generally there are two common ways that the geolocation refers to: left top and center of the pixel.


text:
Q: Make only visible parts of png clickable UIbutton swift Hi I have a file where the view is buildt up of 10 layered images that is pngs with big transparent parts. I like this to be clickable only on the visible parts, but how ever I try it's only the top image/button that register clicks. I've tried with both UIbuttons and tappable UIImage views. I work in swift 2.2. Does anyone have an idea on how to solve this?

A: *

*Sort the image views by z-position in the view hierarchy. This ensures correct behaviour when multiple opaque regions overlap.

*Iterate through all of the images.

*For each image, check the alpha component of the pixel at the selected location.

*The alpha will be between some range (usually between 0 ... 100). If the alpha is greater than some threshold amount, then respond to the tap and exit, otherwise check the next image.

Below is an example of how this would work. The images and tap gesture have been added in interface builder. This example just brings the tapped view to the front, although it can be easily modified for your required behaviour.
class ClickViewController: UIViewController {

    @IBOutlet var images: [UIImageView]!

    @IBAction internal func tapGestureHandler(gesture: UITapGestureRecognizer) {

        let sorted = images.sort() { a, b in
            return a.layer.zPosition < b.layer.zPosition
        }

        for (i, image) in sorted.enumerate() {

            let location = gesture.locationInView(image)
            let alpha = image.alphaAtPoint(location)

            if alpha > 50.0 {

                print("selected image #\(i) \(image.layer.zPosition)")
                view.addSubview(image)

                return
            }
        }
    }
}

Here is an example of how to set up the storyboard. Note the image views and the tap gesture recogniser. The views can also be added programatically.

Link each image to the images IBCollection, under the Referencing Outlet Collections in the Connections Inspector.

Here is the code to determine the alpha component of the pixel in image at the tapped location. This code below was provided as an answer to another similar question on SO.
extension UIImageView {

    //
    // Return the alpha component of a pixel in the UIImageView.
    //
    // See: https://stackoverflow.com/questions/27923232/how-to-know-that-if-the-only-visible-area-of-a-png-is-touched-in-xcode-swift-o?rq=1
    //
    func alphaAtPoint(point: CGPoint) -> CGFloat {

        var pixel: [UInt8] = [0, 0, 0, 0]
        let colorSpace = CGColorSpaceCreateDeviceRGB();
        let alphaInfo = CGImageAlphaInfo.PremultipliedLast.rawValue

        guard let context = CGBitmapContextCreate(&pixel, 1, 1, 8, 4, colorSpace, alphaInfo) else {
            return 0
        }

        CGContextTranslateCTM(context, -point.x, -point.y);

        layer.renderInContext(context)

        let floatAlpha = CGFloat(pixel[3])

        return floatAlpha
    }
}

See the example app available on GitHub.

A: @Luke Van In
Thanks for this answer, it helped me out a lot.
Here is the Swift 3 version: (Some syntax changes)
import UIKit

class ViewController: UIViewController {

@IBOutlet var images: [UIImageView]!

@IBAction internal func tapGestureHandler(gesture: UITapGestureRecognizer) {

    let sorted = images.sorted() { a, b in
        return a.layer.zPosition < b.layer.zPosition
    }

    for (i, image) in sorted.enumerated() {

        let location = gesture.location(in: image)
        let alpha = image.alphaAtPoint(point: location)

        if alpha > 50.0 {

            print("selected image #\(i) \(image.layer.zPosition)")
            view.addSubview(image)

            return
        }
    }
}

}

extension UIImageView {

func alphaAtPoint(point: CGPoint) -> CGFloat {

    var pixel: [UInt8] = [0, 0, 0, 0]
    let colorSpace = CGColorSpaceCreateDeviceRGB();
    let alphaInfo = CGImageAlphaInfo.premultipliedLast.rawValue

    guard let context = CGContext(data: &pixel, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: colorSpace, bitmapInfo: alphaInfo) else {
        return 0
    }

    context.translateBy(x: -point.x, y: -point.y);

    layer.render(in: context)

    let floatAlpha = CGFloat(pixel[3])

    return floatAlpha
 }
}


text:
Q: what happens when we invoke a method on a nil pointer
Possible Duplicate:
Sending a message to nil?

what happens when we invoke a method on a nil pointer

A: It returns 0, nil, a structure filled with 0s, etc.
Sending Messages to nil


text:
Q: Import data containing title instead of ID in django I am using django-import-export. It is an extension used to import tables of data to the admin panel using a csv file. I have a model with a foreign key : ProductModel, now if i want to import data i have to supply an ID of the ProductModel in the csv. I want a bypass so I can use title of an object instead of id in the csv
class Item(models.Model):
    title = models.CharField(max_length=100)
    model = models.ForeignKey(ProductModel, ....)

class ProductModel(models.Model):
    title = models.CharField(max_length=100)
    desc = models.Tex.....

A: You have to declare 'title' as the lookup field in your ForeignKeyWidget definition.
For example:
from import_export import fields, resources
from import_export.widgets import ForeignKeyWidget

class ItemResource(resources.ModelResource):
    model = fields.Field(
        column_name='model',
        attribute='model',
        widget=ForeignKeyWidget(ProductModel, 'title'))

    class Meta:
        fields = ('model',)


text:
Q: Using Jackson As.External_Property with a Collection Trying to serialize (and then deserialize) a container with a list of subtypes using JsonTypeInfo.As.EXTERNAL_PROPERTY.
I get
com.fasterxml.jackson.core.JsonGenerationException: Can not write a field name, expecting a value

when Jackson tries to write the collection (elements)
public class Container {

public static final TypeReference<Container> CONTAINER_REF = new TypeReference<Container>() {
    // nothing extra
};

@JsonTypeInfo(use = Id.NAME, include = As.EXTERNAL_PROPERTY)
@JsonSubTypes({
      @Type(value = ChildOne.class, name = "childOne"),
      @Type(value = ChildTwo.class, name = "childTwo"),
      })
private List<? extends Parent<?>> elements;

public Container() {
   super();
}

public List<? extends Parent<?>> getElements() {
    return elements;
}

public void setElements(List<? extends Parent<?>> elements) {
    this.elements = elements;
}

}
@JsonSubTypes({
@Type(value = ChildOne.class, name = "childOne"),
@Type(value = ChildTwo.class, name = "childTwo"),
})
public abstract class Parent<T> {

public Parent() {
    super();
}

public abstract T getSomething();

public static class ChildOne extends Parent<String> {
    public ChildOne() {
        super();
    }

    @Override
    public String getSomething() {
        return "lala";
    }
}

public static class ChildTwo extends Parent<Long> {
    public ChildTwo() {
        super();
    }

    @Override
    public Long getSomething() {
        return 764L;
    }
}

}
Note that I want the type property to be part of the container and not per each item in the collection.
EDIT:
I've ended up using JsonTypeInfo.As.Property instead, with two subclasses of Container and a type property that each subclass has to implement returning it's class name

A: That is not possible to do. Your Collection declaration can either indicate uniform non-polymorphic type, or base of polymorphic type. But it can not force contents.


text:
Q: why can't I add a member to an ADobject If I have an object of type Microsoft.ActiveDirectory.Management.ADObject, I can't use Add-Member to add a note property, unless I use -force. If I don't use the force directive, I get an error like:

Add-Member : Cannot add a member with the name "SAMAccountName"
  because a member with that name already exists. To overwrite the
  member anyway, add the Force parameter to your command.

But, it doesn't already exist. And that happens for any property name. For example:
$domainAccount | Add-Member -NotePropertyName SAMAccountName -NotePropertyValue $account.name

But, this works:
$domainAccount | Add-Member -NotePropertyName SAMAccountName -NotePropertyValue $account.name -force

I can't find documentation that explains this. Can you explain it? And, is there any danger in doing this with the -force directive?

A: The ADObject class behaves a bit clumsy, in that by simply asking if a property exists, you cause the property to be created if it doesn't.
When Add-Member checks for whether the SAMAccountName property already exists, it incidentally cause it to be created.
Just use the -Force parameter switch.

You can reproduce this behavior yourself:
Import-Module ActiveDirectory
$ADObject = New-Object Microsoft.ActiveDirectory.Management.ADObject

# No SamAccountName property will be listed
$ADObject | Get-Member

Now, try to reference a non-existing property, like "SamAccountName" (the ADObject extends the ADPropertyValueCollection class which is basically a dictionary, so indexing into it's property is totally valid):
$ADObject["SamAccountName"]
# SamAccountName property will now be listed even though we haven't set it
$ADObject | Get-Member

This is not restricted to AD property names, anything goes:
"1 This","2 Is","3 Quite","4 Funky","5 Isn't","6 It?" |ForEach-Object {
    [void]$ADObject[$_]
}

$ADObject |Get-Member

A: Microsoft.ActiveDirectory.Management.ADObject already have SamAccountName property. You don't need to recreate it. Just need define value for it, like this:
$obj = New-Object Microsoft.ActiveDirectory.Management.ADObject
$obj.SamAccountName = 'AccountName'
$obj | Get-Member

Output:
TypeName: Microsoft.ActiveDirectory.Management.ADObject

Name           MemberType            Definition
----           ----------            ----------
Contains       Method                bool Contains(string propertyName)
Equals         Method                bool Equals(System.Object obj)
GetEnumerator  Method                System.Collections.IDictionaryEnumerator GetEnumerator()
GetHashCode    Method                int GetHashCode()
GetType        Method                type GetType()
ToString       Method                string ToString()
Item           ParameterizedProperty Microsoft.ActiveDirectory.Management.ADPropertyValueCollection Item(string propertyN...
SamAccountName Property              Microsoft.ActiveDirectory.Management.ADPropertyValueCollection SamAccountName {get;s...


text:
Q: How to filter while loop in PHP I stuck on this,
I want to create a table with 10 rows, each row having "same drop down menu" of 10 products. But in every row different product selected. example in first row first product in second row second product and so on. The bellow code is showing drop down menu in each row but every row have first product selected. How can I select next product for next row?

            <select>
                <?php
                    $query = "SELECT * FROM table_name WHERE featured=1 LIMIT 10";
                    $result = mysqli_query($connection, $query);
                    while($row = mysqli_fetch_array($result)){
                        echo "<option>".$row["product_name"]."</option>"
                    }
                ?>
             </select>

            <select>
                <?php
                    $query = "SELECT * FROM table_name WHERE featured=1 LIMIT 10";
                    $result = mysqli_query($connection, $query);
                    while($row = mysqli_fetch_array($result)){
                        echo "<option>".$row["product_name"]."</option>"
                    }
                ?>
             </select>

A:     <?
    //Only Once call to DB
    $query = "SELECT * FROM tbl WHERE featured=1 LIMIT 10";
    $result = mysqli_query($connection, $query);
    $pos = 0;
    $currentRow = 0;
    ?>

            <select>
                <?php

                while($row = mysqli_fetch_array($result)){

                if($pos==$currentRow)
                   echo "<option selected=\"selected\">".$row["product_name"]."                     </option>";
                else
                   echo "<option>".$row["product_name"]."</option>";
                $pos++;

                }

                mysqli_data_seek( $result, 0 );
                $pos = 0;
                $currentRow++;

                ?>
            </select>

            <select>
                <?php
               while($row = mysqli_fetch_array($result)){

                if($pos==$currentRow)
                   echo "<option selected=\"selected\">".$row["product_name"]."                     </option>";
                else
                   echo "<option>".$row["product_name"]."</option>";
                           $pos++;

                }

                mysqli_data_seek( $result, 0 );
                $pos = 0;
                $currentRow++;
                ?>

            </select>

A: your second while loop
$i=0;
while($row = mysqli_fetch_array($result)){
$i++;
if($i==2)
    echo "<option selected=\"selected\">".$row["product_name"]."</option>";
else
 echo "<option>".$row["product_name"]."</option>";
    }
    ?>


text:
Q: Using BasicAuth in servant I'm trying user BasicAuth in servant :
type ServerAPI = "news" :> BasicAuth "auth" User :> ReqBody '[JSON] News :> Post '[JSON] Bool
Documentation and cookbook both suggests having Server API like this :
server :: Server ServerAPI
server = createNewsHandler (user :: User)
and createNewsHandler of type
User -> News -> Handler Bool
However, there is no 'user' variable in the scope of server function and code does not compile of course.
I wonder where can find valid example of using this feature.
I tried reading documentation, cookbook, articles with examples and expected finding proper examples.


text:
Q: How do I see the contract log events in Ethereum? I finished the https://www.ethereum.org/crowdsale tutorial in Ethereum and intentionally left the crowdsale having failed its funding goal (sample code at the start of the page). I fired the "safeWithdrawal" function from within Ethereum-Wallet and it adds the transaction on to the blockchain. But at this point I do not know how to listen to the response. The ether I sent was not returned.

*

*I would like the ether to be returned.

*I would like to know how to listen to the event that should have fired. Or any feedback mechanism to know that the why / how the event fired.

Screenshot: http://i.stack.imgur.com/2lsVo.png

A: Currently, the Ethereum-Wallet has no debugger built-in for smart contracts.
I suggest, you code up your example using the browser-solidity. It allows you not only to code and test the deployment but got most recently a debugger built in. Click the little bug.

The debugger used in browser solidity is remix which is both a javascript IDE but also a library which can be attached to your own javascript projects. It is possible that future releases of Ethereum-Wallet will also include remix, this would simplify your task pretty much.
But for now, the mentioned browser tool seems like perfectly suited for your needs.


text:
Q: eternicode date picker - dynamically change language I have installed eternicode bootstrap date picker to a test form. This is working well.
I am now wanting to dynamically change the language of the date picker when the user changes a language select list on the form.
The exact operation is show here, on the eternicode sand box. If the user changes the language select list, the language of the date picker changes to the selected language without a page re-fresh.
I have tried to get this to work on my form, but cannot figure out how to get this to work on my form without a page re-fresh. I have looked at the source code, but could not find it - maybe b/c I am not so good at javascript.
I have installed the language files for the eternicode bootstrap date picker to the test form.
Here is the relevant select list code that I have:
<select name="language_code" id="id_language_code" >
    <option value="ar">Arabic - العربية</option>
    <option value="en-GB">English (UK) - English (UK)</option>
    <option value="en" selected="selected">English (US)</option>
    <option value="fr-CA">French (Canada) - français (Canada)</option>
    <option value="fr">French (France) - français (France)</option>
    <option value="de">German - Deutsch</option>
    <option value="it">Italian - italiano</option>
    <option value="pl">Polish - polski</option>
    <option value="pt-BR">Portuguese (Brazil) - português (Brasil)</option>
    <option value="pt">Portuguese (Portugal) - português (Portugal)</option>
    <option value="ru">Russian - pусский</option>
    <option value="es">Spanish (Spain) - español (España)</option>
</select>

Here is the javascript code I have to add the date picker to my text field on my form:
    $( "#id_test_finish_date" ).datepicker({

        autoclose: true,
        changeMonth: true,
        changeYear: true,
        clearBtn: true,
        endDate: '01/2900',
        format: 'mm/yyyy',
        language: 'en',
        minViewMode: 1,
        startView: 2,
        startDate: '01/1965',

    }).attr('readonly','readonly');

I am hoping that someone smarter than me can show me how to get this working.

A: http://jsfiddle.net/pc9barL0/
JQ:
//datepicker localization files:
//https://github.com/eternicode/bootstrap-datepicker/tree/master/js/locales

//how to localize plugin
//http://bootstrap-datepicker.readthedocs.org/en/latest/i18n.html

//required files
//on the left side JSFIDDLE click on the External Resources  to see the required files

$( "#id_test_finish_date" ).datepicker({
    autoclose: true,
    clearBtn: true,
    endDate: '01/01/2900',
    format: 'dd/mm/yyyy',
    startDate: '01/01/1965'}
).attr('readonly','readonly');

$( "#id_language_code" ).change(function() {
     $element=$( "#id_test_finish_date" );

     $element.datepicker('remove');
     $element.datepicker({language: $( this ).val()});
});

HTML:
<select name="language_code" id="id_language_code" >
    <option value="ar">Arabic - العربية</option>
    <option value="en" selected="selected">English (US)</option>
    <option value="fr">French (France) - français (France)</option>
    <option value="ru">Russian - pусский</option>
    <option value="rs">Serbian - српски</option>
</select>

<input type="text" id="id_test_finish_date" />


text:
Q: Find if there is any subarray that do not match specified condition I have an array called orgnisation. This array entails units in the organisation. Each unit is an object that has an array staff. Some staff have drivers license type A (driversLicenseA).
checkDriversLicense function must go through organisation and see if there is at least one person holding driver's license in each unit. If there is any unit in the whole organisation that has no staff holding driver's license, that unit has to be returned.
organisation: [
  {
    id: 1,
    title: 'Sub Org 1',
    staff: [
      {
        id: 11,
        name: 'John',
        driversLicenseA: false,
      },
      {
        id: 12,
        name: 'Mike',
        driversLicenseA: true,
      },
      {
        id: 13,
        name: 'Daniel',
        driversLicenseA: false,
      }
    ]
  }
  ,
  {
    id: 2,
    title: 'Sub Org 2',
    staff: [
      {
        id: 21,
        name: 'Gustav',
        driversLicenseA: false,
      },
      {
        id: 22,
        name: 'Sandra',
        driversLicenseA: false,
      },
      {
        id: 23,
        name: 'Nikita',
        driversLicenseA: false,
      }
    ]
  },
  {
    id: 3,
    title: 'Sub Org 3',
    staff: [
      {
        id: 31,
        name: 'Carla',
        driversLicenseA: false,
      },
      {
        id: 32,
        name: 'Augustin',
        driversLicenseA: false,
      },
      {
        id: 33,
        name: 'Martin',
        driversLicenseA: false,

      }
    ]
  },

]

public checkDriversLicense(organisation: any[]) {
  let driversLicenseA =  organisation.find((element) => element.staff != null && element.staff?.length != 0 && element.staff?.some((item) => item.driversLicenseA == true));
  return driversLicenseA ;

}

This code however checkes all units and if there is one person in the whole organsation that has driver's license, returns true (false is not returned if there are other units that have no staff holding deriver's license).
How can I modify to return correct result?
I want fasle be returned because Sub Org 2 and Sub Org 3 have no staff with driver's license.

A: You could check with Array#every for organisation abd with Array#some for each staff.

const
    organisation = [{ id: 1, title: 'Sub Org 1', staff: [{ id: 11, name: 'John', driversLicenseA: false }, { id: 12, name: 'Mike', driversLicenseA: true }, { id: 13, name: 'Daniel', driversLicenseA: false }] }, { id: 2, title: 'Sub Org 2', staff: [{ id: 21, name: 'Gustav', driversLicenseA: false }, { id: 22, name: 'Sandra', driversLicenseA: false }, { id: 23, name: 'Nikita', driversLicenseA: false }] }, { id: 3, title: 'Sub Org 3', units: [{ id: 31, name: 'Carla', driversLicenseA: false }, { id: 32, name: 'Augustin', driversLicenseA: false }, { id: 33, name: 'Martin', driversLicenseA: false }] }],
    eachOrganisationHasLicenceA = organisation.every(({ staff }) =>
        staff.some(({ driversLicenseA }) => driversLicenseA)
    );

console.log(eachOrganisationHasLicenceA);

A: Though not the most compact code possible, I think this is clear to understand
public checkDriversLicence(organisation: any[]) {
  for (let unit of organisation) {
    // each unit should have at least 1 driver's licence
    if (unit.staff.filter(e => e.driversLicenceA).length === 0) {
      // this unit does not have anyone with a driver's licence
      return false;
    }
  }
  // if we reach this point, each unit has at least one staff member with a driver's licence
  return true;
}

A: Here is something that should help.

let organization = [
      {
        id: 1,
        title: 'Sub Org 1',
        staff: [
          {
            id: 11,
            name: 'John',
            driversLicenseA: true,
          },
          {
            id: 12,
            name: 'Mike',
            driversLicenseA: true,
          },
          {
            id: 13,
            name: 'Daniel',
            driversLicenseA: true,
          }
        ]
      },
      {
        id: 2,
        title: 'Sub Org 1',
        staff: [
          {
            id: 11,
            name: 'John',
            driversLicenseA: false,
          },
          {
            id: 12,
            name: 'Mike',
            driversLicenseA: false,
          },
          {
            id: 13,
            name: 'Daniel',
            driversLicenseA: false,
          }
        ]
      },
      {
        id: 3,
        title: 'Sub Org 2',
        staff: [
          {
            id: 21,
            name: 'Gustav',
            driversLicenseA: false,
          },
          {
            id: 22,
            name: 'Sandra',
            driversLicenseA: true,
          },
          {
            id: 23,
            name: 'Nikita',
            driversLicenseA: false,
          }
        ]
      },
      {
        id: 4,
        title: 'Sub Org 3',
        staff : [
          {
            id: 31,
            name: 'Carla',
            driversLicenseA: true,
          },
          {
            id: 32,
            name: 'Augustin',
            driversLicenseA: true,
          },
          {
            id: 33,
            name: 'Martin',
            driversLicenseA: false,

          }
        ]
      },
];

 // lets loop over the collection and try to acces the staff property!

organization.forEach(( or ) => {
  drivers = or.staff; // these are our staff.

  // lets loop over the staffs and see if atleast one does not meet the criteria.
  // reduce function will allow us to iterate all the values and return a single value at the end.
  // we simply compare the value from each iteration to the previous value.
  // ie check if the current value is equal to the previous iteration value and return it.
  // The value returned at each iteration is used for next one and so on.
  // The code below assumes if any value at any iteration is false all values will be false.
  // at the end only values with true wil be the one that match our requirements.

  // check object 1 and 2
  let valid = drivers.reduce( ( accumulator , currentValue) => {
    return currentValue.driversLicenseA == accumulator;
  } );

  // lastly check if the value returned is as per our ask and print.
  if(valid){
    console.log("Not applicable to Orgnization Id :" + or.id );
  }else{
   console.log("applicable to Organization Id :" +  or.id );
  }

});


text:
Q: Is number of quasi-kernels NP-hard? A quasi-kernel in a directed graph D is an independent subset of vertices $S$ so that for every $v \in V(D)-S$ either $v->s$ for some $s \in S$ or $v->w->s$ for some $w \in V(D)-S, s \in S$.
Equivalently, a set $S$ is a quasi-kernel if $d(s,t) \geq 2$ for every $s,t \in S$ and $d(v,s) \leq 2$ for every $v \in V(D)-S,s \in s$.
Chvatal & Lovasz had proved that every digraph has a quasi-kernel (very easy proof by induction) and Jacob & Meyniel had proved that a graph without a kernel has at least three quasi-kernels.
My question is:

Is counting the number of
  quasi-kernels NP-hard?

A: Here's a reduction that works even if the directed graphs are required to be simple. I'll argue that there is a polynomial time algorithm which, given a graph $G$, outputs a directed graph $G'$ such that the number of independent sets in $G$ is the number of quasi-kernels in $G'$. Hence the number of quasi-kernels is NP-hard to calculate.
Take $G$, direct each edge arbitrarily, and for each vertex $v$ in $G$ add a directed path $v\rightarrow v'\rightarrow v''$ of length 2, directed away from the vertex. Call the resulting graph $G'$. (So $|V(G'|=3|V(G)|$ and $|E(G')|=|E(G)|+2|V(G|$.) Vertices of the form $v''$ must be in any quasi-kernel, and so vertices of the form $v'$ are not in any quasi-kernel, and the only condition on the original vertices are that two adjacent vertices cannot both be in a quasi-kernel. So the number of quasi-kernels in $G'$ is the number of independent sets in $G$.
This gives #P-completeness and NP-hardness of approximation (see M. Dyer, L.A. Goldberg, C. Greenhill and M. Jerrum, On the relative complexity of approximate counting problems, Algorithmica 38(3) 471-500 (2003)).

A: If I understand correctly the condition $ d(s,t) \geq 2 $ means there is no outgoing edge from $s$ to $t$
which is very close to independent set in undirected graphs.
Here is an argument why your problem is #P complete via reduction from independent set.
Given undirected graph $G$ make it directed by adding both $(s,t)$ and $(t,s)$.
The condition $ d(s,t) \geq 2 $ means $s$ and $t$ are not adjacent in $G$ and your set $S$
is an independent set for $G$.
Counting independent sets is #P complete.


text:
Q: SQL selecting rows with same field value The initial table is something like this
id  name        count
1   chocolate   5
1   cheeze      3
2   pepperoni   2
2   potatoes    1
2   cheese      7
3   dirty sock  2

What i want is to select the rows that have different ids but have the same name. In other words the ingredients that would be used in more recipes

A: If I understand correctly, you wanted to select duplicates by name. In your example that should have been cheese if you used the same spelling (but you didn't - is it mistake?).
Assuming I got it right, this should work (SQLFiddle DEMO):
SELECT * FROM mytable
WHERE [name] IN (
    SELECT [name]
    FROM mytable
    GROUP BY [name]
    HAVING count(*) > 1
)

A: First get your unique id, name pairs as a subquery, then aggregate the results by name.
select name, COUNT(*) as count
from (
    select distinct id, name
    from mytable) as sq
group by name

A: Tried to post in comment above, formatting didn't quite work out; this works as well:
SELECT t1.id FROM myTable t1, myTable t2
    WHERE t1.name LIKE t2.name AND t1.id != t2.id;

A: select name, count(id) as used_in_recipes
from ingredients
group by name;
Do we really need to check for a different id?
why would i need to repeat the same ingredient in a recipe?
Just let's group them by name.


text:
Q: Ruby Inserting "\n" newline into String with Regular Expression I have a variable like so:

output =  "KORD 142327Z 1500/1606 31012KT P6SM FEW060 SCT300 FM150200 04007KT >P6SM FEW300 FM150400 01005KT P6SM SKC FM151400 22008KT P6SM SCT250 FM151900 >22014G23KT P6SM BKN250 FM160200 23014KT P6SM SCT150 BKN250 WS010/25040"

I want to insert a newline before every "FM" character sequence so I can print it to user and its easier to read.
Currently my code is as follows, but replaces the first "FM" sequence with a "\n" then stops without continuing onto the next "FM" set.

output [/(FM{1})/, 0]  = "\n"

I don't want to replace FM with newline. I need to append "\n" immediately before each "FM" character set. Any help with this would be appreciated.

A: Try this:
 output.gsub!("FM","\nFM")


text:
Q: Set time or sending limit for PHP mailing script I have a simple php registration form that captures a name and email address. After registering, I have a confirmation email set to go to the registrant and one to go to the admin.
I've had an issue where the user only registered once, but some issue caused the email to be sent 50+ times to both the registrant and admin. It's only happened a few times, but I'm trying to prevent it from happening in the future.
I'm thinking of a time limit on running the script, but wondering the best way to handle this. Below is a snippet of the mailing portion of the script.
2 notes, in case they are of use:

*

*I'm using PEAR Mailer

*My mail is being sent via MailGun

$headers = array ('From' => $from,
    'To' => $to,
    'Bcc' => $bcc,
    'Reply-to' => $email,
    'Subject' => $subject,
    'MIME-Version' => 1,
    'Content-type' => 'text/html;charset=iso-8859-1');

$headers_admin_notification = array ('From' => $from_admin_notification,
    'To' => $to_admin_notification,
    'Subject' => $subject_admin_notification,
    'MIME-Version' => 1,
    'Content-type' => 'text/html;charset=iso-8859-1');

// credentials for SMTP Authentication included from config file

$smtp = Mail::factory('smtp',   array ('host' => 'ssl://smtp.mailgun.org',
    'auth' => true,
    'port' => 465,
    'username' => 'XXXXX',
    'password' => 'XXXXX'));

$mail = $smtp->send($to, $headers, $body);
$mail_admin_notification = $smtp->send($to_admin_notification, $headers_admin_notification, $body_admin_notification);

if (PEAR::isError($mail) || PEAR::isError($mail_admin_notification)) {
    echo("
" . $mail->getMessage() . "
");
    echo("
" . $mail_admin_notification->getMessage() . "
");
}
else {
    header("Location: LINK-TO-MY-CONFIRMATION-PAGE?fname=$fname&session=$readable_date_and_time");
}

Thanks!


text:
Q: Using the definition of the derivative prove that if $f(x)=x^\frac{4}{3}$ then $f'(x)=\frac{4x^\frac{1}{3}}{3}$ So I have that $f'(x)=\lim_{h \to 0} \frac{f(x+h)-f(x)}{h}$
and know that applying
$f(x)=x^\frac{4}{3}=f\frac{(x+h)^\frac{4}{3} -x^\frac{4}{3}}{h}$
but am at a loss when trying to expand
$(x+h)^\frac{4}{3}$

A: You can use the generalized binomial coeficients to solve this problem, which gives you
$(x + h)^\frac{4}{3} = x^\frac{4}{3}(1 + \frac{4h}{3x} + \frac{4h^2}{18x^2} + \ldots)$
It will go on forever, but since you divide by $h$, most will tend to zero, and you'll be left with $x^\frac{4}{3} \frac{4}{3x} = \frac{4}{3}x^\frac{1}{3}$.

A: This is a little bit not fun, but will give your algebra a good workout. First note that
$$(x+h)^{4/3}-x^{4/3}=\left((x+h)^{2/3}+x^{2/3}\right)\left((x+h)^{2/3}-x^{2/3}\right)
.\tag{1}$$
and the right-hand side of (1) can be written as
$$\left((x+h)^{2/3}+x^{2/3}\right)\left((x+h)^{1/3}+x^{1/3}\right)\left((x+h)^{1/3}-x^{1/3}\right)
.\tag{2}$$
We have used the identity $a^2-b^2=(a+b)(a-b)$ a couple of times.
So we want to find
$$\lim_{h\to 0}\frac{\left((x+h)^{2/3}+x^{2/3}\right)\left((x+h)^{1/3}+x^{1/3}\right)\left((x+h)^{1/3}-x^{1/3}\right)}{h}.\tag{3}$$
The first two terms in the numerator of (3) behave very nicely as $h\to 0$. We need to worry only about
$$\frac{(x+h)^{1/3}-x^1/3}{h}.\tag{4}$$
Now we use the identity $(a-b)(a^2+ab+b^2)=a^3-b^3$. Letting $a=(x+h)^{1/3}$ and $b=x^{1/3}$ we multiply top and bottom of (4) by $a^2+ab+b^2$. We get
$$\frac{(x+h)-x}{h\left((x+h)^{2/3}+(x+h)^{1/3}x^{1/3}+x^{2/3}\right)}.$$
Now everything is under control, you can put the pieces together.
Remark: There are many other ways to do the algebra. For example instead of the initial factoring that we did, you could immediately multiply top and bottom by
$$(x+h)^{8/3}+(x+h)^{4/3}x^{4/3}+x^{8/3}.$$
Then on top we end up with $(x+h)^4-x^4$. We can expand this as usual and get a simpler-looking path to the answer.

A: Let
$$D = \frac{(x+h)^{4/3}-x^{4/3}}{h}$$
Then
$$\begin{align}D^3 &= \frac{(x+h)^4-3 (x+h)^{8/3} x^{4/3} + 3 (x+h)^{4/3} x^{8/3} - x^4}{h^3}\\ &= \frac{4 x^3 h + 6 x^2 h^2 + 4 x h^3 + h^4 -3 (x+h)^{4/3} x^{4/3} \left [ (x+h)^{4/3}-x^{4/3}\right ]}{h^3}\\ &= \frac{4 x^3 + 6 x^2 h + 4 x h^2 +h^3}{h^2} - \frac{3 (x+h)^{4/3} x^{4/3}}{h^2} D\end{align}$$
Thus,
$$h^2 D^3 + 3 (x+h)^{4/3} x^{4/3} D = 4 x^3 + 6 x^2 h + 4 x h^2 +h^3$$
Taking the limit as $h \to 0$, (and assuming that $\bar{D}=\lim_{h \to 0} D$ remains finite as we do so), we see that
$$3 x^{8/3} \bar{D} = 4 x^3$$
or $\bar{D} = (4/3) x^{1/3}$ as was to be demonstrated.

A: Hint:
The expansion of $(x+h)^\frac{4}{3}$ is
$$h\sqrt[3]{x+h} + x\sqrt[3]{x+h}$$
So then you will have
$$\lim_{x \rightarrow \infty}\frac{h\sqrt[3]{x+h} + x\sqrt[3]{x+h} - x^{\frac{4}{3}}}{h}$$
Can you take it from there?


text:
Q: coplot in R - how to tell which plot is which I am using coplot in R to plot some conditioning plots:
coplot(var1 ~ var2 | var3, data=dtb, number=5, overlap=.1, panel=function(x,y, col, pch) {idx = order(x); lines(x[idx], predict(loess(y ~ x))[idx], pch = pch, col = col)})

How can one tell which plot corresponds to which "bucket" of the conditioning variable, in this case var3?
> dput(dtb)
structure(list(var1 = 1:50, var2 = c(50L, 49L, 48L, 47L, 46L,
45L, 44L, 43L, 42L, 41L, 40L, 39L, 38L, 37L, 36L, 35L, 34L, 33L,
32L, 31L, 30L, 29L, 28L, 27L, 26L, 25L, 24L, 23L, 22L, 21L, 20L,
19L, 18L, 17L, 16L, 15L, 14L, 13L, 12L, 11L, 10L, 9L, 8L, 7L,
6L, 5L, 4L, 3L, 2L, 1L), var3 = c(1L, 2L, 3L, 4L, 5L, 6L, 7L,
8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L,
3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L,
8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L)), .Names = c("var1",
"var2", "var3"), row.names = c(NA, -50L), class = "data.frame")

A: Apparently it is left to right and bottom to top, which means it is much easier to read if you set rows=1 :
# determine how many levels in var3
num <- length(unique(dtb$var3))

# plot in one row using all levels of var3
coplot(var1 ~ var2 | var3, data=dtb,
number=num,
overlap=.1,
col=rainbow(num),
type="o",           # plot symbols and lines
cex=2,              # make symbols larger
pch=as.character(c(seq(from=1,to=(num-1)),"T")), # use chars as symbols
rows=1)                                          # as.character not required
                                                 # due to "T"

# plot in two rows
coplot(var1 ~ var2 | var3, data=dtb,
number=num,
overlap=.1,
col=rainbow(num),
type="o",           # plot symbols and lines
cex=2,              # make symbols larger
pch=as.character(c(seq(from=1,to=(num-1)),"T")), # use chars as symbols
rows=2)                                          # as.character not required
                                                 # due to "T"


text:
Q: How to measure the power in mW of a radio signal I would like to build a small circuit to measure with my oscilloscope the power emitted by the 5.8GHz video transmitters mounted on my drones and searching I found this answer:
https://electronics.stackexchange.com/a/74370/228767
The question recommends using a 50 ohm dummy resistive load.
Why was that value chosen? is it random or can the optimal value be calculated?
Personally I will have to measure signals with power lower than one watt.
Also, to have precise measurements and avoid damaging the video transmitter, is that 50 ohm resistor sufficient, or is a more complex circuit necessary as shown here?
https://www.ab4oj.com/test/pwrmeas.html

A: You're not going to be able to directly measure a 5.8 GHz signal with the oscilloscope you have, it's rated bandwidth is 110 MHz. A multimeter is going to be even worse, probably less than 20 KHz.
Measurements at frequencies that high require special equipment and techniques, even very short wires can be a significant fraction of a wavelength.
What you need is an RF power meter designed for that frequency range (an internet search should turn up meters made for RC hobbyists that will cover the 5.8 GHz) or something like a directional coupler or RF detector rated for that range. These will basically rectify the RF and output a DC voltage that you can measure with a DMM or scope.
You can check this video to get some ideas about how to make measurements at this frequency.


text:
Q: How to train GPT2 with Tensorflow I'm trying to train gpt2 model with custom dataset, but it fails with the error below.
ValueError: Unexpected result of `train_function` (Empty logs). Please use `Model.compile(..., run_eagerly=True)`, or `tf.config.run_functions_eagerly(True)` for more information of where went wrong, or file a issue/bug to `tf.keras`.

I thought model and dataset are correctly defined and processed by referring this article.
But the error shows up when model.fit is executed.
Can someone tell me how to resolve the error, or proper way to train the model?
from transformers import TFGPT2LMHeadModel, GPT2Tokenizer
import tensorflow as tf

# Define the model
model = TFGPT2LMHeadModel.from_pretrained('gpt2', from_pt=True)
optimizer = tf.keras.optimizers.Adam(learning_rate=3e-5, epsilon=1e-08, clipnorm=1.0)
loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
metric = tf.keras.metrics.SparseCategoricalAccuracy('accuracy')
model.compile(optimizer=optimizer, loss=[loss, *[None] * model.config.n_layer], metrics=[metric], run_eagerly=True)
model.summary()

# Obtain the tokeinizer
tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
tokenizer.add_special_tokens({
  "eos_token": "</s>",
  "bos_token": "<s>",
  "unk_token": "<unk>",
  "pad_token": "<pad>",
  "mask_token": "<mask>"
})

# Get single string
paths = ['data.txt']  # each file only contains some sentences.

single_string = ''
for filename in paths:
    with open(filename, "r", encoding='utf-8') as f:
        x = f.read()
    single_string += x + tokenizer.eos_token

string_tokenized = tokenizer.encode(single_string)

print(string_tokenized)

# creating the TensorFlow dataset
examples = []
block_size = 100
BATCH_SIZE = 12
BUFFER_SIZE = 1000
for i in range(0, len(string_tokenized) - block_size + 1, block_size):
    examples.append(string_tokenized[i:i + block_size])
inputs, labels = [], []
for ex in examples:
    inputs.append(ex[:-1])
    labels.append(ex[1:])
dataset = tf.data.Dataset.from_tensor_slices((inputs, labels))
dataset = dataset.shuffle(BUFFER_SIZE).batch(BATCH_SIZE, drop_remainder=True)

print(dataset)

# train the model
num_epoch = 10
history = model.fit(dataset, epochs=num_epoch) # <- shows the error


text:
Q: How to close modal dialog when file download completed I have a modal dialog which contain form and hidden iframe to which form is submitted. The result of submission is file to download.
I need to close modal dialog as soon as download dialog is opened i.e. file is ready.
I was trying to catch 'onreadystatechange' event of iframe, but after submit call changing state to 'complete' it does not trigger 'onreadystatechange' event.
Eventually, i use window.setInterval which monitoring readyState of iframe and close modal dialog when its state == 'complete'.
the solution that using window.setInterval seems not professional to me and I am looking for better solution, I saw solution with cookies but I can't use cookies in my application.
Any help will be appreciated!

A: There is nothing wrong or unprofessional in using window.setInterval().

A:
 function Close_Popup() {
        $(".modal-backdrop").remove();
        $('#div_Popup1').modal('hide');
        $(".modal-backdrop fade in").remove();
    }

Call this function on OnClientClick="Close_div_Popup1_Popup();"


text:
Q: List the users in AD security group in sp server I added an AD security group in a sharepoint site. I want to list the users in this group. I want to do this in SP server instead of AD. Have anyone done this before? Could this be achieved through powershell? Please kindly advice.

A: You can use below commands:
Replace the asterisk (*) with the Security Group
Display on Screen:
  Get-ADGroupMember -identity "*" | Select Name

Export to CSV:
  Get-ADGroupMember -identity "*" | Select Name | Export-CSV -Path C:\Windows\Temp\SecurityGroups.csv -NoTypeInformation

Link Source: http://itnutt.com/powershell-list-members-of-ad-security-group/

A: You could try the following powershell script to achieve this:
$web=get-spweb http://yoursite

$ADGroup = $web.EnsureUser("ADGroup")

$reachedMax = $false

$users =[Microsoft.SharePoint.Utilities.SPUtility]::GetPrincipalsInGroup($web, $ADGroup
, 10,[ref]$reachedMax)
$users


text:
Q: What are the benefits of porting 32-bit iOS apps to 64-bits? If I have an existing tested 32-bit app code base, is porting to 64-bit worth the effort? What are the benefits? It will obviously take more memory at run time, but will it be faster as well? Fast enough to justify memory overhead?

A: One compelling reason is if you want to support iOS8 extensions with 64-bit operating systems.
From the release notes:

Extensions
Notes

*

*Extensions need an arm64 slice to run on 64-bit
  devices. If you try to run the armv7 slice on a 64-bit device it won't
  work.

*Apps need to have an arm64 slice if the bundle contains a
  framework that both the app and the app extension link against.

https://developer.apple.com/library/prerelease/ios/releasenotes/General/RN-iOSSDK-8.0/index.html


text:
Q: Exploring Hadoop code I wanted to know about Hadoop more than a black box. I wanted to explore the Hadoop code itself. How can I download the bundle not from the trunk and where should I start from? Any help would be really helpful
Thanks
Shujaat

A: The Hadoop code is in SVN and in Git also. Setup the Hadoop projects in Eclipse and start exploring the code. Currently 0.23, 0.22 and 0.20.205 branches is all where the active development is happening. HowToContribte is a nice start if you want to know more about the code. Learn what is MapReduce, Hadoop and finally setup Hadoop environment on a Linux box. Also, subscribe to the Hadoop mailing list and follow the JIRAs.
Not sure why not trunk. All the fun stuff happens at trunk.

A: To explorer hadoop code, make sure whether you are explorer in windows or linux box. If it is for windows, visit http://tech.zhenhua.info/2010/11/svn-subclipse.html
Hadoop requires Ivy, sh on windows.
Praveen, "Not Sure why not trunk", i did not understood the line? i used trunk by following these links http://hadoop.apache.org/common/version_control.html


text:
Q: Data mismatch in AWS DMS Bulk load vs CDC I have a postgis database(source) for which i have done DMS and moved it to S3 bucket(target) in parquet file.
There is a column name point of datatype-geometry(point, 4326) in the source which converts to string after dms and looks like this in target-
-In bulk load it is like -point": "<Point srsName=\"EPSG:4326\"><coordinates>72.836903300000003,19.0823766</coordinates></Point>"
-In CDC it is like -point": "0101000020E610000051D77F4262855EC09591C4DCFFB54240"
I am able to get the coordinates back from the string in full load by string parsing but during CDC it is in some random hexadecimal string from which I am not aware how to decode back to the coordinates.

A: Welcome to SO.
In PostgreSQL in order to display geometries in a format other than WKB you have to explicitly state it in your query. In your case ST_AsGML:
SELECT ST_AsGML('0101000020E610000051D77F4262855EC09591C4DCFFB54240');

                                               st_asgml
-------------------------------------------------------------------------------------------------------
 <gml:Point srsName="EPSG:4326"><gml:coordinates>-122.0841223,37.4218708</gml:coordinates></gml:Point>
(1 row)

Or something like this if you wish to omit the namespace (as your example suggests):
SELECT ST_AsGML('0101000020E610000051D77F4262855EC09591C4DCFFB54240', 15, 0, '', '');

                                       st_asgml
---------------------------------------------------------------------------------------
 <Point srsName="EPSG:4326"><coordinates>-122.0841223,37.4218708</coordinates></Point>
(1 row)

See also: Converting geometries in PostGIS


text:
Q: Load and save to txt file In my previous thread I forgot to show people that I had made an attempt to try this myself, rest assured, i have spent the past 2 hours trying to get this stupid problem solved.
I need to do the following :

*

*Search for file called "file.txt", if null then create it.

*Read the file to find the integer (should be the only thing in the whole file)

*If the integer doesn't exist then create it and set it to 1

*If it does already exist then add 1 to it, and save it again

*Open the file again, get the integer and print it to the console.

This is as far as I managed to get :
package science;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;

public class DumpData {

    static void writeStringToFile(String gender, String securityLevel){
        try {

            File file = new File(gender + securityLevel + ".txt");
            //file.getParentFile().mkdirs();

            PrintWriter pr = new PrintWriter(file);

            FileInputStream fs = new FileInputStream(gender + securityLevel + ".txt");
            BufferedReader br = new BufferedReader(new InputStreamReader(fs));
            if (br.readLine() == null) {
                pr.println("" + 0);
            }

            //String first = br.readLine();
            //System.out.println(first);
            try{
                String first = br.readLine();
                  int num = Integer.parseInt(first);
                  int add = (num + 1);
                  pr.println("" + add);
                  pr.close();
                  System.out.println(num);
                } catch (NumberFormatException e) {
                  // not an integer!
                    System.out.println("error");
                    System.out.println(br.readLine());
                }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

I kept getting this the message "error" printed to the console, and with more examination I found that nothing was being saved to the .txt file at all. I fully expected my code to add 1 to the int in the file every time the method was executed.

A: You're trying to read a line twice
if (br.readLine() == null) {         <-- first time
    pr.println("" + 0);
}

 //String first = br.readLine();
 //System.out.println(first);
 try{
     String first = br.readLine();   <-- second time

The second time will fail because there is no second line.
Instead just do this
String line;
while ((line = br.readLine()) != null){
    int num = Integer.parseInt(line.trim());
    ...
}

You don't need the first if statement

A: I strongly suggest you to work with Apache COmmons IO when dealing with files.
Here's the link : http://commons.apache.org/proper/commons-io/
Look at the FileUtils class.


text:
Q: Mat-Datepicker: how to use ja-JP Dateformat but keep english datepicker language I want the date-format "YYYY/MM/DD" and therefore I use 'ja-JP' in my app.module
providers: [
    {provide: MAT_DATE_LOCALE, useValue: 'ja-JP'},
]

I get the right date-format "YYYY/MM/DD" but the datepicker is displayed in japanese.

I would like to keep the default layout

Can you help me?


text:
Q: Django rest nested serializer not displaying fields I have a model Workflow and WorkflowLevel. Each workflow has many WOrkflow levels .Im trying to use nested serializer :
class WorkflowLevelSerializer
(serializers.ModelSerializer):
class Meta:
    model = WorkflowLevel
    fields = '__all__'

class
WorkflowSerializer
(serializers.ModelSerializer):

levels = WorkflowLevelSerializer(many=True)

class Meta:
    model = Workflow
    fields = ('id', 'name', 'description',
'tenant', 'levels')

models.py:
class Workflow(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=32, default=None, null=True)
description = models.CharField(max_length=100, default=None, null=True)
tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE, default=None,
null=False)
class Meta:
    unique_together = ('name', 'tenant',)

class WorkflowLevel(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
workflow = models.ForeignKey(Workflow, on_delete=models.CASCADE,
default=None, null=False)
level = models.IntegerField(default=None, null=False)
operation = models.CharField(max_length=32, default=None, null=False)
class Meta:
    unique_together = ('workflow', 'level',)

The levels field is not displaying in the workflow listAPI view .
Getting error:
Got AttributeError when attempting to get a value
for field `levels` on serializer
`WorkflowSerializer`.
The serializer field might be named incorrectly
and not match any attribute or key on the
`Workflow` instance.
Original exception text was: 'Workflow' object
has no attribute 'levels'.

A: You can define related_name in the Model like this:
 workflow = models.ForeignKey(Workflow, on_delete=models.CASCADE, related_name="levels", default=None, null=False)

I am using related_name='levels', so that in Serializer, it will use that reverse relationship name to fetch WorkflowLevel data from db.


text:
Q: Returning an object vs returning by reference an object Is there any difference between
vector<int> function(vector<int>& input) {
    // do something with input then return it
    input.push_back(3);
    return input;
}

and
vector<int>& function(vector<int>& input) {
    // do something with input then return it
    input.push_back(3);
    return input;
}

Does it matter? Since when you assign the return of the function to a new variable, the vector gets copied anyways:
vector<int>result = function(some_vector);

A: There is a difference, the second function can act as lvalue in a statement.
function(some_vector).push_back(4);

Here the vector is not copied, the original 'some_vector' is modified. Also, performance wise, this may make a big difference.

A: Using reference as the parameter allows to make return type of the function void
void function(vector<int>& input) {
    // do something with input then return it
    input.push_back(3);
    return input;
}

By the way member function push_back of class std::vector has return type void.
Returning reference to the vector allows to chain together the function call with other methods of class std::vector. For example
function( v ).push_back( value );


text:
Q: iOS Certificates and Provisioning Profile My client has a few apps in the app store that were submitted using a certain App Store profile which I have access to the account. We also have those apps installed Ad Hoc signed with the same Distribution Profile. Now I am taking care of one of this apps and I need to code sign to make a few changes and then submit it Ad Hoc for some testers. No one knows where the .developerprofile backup is. Can I revoke the existing certificate and recreate a new one without affecting the apps on the App Store. If I revoke, any other developer using this key pair will stop working, right? Any other problem I am not remembering. Can I revoke the certificate?
Thanks in advance.

A: Yes, you can safely revoke the developer and AdHoc distribution certificates without affecting any App Store apps. Be careful not to revoke any Push Notification certificates if your app uses push.
Generate a new certificate signing request on your machine and use that to generate the new certificates. Remember to edit the provisioning profiles after you create the new certificates, especially if you've added any additional devices to the provisioning list. Then download the new provisioning profiles and you should be good to go.
Any other developers (if they still have access) will be able to download the new profiles if they need them. If they also need to sign builds, they should generate their own keys/certificates as well for their developer certificates.


text:
Q: скажите знатоки, что с этим кодом не так, не даёт ожидаемый результат bonuses={'950895778':['1234','12000'], '912045858':{'1255':13000}, '911458384':{'7896':14000},
 '999987311':{'1111':15000},
   '975950701':{'2222':15000}}

bot=Bot(token=TOKEN)
dp=Dispatcher(bot)

@dp.message_handler(commands=['start', ])
async def send_welcome(message: types.Message):
    await message.answer("Hi enter your phone number")

@dp.message_handler()
async def echo_send(message:types.Message):
    if message.text in bonuses.keys():
        text=bonuses[message.text]
        await message.answer("Your discount card number")

@dp.message_handler()
async def score_send(message:types.Message):
    if message.text in text[0]:
        await message.answer(f"Your score:{text[1]}")
executor.start_polling(dp, skip_updates=True)

скажите пож что здесь ни так. спасибо.

A: Хоть я и не эксперт, но разве 2 функции с одинаковым @ не будут мешать друг другу?

Из очевидного:
text - локальная переменная, ты не можешь к ней так обращаться. Даже если сможешь, при использовании 2мя+ юзерами у тебя все сломается.
Обрати внимание, что в словаре у тебя в первом слоте очки в формате строки.


text:
Q: dbcontext does not contain a definition for 'Refresh' I'm working with the entity framework code first and am getting the following compilation error.
dbcontext does not contain a definition for 'Refresh'.  I have seen many examples where the Refresh method is being used.  But when i add the Refresh method to my dbcontext I get a complilation error.  I'm using the following namespaces.
using System.Data;
using System.Data.Entity;
using System.Data.Linq;

Am I missing one? I tried to look it up but did not find the namespace.

A: DbContext does indeed not have a Refresh() method.
The examples you saw were probably using ObjectContext.Refresh().
You can get one from the other:
 db = new MyDbContext())
 ...
 var ctx = ((IObjectContextAdapter)db).ObjectContext;
 ctx.Refresh();

This question has more about the details and differences.

A: LINQ-to-SQL has a confusingly similar DataContext class, that has this method.
Entity Framework: does not.


text:
Q: How do I add/remove attributes and methods? I am trying to develop a system where a user should be able to make modifications [add/remove attributes and methods] in the actual java file. While there are methods provided by API to create new methods/fields, how can we remove/destroy the ones that are not required.
I want to make a method
updatefile(file, newMethods, newAttributes)

*

*file is the java file that is going to be modified whose methods and attributes need to be removed.

*newMethods would now be methods of file

*newAttributes would be attributes of file
It is also possible that some entries of newMethods == some entries of original methods for which I will require a check; similarly for newAttributes.
How can this be done?

A: You need a bytecode manipulation library. Check the following: bcel, cglib, asm, javassist.
Though I agree with JBNizet that the requirements look a bit strange. There are already powerful IDEs that do that, and end users shouldn't normally temper with the class structure.

A: Your idea seem's similar to the JBoss forge project.
I think a possibility to remove methods must be based on Java method's signature declared in Java specs and a method return type.
For example: methodRemove(File file, String returnType, String methodName, String[] methodParametersTypes) will reference appropriate method to remove in file in case of only one class in file.


text:
Q: How to see wp-config file from WordPress dashboard? One of my client has lost all of his WordPress hosting details. The only thing he/she remembers is the WordPress dashboard's password. Is there a way I can see wp-config file from WordPress dashboard so I can examine where must the database and files be present? Thanks.

A: You could create a plugin for a dashboard widget, zip, upload and activate it.
Example:
<?php # -*- coding: utf-8 -*-
/**
 * Plugin Name: Configuration Dashboard Widget
 * Description: Show the current installation path and the content of the wp-config.php.
 * Version:     16.10.15
 * Required:    4.0
 * Author:      Thomas Scholz
 * Author URI:  http://toscho.de
 * License:     MIT
 * License URI: http://www.opensource.org/licenses/mit-license.php
 */

add_action( 'wp_loaded', function() {

    current_user_can( 'update_core' ) && add_action(
        'wp_dashboard_setup',
        function() {
            wp_add_dashboard_widget(
                'config_widget',
                'Configuration',
                function() {

                    $wp_config = FALSE;
                    if ( is_readable( ABSPATH . 'wp-config.php' ) )
                        $wp_config = ABSPATH . 'wp-config.php';
                    elseif ( is_readable( dirname( ABSPATH ) . '/wp-config.php' ) )
                        $wp_config = dirname( ABSPATH ) . '/wp-config.php';

                    if ( $wp_config )
                        $code = esc_html( file_get_contents( $wp_config ) );
                    else
                        $code = 'wp-config.php not found';

                    print '
Installation path: ' . ABSPATH
                          . "\n\n"
                          . $code
                          . '
';
                }
            );
        }
    );
});


text:
Q: Dismiss Modal NavigationController from pushed ViewController inside I have an iPad app and I'm using the storyboard. I'm presenting a modal view, which I wrap in a UINavigationController. It's a modal "Settings" view with it's own navigation.
I have a delegate setup to dismiss the modal view itself with a Done button in the Settings view which works fine, but I need to be able to dismiss it even after it has pushed another view when the user taps a setting.
So, basically a "cancel" button on the right side of the Navigation bar in the pushed views.
Instead of having to go back to the first "Settings" view to hit the done button.
I've tried setting up a second delegate for the pushed view without success:

A: Just add a bar button item and put this line in its action method:
[self.presentingViewController dismissViewControllerAnimated:YES completion:nil];

The presenting view controller will be the controller that presented the modal, not the navigation controller.


text:
Q: Nodejs - libuv non-blocking event callback I am trying to build an application using Node.Js which requires the native module support. I have used libuv library through the application and I was able to make most of the async methods work except for the part where I had to implement the progress event callback. I want to implement the progress event callback asynchronously and without blocking the Node.js event loop.
Here are code snippets:
native.cc
#include <node.h>
#include <uv.h>
#include "nbind/nbind.h"

using v8::Isolate;
using v8::HandleScope;

int FileProgressCallback(uint64_t const sent, uint64_t const total, void const *const data) {
    nbind::cbFunction cb = *((nbind::cbFunction *) data);
    cb(sent, total);
    return 0;
}

class WorkerFileTransfer {
public:
    WorkerFileTransfer(std::string path, nbind::cbFunction cb) :
            callback(cb), path(path) {};

    uv_work_t worker;
    nbind::cbFunction callback;

    bool error;
    std::string errorMsg;

    std::string path;
};

void FileTransferDone(uv_work_t *order, int status) {
    Isolate *isolate = Isolate::GetCurrent();
    HandleScope handleScope(isolate);

    WorkerFileTransfer *work = static_cast< WorkerFileTransfer * >( order->data );

    if (work->error) {
        work->callback.call<void>(work->errorMsg.c_str(), work->output);
    } else {
        ThirdPartyLibraryFileCopy(work->path.c_str(), FileProgressCallback, (const void *) &work->callback);
    }

    // Memory cleanup
    work->callback.reset();
    delete work;
}

void FileTransferRunner(uv_work_t *order) {
    WorkerFileTransfer *work = static_cast< WorkerFileTransfer * >( order->data );

    try {
        work->output = true;
    }
    catch (...) {
        work->error = true;
        work->errorMsg = "Error occured while executing the method...";
    }
}

void FileTransfer(const std::string path, nbind::cbFunction &callback) {
    WorkerFileTransfer *work = new WorkerFileTransfer(path, callback);

    work->worker.data = work;
    work->path = path;
    work->error = false;

    uv_queue_work(uv_default_loop(), &work->worker, FileTransferRunner, FileTransferDone);
}

function(FileTransfer);

test.js
FileTransfer(
  '/path/file.txt',
  (sent, total) => {

    console.log(`sent`, sent);
    console.log('total', total);
  }
);

I was able to achieve the file transfer done because of the below lines but the Node.Js event loop gets blocked here.
void FileTransferDone(uv_work_t *order, int status) {
   ...

   ThirdPartyLibraryFileCopy(work->path.c_str(), FileProgressCallback, (const void *) &work->callback);

   ...
}

When I move the line ThirdPartyLibraryFileCopy(work->path.c_str(), FileProgressCallback, (const void *) &work->callback); into the FileTransferRunner(uv_work_t *order) method then I am not getting any output in the javascript callback function.
How do I get the progress values in the javascript callback function, asynchronously, without blocking the Node.Js event loop?

A: As per the uv_queue_work documentation: http://docs.libuv.org/en/v1.x/threadpool.html#c.uv_queue_work The work callback (FileTransferRunner in your case) runs on the threadpool but the done callback (FileTransferDone in your case) runs on the loop thread. Thus, if you perform a blocking operation on the latter, you are going to block the loop.
If you want to send periodic progress reports this model won't work well for you. You could use an async handle uv_async_t and report progress using uv_async_send (which is thread-safe) from the work function. Or use multiple work requests to send chuncks (that will probably be slower).


text:
Q: clang: error: linker command failed with exit code 1 - library not found I have a bit of a problem building my project. I'm getting the bellow error for some reason since last week and cannot get rid of it.
Ld /Users/Nathan/Library/Developer/Xcode/DerivedData/SmartPic-elnbgmemojraijcotdlcskagbibq/Build/Products/Debug-iphoneos/SmartPic.app/SmartPic normal armv7
    cd "/Users/Nathan/Documents/Xcode Projects/SmartPic"
    setenv IPHONEOS_DEPLOYMENT_TARGET 4.3
    setenv PATH "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
    /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang++ -arch armv7 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.1.sdk
-L/Users/Nathan/Library/Developer/Xcode/DerivedData/SmartPic-elnbgmemojraijcotdlcskagbibq/Build/Products/Debug-iphoneos
-F/Users/Nathan/Library/Developer/Xcode/DerivedData/SmartPic-elnbgmemojraijcotdlcskagbibq/Build/Products/Debug-iphoneos -filelist /Users/Nathan/Library/Developer/Xcode/DerivedData/SmartPic-elnbgmemojraijcotdlcskagbibq/Build/Intermediates/SmartPic.build/Debug-iphoneos/SmartPic.build/Objects-normal/armv7/SmartPic.LinkFileList -dead_strip -miphoneos-version-min=4.3 -framework MobileCoreServices -framework SystemConfiguration -framework CFNetwork -framework EventKit -framework EventKitUI -framework MessageUI -lz -framework CoreLocation -framework UIKit -framework Foundation -framework CoreGraphics -framework QuartzCore -framework AVFoundation -framework CoreMedia -framework CoreMotion -framework CoreVideo -framework AudioToolbox -lDMReader -o /Users/Nathan/Library/Developer/Xcode/DerivedData/SmartPic-elnbgmemojraijcotdlcskagbibq/Build/Products/Debug-iphoneos/SmartPic.app/SmartPic

ld: library not found for -lDMReader
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I searched for information about the erorr, as, at one point, I had 6 other similar ones and the answer was to delete Library Search Paths in the Build Settings and that got rid of all but this last one. It was all fine until I imported some extra frameworks and classes. So not sure really what's caused it and how I can fix it.
I'm still fairly new to app development, so please try not to get too technical.
Any help is much appreciated, thank you.

A: Solved this by changing Library Search Paths in Build Settings to

./Classes "$(SRCROOT)/Classes"

Just in case anyone else finds this and wants to give it a try.
EDIT:
Just to add, I had this same problem again just now actually. And the reason it happened for me is because I changed the folder name that sits with the .xcodeproj file. So In a folder on my mac I had a directory called App Name and file called App Name.xcodeproj. I changed the directory App Name to something different and despite updating the build settings in xcode, still had the same problem. What I had to do was

*

*Right Click App Name.xcodeproj

*Click Show Package Contents

*Open project.pbxproj

*Then cmd + f (search) and enter App Name, I think there were just two places and they were 1/3 of the way down the page, called name and immediately below, path. Change them to the new directory name, save and reopen your project and all should be well.


text:
Q: LVM corruption, perhaps, or other hard drive boot error? Had been using Fedora Core 23 for a few months and then turned on the computer, entered my boot password, and instead of getting the user login screen as usual I got the following message after it had booted:
Generating "/run/initramfs/rdsosreport.txt"
Entering emergency mode
Exit the shell to continue
Type "journalctl" to view system logs.
:/#

I tried looking at the report and there were a number of lines in red, errors such as:
"Buffer error I/O dw dm-1"

"error {UNC}"

"Read FPDMA Queued"

"fsck failed error 4"

"res (long MAC address looking numbers, then) media error F"

"Blk update request I/O error dev/sda"

Towards the end of the file:

"Dependency failed for /sysroot"

"Dependency failed for INITRD root file system"

Not in exact order.
I tried running "fsck" ("/sbin/fsck") but it didn't do anything.
Anyone out there know if I'm just totally hosed and need to reinstall from scratch and hope I have backups?  Or is there any way to fix the LVM config or whatever else might be causing this?  S.O.S.
Thank you for any and all help...

A: You may want to boot into rescue mode and repair the disks.


text:
Q: WPF Web Application Not Showing I'm a beginner programmer and I have been using WPF in C# to make programs. I have recently read, though, that you can make WPF apps for browsers so I downloaded .net 5 but I still can't make them. When I select new project in visual studio community 2015, it only shows WPF but not WPF Browser. If anyone knows how to get it then please tell me. Thanks!

A: Sounds like you are looking for this:

A: To create a WPF Browser Application:

*

*Start Visual Studio.

*On the File menu, point to New, and then select Project.
The New Project dialog box appears.

*In the Installed Templates pane, expand Visual Basic or Visual C#,
and then select Windows.

*Above the middle pane, select the target framework from the
drop-down list.

*In the middle pane, select the WPF Browser Application template.
Note that the WPF Browser Application template in the .NET Framework 4 targets the Client Profile by default. For more information, see .NET Framework Client Profile.

*In the Name text box, specify a name for the project.

*In the Location text box, specify a folder to save the project.

*Click OK.
The WPF Designer for Visual Studio opens and displays Page1.xaml of the project.

*On the Debug menu, and select Start Debugging.
A browser window opens and displays the WPF browser application.

Some helpful links:
How to: Create a New WPF Browser Application (the above instructions) - https://msdn.microsoft.com/en-us/library/bb628663(v=vs.100).aspx
WPF XAML Browser Applications Overview - https://msdn.microsoft.com/library/aa970060(v=vs.100).aspx


text:
Q: OpenSUSE can only boot into Failsafe mode I installed the latest version of OpenSUSE and tried to install the driver for my touchpad. It would not install, so I installed it in this way:
zypper install ./filename_.rpm

After that my OpenSUSE will not load. When I boot and choose OpenSUSE in the Grub menu, I only see the OpenSUSE logo (about 4sec) and then only a black screen.
Failsafe mode is working.
Is it possible that the system isn't working due to the driver I installed? If yes, is there a way to "delete" the driver, which I installed or maybe remove it from startup?

A: Enter in Failsafe mode and remove the package, using rpm -e package_name.


text:
Q: Does SELECT start transaction in PL/SQL I was told that following code won't help me to check duplicity, because result might be different before SELECT and UPDATE statement.
PROCEDURE AddNew(Pname VARCHAR2, Pcountry VARCHAR2)
AS
    already_exists BOOLEAN;
BEGIN
    SELECT COUNT(*)>0 INTO already_exists FROM Publishers WHERE name=Pname;
    IF already_exists THEN
        RAISE_APPLICATION_ERROR(-20014,'Publisher already exists!');
    END IF;
    INSERT INTO Publishers(id,name,country)
        VALUES (NewPublisherId(),Pname,Pcountry);
END;

This post claims that SELECT starts a transaction:
Why do I get an open transaction when just selecting from a database View?

This part of documentation suggests otherwise:

A transaction implicitly begins with any operation that obtains a TX
  lock:

*

*When a statement that modifies data is issued

*When a SELECT ... FOR UPDATE statement is issued

*When a transaction is explicitly started with a SET TRANSACTION statement or the DBMS_TRANSACTION package

So? Does SELECT start a transaction or not?

A: The latter is true: https://docs.oracle.com/cloud/latest/db112/SQLRF/statements_10005.htm#SQLRF01705

A transaction implicitly begins with any operation that obtains a TX
  lock:

*

*When a statement that modifies data is issued

*When a SELECT ... FOR UPDATE statement is issued

*When a transaction is explicitly started with a SET TRANSACTION statement or the DBMS_TRANSACTION package

But it really does not matter, from the point of view of the main problem - to see if the record already exists in the database. Even if the transaction is explicitely startet using SET TRANSACTION ..., your code simply does not detect duplicate transactions !
Just do a simple test manually simulating the procedure in two simultaneous sessions and you will see:
CREATE TABLE Publishers(
    id int,
    name varchar2(100)
);

Let say that in session #1 the procedure begins at 8:00:00.0000:
SQL> Set transaction name 'session 1';

Transaction set.

SQL> select count(*) FROM Publishers where name = 'John';

  COUNT(*)
----------
         0

SQL> INSERT INTO Publishers(id,name) VALUES(1,'John');

1 row created.

Let say that in session #2 the same procedure begins at 8:00:00.0020, just after the insert was made in session 1, but still before the session#1 commits:
SQL> Set transaction name 'session 2';

Transaction set.

SQL> select count(*) FROM Publishers where name = 'John';

  COUNT(*)
----------
         0

The transaction #2 does not see uncommited changes done by the session 1, so the session 2 assumess that there is no record John, so it also inserts it to the table:
SQL>  INSERT INTO Publishers(id,name) VALUES(1,'John');

1 row created.

Now the session 1 commits:
SQL> Commit;

Commit complete.

and a few milliseconds later the session2 commits too:
SQL> Commit;

Commit complete.

And the final result is - a duplicated record even though the transaction has been explicitelly started:
select * from publishers;
        ID NAME
---------- ----------------------------------------------------------------------------------------------------
         1 John
         1 John

========== EDIT =================

You can avoid the duplicity by executing statement SET TRANSACTION
  ISOLATION LEVEL SERIALIZABLE in the beginning. – @Draex_

Many think that ISOLATION LEVEL SERIALIZABLE will solve the problem magically. Unfortunately, it will not help.
Let's see how it works on a simple example:
Session #1
SQL>  SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

Transaction set.

SQL> select count(*) FROM Publishers where name = 'John';

  COUNT(*)
----------
         0

SQL> INSERT INTO Publishers(id,name) VALUES(1,'John');

1 row created.

Session #2
SQL> SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

Transaction set.

SQL>  select count(*) FROM Publishers where name = 'John';

  COUNT(*)
----------
         0

SQL> INSERT INTO Publishers(id,name) VALUES(1,'John');

1 row created.

Session #1 again:
SQL> commit;

Commit complete.

SQL> select * from publishers;

        ID  NAME
----------  --------
         1  John

and back to session #2
SQL> commit;

Commit complete.

SQL> select * from publishers;
            ID  NAME
    ----------  --------
             1  John
             1  John

As you can see, the magic of ISOLATION LEVEL SERIALIZABLE did not work.


text:
Q: Background image makes different design html,
<select id="start_time" name="start_time" class="hasTimeEntry">
    <option value="00:00">00:00</option>
    <option value="00:30">00:30</option>
    <option value="01:00">01:00</option>
    <option value="01:30">01:30</option>
    <option value="02:00">02:00</option>
    <option value="02:30">02:30</option>
    <option value="03:00">03:00</option>
    <option value="03:30">03:30</option>
    <option value="04:00">04:00</option>
    <option value="04:30">04:30</option>
    <option value="05:00">05:00</option>
    <option value="05:30">05:30</option>
    <option value="06:00">06:00</option>
    <option value="06:30">06:30</option>
    <option value="07:00">07:00</option>
    <option value="07:30">07:30</option>
    <option value="08:00">08:00</option>
    <option value="08:30">08:30</option>
    <option value="09:00">09:00</option>
    <option value="09:30">09:30</option>
    <option value="10:00">10:00</option>
    <option value="10:30">10:30</option>
    <option value="11:00">11:00</option>
    <option value="11:30">11:30</option>
    <option value="12:00">12:00</option>
    <option value="12:30">12:30</option>
    <option value="13:00">13:00</option>
    <option value="13:30">13:30</option>
    <option value="14:00">14:00</option>
    <option value="14:30">14:30</option>
    <option value="15:00">15:00</option>
    <option value="15:30">15:30</option>
    <option value="16:00">16:00</option>
    <option value="16:30">16:30</option>
    <option value="17:00">17:00</option>
    <option value="17:30">17:30</option>
    <option value="18:00">18:00</option>
    <option value="18:30">18:30</option>
    <option value="19:00">19:00</option>
    <option value="19:30">19:30</option>
    <option value="20:00">20:00</option>
    <option value="20:30">20:30</option>
    <option value="21:00">21:00</option>
    <option value="21:30">21:30</option>
    <option value="22:00">22:00</option>
    <option value="22:30">22:30</option>
    <option value="23:00">23:00</option>
    <option value="23:30">23:30</option></select>

css,
#start_time {
background: url(/images/startclock_icon_small.gif) no-repeat scroll 1px 1px;
text-indent: 20px;
border-width: 1px 1px 1px 1px;
width: 142px;
}

if i run this it shows like this,

as you can see in the pic, if i put the
background:url attributes

it shows a different design that i dont want.
i want the same design like the right textfield.
if i comment the background : url it shows fine
however, i need this img icon as a background img :(
any good idea????
========================================
fiddle demo
DEMO
=================================
still design that i don't want

A: Try this :-
#start_time {
   background: url(/images/startclock_icon_small.gif) no-repeat scroll 1px 1px !important;

}

Your hasTimeEntry class is overriding your background property.

Put this inline style on element which isn't working.
style="border-color: #ccc !important;"


text:
Q: How to create a program i n Java which gets all combinations of 1 and 2 of given number of digits Let's say n= 7, so I need to display all possible combinations of 7 digits made out of 1s and 2s:
1111111
1111112
1111121
1111211
1112111
.......
2222222
Here is my code, but it is hardcoded nested 7 times loops. So my count=128 which is 2^7 But how to make it programmatically for n number of times nesting? I think it needs some recursion, but how to do it?
int count = 0;
    for (int j = 1; j<=2; j++) {
        for (int z= 1; z<=2; z++) {
            for (int i = 1; i<=2; i++) {
                for (int k = 1; k<=2; k++) {
                    for (int l= 1; l<=2; l++) {
                        for (int m = 1; m<=2; m++) {
                            for (int y = 1; y<=2; y++) {
                                count++;

                                System.out.println(count+":"+j+z+i+k+l+m+y+",");

                            }
                        }
                    }
                }
            }
        }
    }

A: Usually, "all combinations of N symbols" is the same than "counting in base N".
Since you have two symbols, even easier. Count from 0 to X, get the binary representation of each number, replace 0 by 2. Once the binary representation gets longer than the number of values you desire, stop.
Do not forget to add leading 2 to numbers which are too short.

A: I quite like an obfuscated version .... ;-) :
    final int l = 7;
    long m = 1 << l;
    while (--m >= 0) {
        int b=l;
        while (--b >= 0) {
            System.out.print(((m >> b)& 1 ) + 1);
        }
        System.out.println();
    }
}

Edit:
I should add a description of the above.... All I do is count down from 2^7 - 1 and then print the bits set in each value (printing 2 for bit-value 1, and printing 1 for bit-value 0);

A: Use recursion. You should plan to pass in the partially-built string, and the number of digits remaining. I will concatenate strings here, though StringBuilders should generally be used.
public static void printOutString(int levelsRemaining, String current){
    if(levelsRemaining==0) System.out.println(current);
    else{
        printOutString(levelsRemaining-1, current+"1");
        printOutString(levelsRemaining-1, current+"2");
    }
}

You can also use an iterative approach:
public static ArrayList<String> getAllStrings(int length){
    ArrayList<String> prev;
    for(int i=0; i<length; i++){
        ArrayList<String> newL=new ArrayList<String>;
        for(String s:prev){
            newL.add(s+"1");
            newL.add(s+"2");
        }
        prev=newL;
    }
    return prev;
}

A: Here's a simple way to get all permutations of some domain, ie you would calling:
permute(3,"12", ""); yields:

111 112 121 122 211 212 221 222

public void permute(int length, String domain, String result)
    {
        if (length == 0)
        {
            System.out.println(result);
        }
        else
        {
            for (int i = 0; i < domain.length(); i++)
                permute(length-1, domain, result + domain.charAt(i));
        }
    }


text:
Q: is it possible to write a generic method to select date from a datepicker calender in selenium Let's suppose I have a date-picker calendar when I click on that a calendar popup will show up in which I need to select year then month then date. But I need a generic method so that whenever I click on that calendar when the calendar popup shows up. If I call a method that would select the date for me from the calendar. Is it possible to write a generic method to select a date from a date-picker calendar in selenium by just passing the desired date? I am doing it separately by selecting year then month then date like that. I have tried several methods as well.
SimpleDateFormat format = new SimpleDateFormat("dd-mm-yyyy");
try {
    selectDate(format.parse(ConfigurationManager.getBundle().getString("dates.holiday")));
} catch (ParseException e) {
    e.printStackTrace();
}

public void selectDate(Date date) {
}


text:
Q: Selenium - Webelement selection I am doing automation using Selenium.The site that I am automating has the following html elements. From Selenium I want the grab the "0400320908" and "0400 962887".
I tried below code:-
WebElement mobElement = driver.findElement(By.xpath("//i[contains(text(),mobile)]"));

but the webdriver is grabbing only the first number i.e. 0400320908 but not the other number. Could you please advise what mistake I am doing.
Regards,
Badari

Mobile
0400 320 908


text:
Q: Create tag from using ASP Tokken Input I can easily create tags using ASPTokkenInput and saved in database in the form of string.
For example : I created 3 tags like JAVA  C#  Entity
and saved these tags in database like java,c#,entity
But after fetching using sql query from database, I need to create this string back in the form of TAGS in ASPTokenInput.
How can I create tags from .cs page in C#?
Here is the code for creating tags
ASPX Page
<ati:ASPTokenInput ID="StateNameBox" runat="server"
 RequestHandlerPath="SearchItemList.aspx?type=StateName"
 OnListChanged="StateName_ListChanged" Theme="facebook"
 PostbackOnItemAdded="True" PostbackOnItemRemoved="True"
 HintText="Start Typing StateName..." PreventDuplicates="True"/>

 <asp:ListBox ID="StateNameList" runat="server" Width="100%" Height="150px"
 style="display:none;" />

.csPage
  protected void StateName_ListChanged(object sender, ASPTokenInput.ListChangedEventArgs e)
 {
        if (e.Action == ASPTokenInput.ListChangeActions.Add)
            StateNameList.Items.Add(e.Item.name);
        else
        {
            for (int n = StateNameList.Items.Count - 1; n >= 0; --n)
            {
                string removelistitem = e.Item.name;
                if (StateNameList.Items[n].ToString().Contains(removelistitem))
                {
                    StateNameList.Items.RemoveAt(n);
                }
            }
        }
   }

Buttonclick to save in database
String state = "";
for (int j = 0; j < StateNameList.Items.Count; j++)
{
   state = (StateNameList.Items[j].Text)+","+state;
}

Save state string in to the database
Now, i am fetch this string from database and need to create tags in ASPTokenInput
 conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
 objsqlconn = new SqlConnection(conn);

 objsqlconn.Open();
 objcmd = new SqlCommand("Select state from StateName where stateId='1'");
 sqlread = objcmd.ExecuteReader();

 String statename = "";
  if (sqlread.Read())
  {
    statename = sqlread.GetString(0);
  }

 String[] statelist = statename.Split(',');
 for(int i=0;i<statelist.Length;i++){

    //now here what i want to do for createing tags again in ASPTokenInput

 }