text:
Q: row ID error after deleting a row in Android SQLite database I have created a program based on this Deleting entry from SQLite database tutorial.
Everything works fine except one thing. While I have added new rows to the SQLite Database it worked perfectly, but as soon as I deleted one of these rows, the rest of the ROWID haven't updated itself, just continued counting as usually.
For example I have added five rows, than I deleted the third one so the others should rewrite themselves to 1,2,3,4. But the ROWIDs remained: 1,2,4,5
I was looking for this problem on the Internet, and I found out that I should somehow put the remained rows to a new database and then back and it should be all right. But I have never worked with SQL before, so I don't know the code how to fix the problem.
Could you please tell me, how to solve my problem?
Here is my database code:
public class HotOrNot {

public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "persons_name";
public static final String KEY_HOTNESS = "persons_hotness";

private static final String DATABASE_NAME = "HotOrNotdb";
private static final String DATABASE_TABLE = "peopleTable";
private static final int DATABASE_VERSION = 1;

private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;

private static class DbHelper extends SQLiteOpenHelper {

    public DbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
                KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                KEY_NAME + " TEXT NOT NULL, " +
                KEY_HOTNESS + " TEXT NOT NULL);"

                );
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
        onCreate(db);
    }

}
public HotOrNot(Context c){
    ourContext = c;
}

public HotOrNot open() throws SQLException{
    ourHelper = new DbHelper(ourContext);
    ourDatabase = ourHelper.getWritableDatabase();
    return this;
}
public void close(){
    ourHelper.close();
}

public long createEntry(String name, String hotness) {
    // TODO Auto-generated method stub
    ContentValues cv = new ContentValues();
    cv.put(KEY_NAME, name);
    cv.put(KEY_HOTNESS, hotness);
    return ourDatabase.insert(DATABASE_TABLE, null, cv);
}

public String getData() {
    // TODO Auto-generated method stub
    String[] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_HOTNESS};
    Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
    String result = "";

    int iRow = c.getColumnIndex(KEY_ROWID);
    int iName = c.getColumnIndex(KEY_NAME);
    int iHotness = c.getColumnIndex(KEY_HOTNESS);

    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
        result = result + c.getString(iRow) + " " + c.getString(iName) + " " + c.getString(iHotness) + "\n";
    }
    return result;
}

public String getName(long l) throws SQLException{
    // TODO Auto-generated method stub
    String[] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_HOTNESS};
    Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "=" + l, null, null, null, null);
    if(c != null){
        c.moveToFirst();
        String name = c.getString(1);
        return name;
    }
    return null;
}

public String getHotness(long l) throws SQLException{
    // TODO Auto-generated method stub
    String[] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_HOTNESS};
    Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "=" + l, null, null, null, null);
    if(c != null){
        c.moveToFirst();
        String hotness = c.getString(2);
        return hotness;
    }
    return null;
}

public void updateEntry(long lRow, String mName, String mHotness) throws SQLException{
    // TODO Auto-generated method stub
    ContentValues cvUpdate = new ContentValues();
    cvUpdate.put(KEY_NAME, mName);
    cvUpdate.put(KEY_HOTNESS, mHotness);
    ourDatabase.update(DATABASE_TABLE, cvUpdate, KEY_ROWID + "=" + lRow, null);
}

public void deleteEntry(long lRow1) throws SQLException{
    // TODO Auto-generated method stub
    ourDatabase.delete(DATABASE_TABLE, KEY_ROWID + "=" + lRow1, null);
}
}

Thanks in advance!

A: The ID (primary key)in database is unique for each record and it is assigned once.
They can not be changed later for any record.
So if you delete any record then other rowId will not get affected.
The result you are getting is Expected Result. Don't Worry.


text:
Q: adMob contentURL parameter purpose Reading the official documentation regarding the adMob contentURL parameter it is not clear what is the purpose of passing a URL.
The doc says:

Content URL
Applications that monetize content matching a webpage's content may pass a content URL for keyword targeting.
For example, if your app serves blog articles and is requesting an ad while showing content from the article http://googleadsdeveloper.blogspot.com/2013/10/upgrade-to-new-google-admob.html, then you can pass this URL to target relevant keywords.

Will they fetch the page in realtime or use historical data to look for keywords to use?

A: If you're asking if AdMob will, at the exact moment of each request, go out and hit the web page to get its contents, the answer is no. People hate waiting for ads to load, and it would add too much latency to do something like that.
Google constantly crawls and recrawls the web for its search engine, though. That's the data that gets used. So it's historical in a sense, but not ancient. :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: When your executable behaves differently when invoked with ./ I just compiled some (parallelised) code in C, and have found the bewildering issue that it runs fine if invoked with
./executable

and when I try to run it "normally", i.e.
executable

I started hitting the error message:
unrecognised symbol: ompi_mpi_int

The message was the same one I had received before recompiling the executable (I had scp'ed it across from an older machine, and was recompiling it for use on the new cluster)
Why does my code run differently when invoked with "/." and without?
Any help would be greatly appreciated.


text:
Q: Strange error about type defined multiple times with PCL I have Xamarin.Android, Xamarin.iOS and Windows Phone 8 applications, both referencing common PCL library. Inside this library I am using HttpClient, and because WP8, I need nuget package Microsoft.Net.Http.2.2.22
Without enabling compression on HttpClient everything works fine on all 3 platforms. However, after changing code to
var handler = new HttpClientHandler();
if (handler.SupportsAutomaticDecompression)
{
    handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
}
httpClient = new HttpClient(handler);

there is build error with the library on iOS (both Android and WP works fine with this) telling me about multiple definition of DecompressionMethods. What is strange - the second assembly mentioned in error is System.Net.Primitives.dll - which DOES NOT contain definition of DecompressionMethods (i even checked in ILSpy).
Of course, I tried clean solution, rebuild, close/open Xamarin Studio etc...
Error :
MyApiHttpClient.cs(30,50): error CS0433: The imported type  `System.Net.DecompressionMethods' is defined multiple times
/Users/vtoth/myprototype/Services/CommonServices/../../packages/Microsoft.Net.Http.2.2.22/lib/portable-net40+sl4+win8+wp71+wpa81/System.Net.Http.Primitives.dll (Location of the symbol related to previous error)
/Library/Frameworks/Mono.framework/Versions/3.2.6/lib/mono/xbuild-frameworks/.NETPortable/v4.5/Profile/Profile49/System.Net.Primitives.dll (Location of the symbol related to previous error)
Task "Csc" execution -- FAILED
Done building target "CoreCompile" in project "/Users/vtoth/myprototype/Services/CommonServices/CommonServices.csproj".-- FAILED

EDIT:
Version info about dev environment:

=== Xamarin Studio ===
Version 4.2.4 (build 35) Installation UUID:
  (...) Runtime:    Mono 3.2.6
  ((no/9b58377)     GTK+ 2.24.23 (Raleigh theme)
Package version: 302060000
=== Apple Developer Tools ===
Xcode 5.1.1 (5085) Build 5B1008
=== Xamarin.iOS ===
Version: 7.2.1.42 (Business Edition) Hash: 773c77c Branch:  Build
  date: 2014-04-18 15:39:16-0400
=== Xamarin.Mac ===
Xamarin.Mac: Not Installed
=== Xamarin.Android ===
Version: 4.12.3 (Business Edition) Android SDK:
  /Users/vtoth/Library/Developer/Xamarin/android-sdk-mac_x86    Supported
  Android versions:
        2.1   (API level 7)
        2.2   (API level 8)
        2.3   (API level 10)
        3.1   (API level 12)
        4.0   (API level 14)
        4.0.3 (API level 15)
        4.3   (API level 18)
        4.4   (API level 19) Java SDK: /usr java version "1.6.0_65" Java(TM) SE Runtime Environment (build 1.6.0_65-b14-462-11M4609) Java
  HotSpot(TM) 64-Bit Server VM (build 20.65-b04-462, mixed mode)
=== Build Information ===
Release ID: 402040035 Git revision:
  1173cb1c45bc56cb702e82cd21a7c9d0cea4acbf Build date: 2014-04-17
  13:45:52-04 Xamarin addins: 53bde0041263928e8bd64686f5ca5a8e4338dd76
=== Operating System ===
Mac OS X 10.9.2

A: After discussing in the comments, it seems to me that you are running an old version of Xamarin Studio, Xamarin.iOS, and Xamarin.Android.
Please make sure you have at least the following stable versions or newer (which are available on the stable channel currently:

*

*Xamarin Studio:  5.0

*Mono: 3.4.0

*GTK#: 2.24.23

*Xamarin.iOS: 7.2.3.39

*Xamarin.Android: 4.12.4

*XCode: 5.1.1

Please try updating and your problems should go away, plus you'll get a much nicer version of Xamarin Studio to work with!


text:
Q: Remove white space from table_name in MySql? Ex:
Server SQL mode. If the ANSI_QUOTES SQL mode is enabled, you can quote identifiers withdouble quotes (although backticks still are permitted).
CREATE TABLE "my table" ("my-int-column" INT);

I have tried the drop, and described like this:
describe 'my table';
drop table 'my table';

describe my table;
drop table my table;

Syntax error.


text:
Q: Parse youtube links with feedjira I use rails 5.2, feedjira 2.1.0
If I parse youtube link
I have this error:
undefined method `image' for #Feedjira::Parser::AtomYoutubeEntry:0x00007fa14be348d0
other links work
my code:
def self.add_entries(entries, stream_id)
      entries.each do |entry|
          unless  FeedEntry.where(guid: entry.id).exists?
            FeedEntry.create!(
              :name          => entry.title,
              :url           => entry.url,
              :summary       => entry.summary,
              :published_at  => entry.published,
              :enclosure_url => entry.image,
              :enclosure_type => entry.enclosure_type,
              :guid          => entry.id,
              :source_id => stream_id
            )
          end
      end
end

How to make to parse all links?

A: You are expecting an image attribute but there is no attribute called image in AtomYoutubeEntry.
Have a look at Feedjira on github. There is for example a media_thumbnail_url which you could use.


text:
Q: Golang: consume items for multiple workers from channel in `case` statement My consumer (run from main) supports context cancellation and reading from a channel via case statement. I can shutdown the consumer with the context, that works fine. However, when I spawn several workers in one case statement, every worker is given the same job (message) from jobsChan, which is not what I want:
func (app *App) consumer() {
    for {
        select {
        case <-app.ctx.Done():
            app.infoLog.Print("Caught SIGINT, stopping.")
            app.wg.Wait()
            app.doneChan <- struct{}{} # main uses this channel to block itself until all goroutines are stopped
            app.infoLog.Print("Shutting down the consumer...")
            return
        case job := <-app.jobsChan:
            // PROBLEM here: wrong, each worker is given the same job
            for workerNumber := 0; workerNumber < app.config.workers; workerNumber++ {
                app.wg.Add(1)
                go app.workerFunc(workerNumber, job)
            }
        }
    }
}

func (app *App) workerFunc(id int, job Job) {
    defer app.wg.Done()

    ... actual worker code here ...
}

How can I rewrite this code so that I can keep select for app.ctx.Done channel and at the same time can spawn workers so that each worker picks next message from the channel as a Job? I need to keep for/select to listen for ctx cancellation but at the same time I need to spawn X workers reading messages from jobsChan in the consumer. Is this possible?
The only alternative that comes to mind is passing channel directly into spawned workerFunc and have another for job := range app.jobsChan in the workerFunc. But then the whole case job := <-app.jobsChan: in the consumer becomes pointless and I am not sure how to rewrite it.
To clarify: When I run the app, I expect every worker to have a new job id pulled from the jobsChan - but they all process the same, e.g. 1, then they all process the next one, e.g. 2
#wrong
Worker 0: start processing item 1
Worker 2: start processing item 1
Worker 1: start processing item 1

A: Your existing code explicitly assigns the same job to all the workers. If you have a fixed number of workers, create goroutines for them (during initialization), and have them listen to a channel:
for workerNumber:0;workerNumber<app.config.workers;workerNumber++ {
   go app.workerFunc(ctx,workerNumber,app.jobsChan)
}

In each worker, simply check the jobQueue and the context cancellation.
In other words, you don't need the consumer, pass jobs directly to the workers.


text:
Q: Show that $f(A ∩ B) ⊆ f(A) ∩ f(B)$, can the relation be improved to equality? I have the following question:

Let $A,B$ be two subsets of a set $X$, and let $f : X → Y$ be a function. Show that $f(A ∩ B) ⊆ f(A) ∩ f(B)$. Is it true that the $⊆$ relation can be improved to $=$?

While I know that in these type of questions I should start by going back to the formal definition of everything stated and work from there I am having trouble stating these formally.
Usually a function can be written as ${\displaystyle \{(x,f(x)):x\in X\}}$ but how do I alter this to show that $x \subseteq A ∩ B$
Does the following work: ${\displaystyle \{(x,f(x)):x\in (A ∩ B) \subseteq X\}}$
In case it does, here is attempt:
${\displaystyle \{(x,f(x)):x\in (A ∩ B) \subseteq X\}}$
is equivalent to: ${\displaystyle \{(x,f(x)):x\in A \subseteq X \wedge x\in B \subseteq X\}}$
which in turn is equivalent to:  ${\displaystyle \{(x,f(x)):x\in A  \subseteq X\}} \wedge  {\displaystyle \{(x,f(x)):x\in B  \subseteq X\}}$
which is equivalent to $f(A) ∩ f(B)$
The biggest flaw in my work is that I am working as if I am showing equality, can someone guide me or give hints?

A: The first half of proving the containment is addressed by @devianceee's comment. Listed here (plz give his/her comment upvote if this was useful to you: Prove $f(S \cap T) \subseteq f(S) \cap f(T)$ )
The second half of the question asks about improving the containment to an equality.
I don't believe the containment can be improved to an equality.
Consider $f(x) = x^2$  On the set $A = \lbrace -1, 2 \rbrace$ and $B=\lbrace 1, 2 \rbrace$
We have that $A \cap B = \lbrace 2 \rbrace$
So $f(A \cap B) = \lbrace 4 \rbrace$
Now $f(A) = \lbrace 1,4 \rbrace$ and similarly $f(B) = \lbrace 1,4 \rbrace$
so $f(A) \cap f(B) =\lbrace 1,4 \rbrace$
Clearly $\lbrace 1,4 \rbrace \ne \lbrace 4 \rbrace$ so we do NOT have that
$ f(A) \cap f(B) = f(A \cap B)$
In general.
Interesting questions to ask:
What conditions on $f$ and the sets $A,B$ need to be added so that equality again becomes possible? How can we play around with those conditions. This can lead to an interesting rabbit hole I believe.


text:
Q: Javascript jslint says spell_img is used before being declared What is wrong with my code, I checked it with an online jslint and it says spell_img is used before being declared?
spell_img = new Image();
spell_img.src = '/images/standard/spellcheck.gif';
spell_img.setAttribute('title',_lang_spellcheck );

function find_text_boxes()
{
    myforms = document.forms;
    for( i=0;i < myforms.length; i++ )
    {
        textareas = myforms[i].getElementsById('textarea');
        for( y=0; y < textareas.length; y++ )
        {
            spelllink = document.createElement('a');
            spelllink.setAttribute('href',"javascript:spellCheck(" + i + ", '" + textareas[y].name + "')");
            spelllink.appendChild( spell_img.cloneNode(true) );
            textareaParent = textareas[y].parentNode;
            textareaParent.insertBefore( spelllink, textareas[y].nextSibling );
        }
    }
}

A: Step 1: declare variables. In JavaScript, this is done using var. var scopes the variable to the scope where the var was found; scopes in JavaScript are (currently) function-based.
var spell_img = new Image();
spell_img.src = '/images/standard/spellcheck.gif';
spell_img.setAttribute('title',_lang_spellcheck );

function find_text_boxes()
{
    var myforms = document.forms;
    for( var i=0;i < myforms.length; i++ )
    {
        var textareas = myforms[i].getElementsById('textarea');
        for( var y=0; y < textareas.length; y++ )
        {
            var spelllink = document.createElement('a');
            spelllink.setAttribute('href',"javascript:spellCheck(" + i + ", '" + textareas[y].name + "')");
            spelllink.appendChild( spell_img.cloneNode(true) );
            textareaParent = textareas[y].parentNode;
            textareaParent.insertBefore( spelllink, textareas[y].nextSibling );
        }
    }
}

Step 2: getElementsById is not a thing that exists. It's getElementsByTagName.
var spell_img = new Image();
spell_img.src = '/images/standard/spellcheck.gif';
spell_img.setAttribute('title',_lang_spellcheck );

function find_text_boxes()
{
    var myforms = document.forms;

    for( var i = 0; i < myforms.length; i++ )
    {
        var textareas = myforms[i].getElementsByTagName('textarea');

        for( var y = 0; y < textareas.length; y++ )
        {
            var spelllink = document.createElement('a');
            spelllink.setAttribute('href',"javascript:spellCheck(" + i + ", '" + textareas[y].name + "')");
            spelllink.appendChild( spell_img.cloneNode(true) );
            textareaParent = textareas[y].parentNode;
            textareaParent.insertBefore( spelllink, textareas[y].nextSibling );
        }
    }
}

Step 3: wait, why are you even getting forms first?
var spell_img = new Image();
spell_img.src = '/images/standard/spellcheck.gif';
spell_img.setAttribute('title',_lang_spellcheck );

function find_text_boxes() {
    var textareas = document.getElementsByTagName('textarea');

    for(var i = 0; i < textareas.length; i++) {
        var spelllink = document.createElement('a');
        spelllink.setAttribute('href',"javascript:spellCheck(" + i + ", '" + textareas[y].name + "')");
        spelllink.appendChild( spell_img.cloneNode(true) );
        textareaParent = textareas[y].parentNode;
        textareaParent.insertBefore( spelllink, textareas[y].nextSibling );
    }
}

Step 4: javascript: URIs are bad. Inline JavaScript is bad. Inline JavaScript in inline URL in JavaScript? That's really bad and is kind of like eval and all sorts of things. Create a function and make spellCheck accept an element object, not form index, yuck. title is a property as well as an attribute (like src), by the way:
var forEach = Array.prototype.forEach;

var spell_img = new Image();
spell_img.src = '/images/standard/spellcheck.gif';
spell_img.title = _lang_spellcheck;

function find_text_boxes() {
    var textareas = document.getElementsByTagName('textarea');

    forEach.call(textareas, function(textarea) {
        var spellLink = document.createElement('a');

        spellLink.href = "#";
        spellLink.addEventListener("click", function(e) {
            e.preventDefault();
            spellCheck(textarea);
        }, false);

        spellLink.appendChild(spell_img.cloneNode(true));

        textarea.parentNode.insertBefore(spelllink, textareas[y].nextSibling);
    });
}

If you need to be compatible with old IE without shivs, that's doable:
var spell_img = new Image();
spell_img.src = '/images/standard/spellcheck.gif';
spell_img.title = _lang_spellcheck;

function find_text_boxes() {
    var textareas = document.getElementsByTagName('textarea');

    for (var i = 0; i < textareas.length; i++) {
        (function(textarea) {
            var spellLink = document.createElement('a');

            spellLink.href = "#";
            spellLink.onclick = function() {
                spellCheck(textarea);
                return false;
            };

            spellLink.appendChild(spell_img.cloneNode(true));

            textarea.parentNode.insertBefore(spelllink, textareas[y].nextSibling);
        })(textareas[i]);
    });
}

You can really put the cherry on top with some event delegation.
function addSpellLink(textarea) {
    var link = document.createElement("a");
    link.className = "spell-link";
    link.href = "#";

    link.appendChild(spell_img.cloneNode(true));

    textarea.parentNode.insertBefore(link, textarea.nextSibling);
}

function findTextboxes() {
    Array.prototype.forEach.call(document.getElementsByTagName("textarea"), addSpellLink);
}

document.addEventListener("click", function(e) {
    if (e.target.classList.contains("spell-link")) {
        e.preventDefault();
        spellCheck(e.previousElementSibling);
    }
}, false);

A: var spell_img = new Image();//place any one of these right at the top of your scope.

or
window.spell_img = new Image();//replace first line


text:
Q: What is a "closing gown"?
There were fringed bolero jackets in abundance and multiple rose-bedecked references to the so-intense-as-to-hurt romantic aesthetic of Frida Kahlo. The closing gown was painted by Romero Britto as a tribute to the trailblazing Mexican artist. (source)

Google seems to show this is not a thing. But then what does "closing" mean here?

A: The closing gown is the last gown (dress) to be displayed in the fashion show. "Closing" as an adjective can be used about something that comes at or near the end of an event.

adjective [ before noun ]
coming near the end of a speech, event, activity, etc.:
In his closing remarks, the chairman thanked everyone who had helped.
the closing ceremony of the OIympic Games

Closing (Cambridge Dictionary)

closing
  ADJECTIVE
  attributive
Bringing something to an end; final.
'the closing stages of the election campaign'
'Nellie's closing words'

Closing (Oxford Dictionaries)


text:
Q: Cordova + Android - android-windowSoftInputMode adjustPan not working I'm using Cordova 5.4.0 and I have this in my config.xml:
<preference name="fullscreen" value="false" />
<preference name="android-windowSoftInputMode" value="adjustPan" />

but after building, in my AndroidManifest.xml there still is
android:windowSoftInputMode="adjustResize"

Why is it not working? And how can I solve it?

A: I found a simple solution using the edit-config tag which is built into cordova since v6.4.0. My config.xml now looks like this and the keyboard no longer resizes the viewport!
<?xml version='1.0' encoding='utf-8'?>
<widget id="com.example.hello" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>HelloWorld</name>
    <!-- ... -->
    <edit-config file="AndroidManifest.xml" mode="merge" target="/manifest/application/activity[@android:name='MainActivity']">
        <activity android:name="MainActivity" android:windowSoftInputMode="adjustPan" />
    </edit-config>
    <!-- ... -->
</widget>

Hint: When experimenting to get this working, I made some accidental changes to my AndroidManifest.xml. You can reset this easily be removing and re-adding the android platform to your cordova project like so: cordova platform rm android && cordova platform add android.

A: The android-windowSoftInputMode preference seems to be supported by Phonegap only, not Cordova.
Workaround 1 (Cordova 6.4+): use edit-config
Make sure the xmlns:android="http://schemas.android.com/apk/res/android" namespace attribute is included in the widget element and add an edit-config element:
<widget xmlns:android="http://schemas.android.com/apk/res/android" ...>
    ...
    <edit-config file="AndroidManifest.xml" target="/manifest/application/activity[@android:name='MainActivity']" mode="merge">
        <activity android:windowSoftInputMode="adjustPan" />
    </edit-config>
    ...
</widget>

Workaround 2 (prior to Cordova 6.4): use a plugin
Add the cordova-custom-config plugin:
cordova plugin add cordova-custom-config

Add the following preference:
<platform name="android">
    <preference name="android-manifest/application/activity/@android:windowSoftInputMode" value="adjustPan" />
    ...
</platform>

Workaround 3: add a before_build hook
Add the following hook to config.xml:
<hook type="before_build" src="scripts/appBeforeBuild.js" />

Add a file appBeforeBuild.js to the scripts directory with the following content:
#!/usr/bin/env node

var fs = require('fs');
var path = require('path');

var pathToManifest = path.join(__dirname, '../platforms/android', 'AndroidManifest.xml');
if(fs.existsSync(pathToManifest)) {
    var config = fs.readFileSync(pathToManifest, 'utf8');

    var result = config.replace(/(android:windowSoftInputMode=").*?(")/, '$1adjustPan$2');
    fs.writeFileSync(pathToManifest, result, 'utf8');

    console.log('Set android:windowSoftInputMode to adjustPan');
}
else {
    console.log('Could not find AndroidManifest to set android:windowSoftInputMode');
}

This script will use Node to lookup the AndroidManifest and do a regex replace on the android:windowSoftInputMode attribute (first occurrence only).

A: Try this one

*

*Index.html
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width, height=device-height">

*config.xml
<preference name="android-windowSoftInputMode" value="adjustResize|adjustPan" />

A: It looks like you are changing the wrong AndroidManifest.xml.
In your application, under \platform\android... you will find the .xml file, you have to change that one.

A: You can also use the cordova-custom-config

cordova plugin add cordova-custom-config

and add this to your config.xml

<platform name="android">
   <preference name="android-manifest/application/activity/@android:windowSoftInputMode" value="adjustPan" />
</platform>

A: I had the same problem and it turned out to be a problem with using display: flex for the container of the inputs. Changing the CSS so the container was not flexbox based solved the keyboard / input / scroll interaction problem on Android for me.


text:
Q: prompt validation if null not working inside funcion/while/try javascript as said on title, validating the prompt if is null (inpname variable) inside the func/while/try wont work. output = {}
meanwhile the testing i did outside works fine.
check the code below please. what did i do wrong?

//works
let test = prompt("testing","aasdasd");
if (test === null) {
  console.log("cancel");
}
else {
  console.log("ok");
}

let inpname;
//do not work
let func = () => {
  while (true) {
    try {
    inpname = prompt("name ", "name here");

    if (inpname.length > 10 || inpname.length <= 3) {
      throw "Your name must be at least 10 characters long, but not less than 4";
    }

    else if ( inpname != inpname.match(/^[a-zA-Z]+$/)) {
      throw "A-Z characters accepted only!";
    }

    //problem here!
    else if (inpname === null) {
      throw "cant cancel";
    }

    else {
      console.log("success");
      break
     }
  }
    catch (err) {
      console.log(err);
      break
    }
  }
}
func();

A: The console outputting {} instead of the exception seems to be a bug in Stack-snippets.  You would get more correct output using console.error.
That being said, the issue you're seeing is in part caused because you're not checking that impname is null before you attempt to dereference it.
Changing the ordering of your error checking would solve the problem (Although stack-snippets is still not going to report exceptions as they happen, which is not the behavior you get in a browser)

let func = () => {
    while(true) {
        var inpname = prompt("name ", "name here");

        try {
            if (inpname === null) {
                throw "cant cancel";
            }
            if (inpname.length > 10 || inpname.length <= 3) {
                throw "Your name must be at least 10 characters long, but not less than 4";
            }
            if (inpname != inpname.match(/^[a-zA-Z]+$/)) {
                throw "A-Z characters accepted only!";
            }
            return inpname;
        } catch(err) {
            console.error(err);
        }
    }
}
func();

Note that you might want to avoid disallowing use of the "cancel" button.  If the user doesn't want to provide the requested info, simply exit the app with an appropriate message


text:
Q: Transcluded element clone can't reach scope I've created this transclude:'element' Atribute directive:
<div repeat="5" ng-click="sayNumber(number)">
        This is number {{number}}
</div>

app.directive('repeat', function () {
    return {
        restrict: 'A',
        transclude: 'element',
        link: function (scope,element,attrs,ctrl,transclude) {
            var repeatNum=parseInt(attrs.repeat);

            for(var i=0;i<repeatNum;i++){
                var childScope = scope.$new();
                childScope.number = i;
                transclude(childScope, function(clone,cloneScope) {
                    element.parent().append(clone);
                });
            }
        }
    }
});

Transclude element rendered as expected, but after - doesn't see parent scope, and can't call any of its functions.
Here is jsfiddle: http://jsfiddle.net/3anj78sz/10/
It's also containing transclude:true Element directive, which works as expected, and standard ng-repeat, which functionality I was trying to achieve with transclude:element directive.
What have I done wrong?

A: Ok, after digging for a while I found out, that this problem has occured because of using multiple angular directives on same element, in this case - both "repeat" ang "ng-click".
That won't causes any trouble in cases, when one directive doesn't depend on another, but if so, it may (or may not) lead to situation, when angular will process dependent directive before the one it depends on.
This happens when directives have same priority, and angular process them in alphabetical order.
So, to make example in the question working, all I have to do, is to set higher priority to "repeat" directive than "ng-click" has.
This is the definition object of correct directive:
        {
           restrict: 'A',
           transclude: 'element',
           priority: 1000,
           link: ...
        }


text:
Q: A better CDate for VB6 We have a a VB6 app (in a COM component) which uses CDate() to take a string and cast it to a Date, for storing in a database.
Depending on if we want the application to talk in dd/MM/yy or MM/dd/yy for example, we have to change the regional settings of the identity user for the COM application.  (Right now the only option we have is a nasty hack.)
We have a date format string which is used for formatting all output dates, and it is assumed that the date
If this were .NET we would use DateTime.ParseExact and be away laughing.  Calling out to a COM object written in .NET for this sole purpose is an option.  Is there a different or better option, involving some black magic around the Format command, or a long reusable function that tokenizes the date depending on the format string, etc?

A: Look, there's no easy way to say this - you're screwed.  If you accept freeform input from the web, you have to live with the reality that people around the world format dates differently.  That's why so many websites use popup calendars, and such, to get user input.  No ambiguity there.  No matter what you think, .NET's library routines can't fathom your user's intentions any better than any other library.
Fwiw, the code Mike posted is absolutely VB6.  I'm not sure what about it looks like VB.NET?  Once you get a date/time into a Date variable, you can display it however you want with Format().  That's the easy part.
I'd strongly suggest you either A) find a way to gather your inputs unambiguously, or B) tell your users what format you expect and live with what they input.  All that said, is it possible I misunderstood the question, and you really do know what format the user is providing the data in?  (Because if so, I really am having trouble understanding what's the problem interpreting it in ClassicVB - sorry.)

A: This should be close, though it hardcodes the delimiter as "/" and windows YY years at 50:
Private Function ParseDate(ByVal DateString As String, _
                           ByVal DatePattern As String) As Date
    'DateString:  i/j/k formatting.
    'DatePattern: i/j/k formatting, each to be:
    '               M or MM for month position.
    '               D or DD for day position.
    '               YY or YYYY for year position, if YY
    '                 then century windowed at 50.
    Dim strStringParts() As String
    Dim strPatternParts() As String
    Dim intPart As Integer, intScore As Integer
    Dim intMonth As Integer, intDay As Integer, intYear As Integer
    Const DELIM As String = "/"
    Const YYWINDOW As Integer = 50

    strStringParts = Split(DateString, DELIM)
    strPatternParts = Split(UCase$(DatePattern), DELIM)
    For intPart = 0 To UBound(strStringParts)
        If intPart > UBound(strPatternParts) Then
            Err.Raise 5, "ParseDate"
        End If
        Select Case strPatternParts(intPart)
            Case "M", "MM"
                intMonth = CInt(strStringParts(intPart))
                intScore = intScore Or &H1
            Case "D", "DD"
                intDay = CInt(strStringParts(intPart))
                intScore = intScore Or &H2
            Case "YY"
                intYear = CInt(strStringParts(intPart))
                If 0 > intYear Or intYear > 99 Then
                    Err.Raise 5, "ParseDate"
                End If
                intYear = intYear + IIf(intYear < YYWINDOW, 2000, 1900)
                intScore = intScore Or &H4
            Case "YYYY"
                intYear = CInt(strStringParts(intPart))
                If 100 > intYear Or intYear > 9999 Then
                    Err.Raise 5, "ParseDate"
                End If
                intScore = intScore Or &H4
            Case Else
                Err.Raise 5, "ParseDate"
        End Select
    Next
    If intScore = &H7 Then
        ParseDate = DateSerial(intYear, intMonth, intDay)
    Else
        Err.Raise 5, "ParseDate"
    End If
End Function

Validation may not be perfect, but it ought to be close.  It throws "Invalid procedure call or argument (Error 5)" on bad inputs.

A: DateAdd accepts a wide variety of inputs and outputs in the correct format.
ThisLine =  "Tuesday, September 04, 2012 2:02 PM"

i = InStr(ThisLine, ",")  ' get rid of the leading day

If i > 0 Then
     TempResult = Trim(Right$(ThisLine, Len(ThisLine) - i))
end if

TempResult = DateAdd("s", 0, TempResult)

A: I don't know of an easy solution. You could Split the input string into sub-strings by the delimiter, and then use DateSerial to recombine the year, month and hour numbers into a native VB6 Date variable. Something like this below. If you need to support a lot of locales, this could get complicated (see Bob's answer). Mind you, so would using DateTime.ParseExact.
sInput = "1/3/71"
Dim splt() As String
splt = Split(sInput, "/")
dte = DateSerial(splt(2) + 1900, splt(1), splt(0))  ' dd/mm/yy'

A: You can use the built-in Format function to do this for you.
Here is a simple test to confirm this:
Public Sub TestDateParsing()

   'On my computer, the date format is U.S. (mm/dd/yyyy)'
   'This test creates a date string in dd/mm/yyyy format to'
   'simulate user input in a different format'

    Const TEST_DATE As Date = #6/1/2009#

    Dim inputDate As String
    inputDate = Format(TEST_DATE, "dd/mm/yyyy")
    'inputDate is "1/6/2009" (June 1 in dd/mm/yyyy format)'

    Debug.Print Format(inputDate, "dd/mm/yyyy")
    'It`s magic! The above line will print 6/1/2009'
    'which is the correct format for my Regional Settings'

End Sub

It might seem like magic, but it isn't. It takes advantage of how the Format function works in conjunction with the current regional settings.
For example, suppose your Regional Settings are configured to use the "mm/dd/yyyy" format for dates.
Now, you get a date string from a user in "dd/mm/yyyy" format. If you Format this date string and tell Format to also use "dd/mm/yyy", it will swap the month and day parts of the date because your settings say dates are in "mm/dd/yyyy" format.
In other words, Format always assumes the date string from the user is formatted according to your current Regional Settings (in this case, "mm/dd/yyyy"), so when you tell it to format the date using "dd/mm/yyyy", it will force it to swap the month and day parts. If your Regional Settings use the same format as the user-provided date, this code will still work: Format will simply return the user date unchanged. Confused yet? ;)
The same thing will happen if your Regional Settings are set for "dd/mm/yyyy" and the user sends a date in "mm/dd/yyyy" format.
The catch is that you have to know ahead of time which format the user is sending dates in. They can't start mixing and matching date formats (and they shouldn't be anyway).

EDIT (by MarkJ) - just to prove that Mike's code can convert a string to Date. Mike, please roll back or change this edit if you want.
Public Sub Test()
  Dim dte As Date
  For dte = #1/1/2009# To #12/31/2009#
    Call TestDateParsing(dte)
  Next dte
End Sub

Public Sub TestDateParsing(ByVal dteIn As Date)

  'On my computer, the date format is U.S. (mm/dd/yyyy)'
  'This test creates a date string in dd/mm/yyyy format to'
  'simulate user input in a different format'

  Dim sExpected As String
  sExpected = Day(dteIn) & " / " & Month(dteIn) & " / " & Year(dteIn)
  Dim inputDate As String
  Dim dte As Date
  inputDate = Format(dteIn, "dd/mm/yyyy")
  dte = Format(inputDate, "dd/mm/yyyy")

  Debug.Assert sExpected = Day(dte) & " / " & Month(dte) & " / " & Year(dte)
  Debug.Print sExpected

End Sub

A: You mention in the comments to one of the other answers that you are taking input from the web.
In that case you can control the date format that is being submitted by restricting user input to <select> drop lists.  Make the month box list the short or long month names Jan/January Feb/February etc and then construct a date string in the format "1 Jan 2009"
Then it doesn't matter what your locale settings are, you'll get the date the user intended.

A: Another way to go:
Public Enum abDateType
    abMDY
    abDMY
End Enum

Public Function MakeDate(ByVal dateString As String, ByVal dateType As abDateType, Optional delimiter As String = "/") As Date
    Dim strVals() As String
    Dim dtRtnVal As Date
    strVals = Split(dateString, delimiter)
    Select Case dateType
    Case abMDY
        dtRtnVal = DateSerial(strVals(2), strVals(0), strVals(1))
    Case abDMY
        dtRtnVal = DateSerial(strVals(2), strVals(1), strVals(0))
    Case Else
        Err.Raise vbObjectError, , "Unexpected date format."
    End Select
    MakeDate = dtRtnVal
End Function

A: You should talk with a date variable (not a formatted string) and then show formatted value in the form using the user regional settings or take the input from the user to a date variable.


text:
Q: Moving a Button control based on GridView height I have a GridView with a button located beneath it. The GridView's height is set dynamically. When the height is set, it displays on top of the button. What I want to do is move the button down so it still displays just below the GridView when its height is changed.
I know I can just set the location of the button, based on the height of the GridView, but is there a way to link the height to the location of the button? Like anchoring the button to the bottom edge of the GridView.

A: Put the gridview and button inside a panel. Anchor the gridview on all four sides, and anchor the button on the bottom (and optionally the left and/or right). (They will be anchored to the panel rather than the form.) Then, in the application, change the size of the panel instead of the gridview. The gridview will change sizes along with the panel, and the button will keep its position underneath of the gridview.


text:
Q: amazon EC2 load balanced - how to deploy web app? We're looking to move to amazon cloud using EC2 and RDS.
I'm looking at load balancing, which I would like to do, two servers, each in a different availability zone to protect against downtime.
My question is how to deploy web applications and updates to them? I assume there is a better way than individually updating the files on each EC2 server?

A: In systems past, I have used the vcs puppet module to ensure that the appropriate source code is installed on my system, in addition to using puppet to build the configuration files for the apache/nginx server that I'm using.  Another possibility is to push your application in a deployable state (if you're not using a scripting language) to Amazon S3, and have your run-time scripts pull the latest build from your S3 bucket.


text:
Q: What is the dimension of the range of T if T is one to one? Explain Full Question:
Let T: R^n -> R^m be a linear transformation.
A). What is the dimension of the range of T if T is one-to-one? Explain.
Ans(a): Range is a subspace of R^m, and since T is one to one then the dim of NS(T)=o, and since a pivot exists in every col then a pivot exists in every row because of T being 1-1. Therefore the dim(range(t))= R^m, but i am not completely sure.
B). What is the dimension of the kernel of T if T maps R^n onto R^m? explain.
Ans(b): I would say the dimension of the kernel of T would be R^m, but i am unsure as to why.

A: Dimension formula: $\dim(ker(T))+\dim(Im(T))=\dim(\Bbb R^n)=n$. If $T$ is one-to-one, then $\dim(Im(T))=n$ which can only happen if $m\geq n$. If $T$ is onto, then $\dim(ker(T))=n-m$, so $n-m\geq 0$ so $n\geq m$.


text:
Q: UITableView Cell Button mixed up I have a problem, setting a button to a UITableviewCell.
After viewDidLoad, the button is on the right place. But when I am scrolling down, the button is anyplace else.
Here is my code, I hope you can help me.
Thanks In Advance.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}

if (indexPath.section == 0 && indexPath.row == 0 && _isAddImageViewLoad == NO) {
    // Add Image Button
    UIButton *addImage = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage* image = [UIImage imageNamed:@"AddImage@2x"];
    addImage.frame = CGRectMake(110.0f, 10.0f, 110.0f, 110.0f);
    [addImage setImage:image forState:UIControlStateNormal];

    [cell.contentView addSubview:addImage];
    _isAddImageViewLoad = YES;
} else {
    NSDictionary *dictionary = [_items objectAtIndex:indexPath.section];
    NSArray *array = [dictionary objectForKey:@"data"];
    NSString *cellValue = [array objectAtIndex:indexPath.row];
    cell.textLabel.text = cellValue;
}

return cell;

}

A: It is because you are reusing the cells, and the button is getting placed when it shouldn't an easy solution in your else section. Write addImage.hidden = YES; and in your if statement put addImage.hidden = NO;

A: Look at this line of code:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

This line of code means the UITableViewCells are not created every time. They are re-used as you scroll up and down. Using the code you have above, the UIButton will be created in the correct spot, but then as the cells are re-used, it will create the button in random spots.
One quick way to solve the problem, change the above line of code to simply
UITableViewCell *cell;

A: Just a couple things.  If you use "AddImage" it will use the "AddImage@2x" automatically if it's a retina display. I don't think that will solve your issue but it could be causing weirdness.
When a table view cell is scrolled off the view it is "recycled" in a sense. It appears like you are using a bool to exclude the original cell from being loaded again with a button. You may want to use a header to hold your button if you always want it at the "top".  You may also want to verify that the button is being removed when the cell is reused. if its not it will show up in the next row that reuses that cell.
On a side note... Buttons don't usually work very well in table view cells because they handle touches in very different ways.  It's quite a bit of modification to get them to feel natural but that's another matter.
Hope that helps!

A: The problem is because of cell reuse. You need to put some code in the else clause to delete the button if it exits. One way to do this, would be to give your button a tag, like:
addImage.tag = 10;

Then in your else clause:
}else{
    if (cell viewWithTag:10) [[cell viewWithTag: 10] removeFromSuperview];
    ...

A: The problem is because of the dequeue for the cells.  The first time the tableview creates the cells, all the cells run through the
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];

code.  But when the section 0 row 0 is moved off the screen, that cell is pushed into the cell reusable queue.
Now when your tableview needs to display section 0 row 0, it will get a cell from the reuse queue.  you will not get the same cell as the first time.  So now you might have 2 cells with the button.
What you should do is have different CellIdentifier for section 0 row 0 , and all other sections and rows.  Also create the button when creating the cell. So after the first time the tableView creates the cell, you will not be creating the the button everything.


text:
Q: Realizar consulta y obtenerla con las relaciones eloquent Estoy haciendo una consulta en laravel pero no me esta dando su relacion de uno a muchos, aqui dejo la consulta y el modelo

Modelo Article

class Article extends Model
{

    protected $with = ['category'];

    protected $fillable = [
        'id',
        'register_number',
        'name',
        'quantity',
        'category_id',
        'created_at',
        'updated_at'
    ];

    public function category() {
        return $this->belongsTo(Category::class);
    }

    public function setNameAttribute($value) {
        $this->attributes['name'] = strtolower($value);
    }

    public function getNameAttribute($value) {
        return ucwords($value);
    }

}

y aqui dejo la consulta que estoy realizando, como se ve anteriomente tengo el atributo with que deberia traer la categoria
$articles = DB::table('articles')
            ->whereDate('created_at', '>=', $start_date)
            ->whereDate('created_at', '<=', $end_date)
            ->get();

me da al final todos los articulos pero no me da tambien la categoria

ejm: una lista de articulos asi:

{
            "id": 1,
            "name": "Prueba",
            "register_number": "95ee89fb-bd27-3249-a7d2-086abc57919e",
            "quantity": 66,
            "category_id": 3,
            "created_at": "2019-07-10 05:37:27",
            "updated_at": "2019-08-11 15:59:40",
            "category": {
                "id": 3,
                "name": "quos",
                "created_at": "2019-08-10 05:37:27",
                "updated_at": "2019-08-10 05:37:27"
            }
        }

A: Me parece que el detalle de que no funcione la relación que estas estableciendo con Eloquent en tu modelo, es por que estás usando el queryBuilder, pues al hacer uso del método table() estas indicando que directo haga una consulta sobre esa tabla y como no invocas al modelo Article no mostrará las categorías con las que el producto se encuentra asociado
Tu consulta debería partir de este modo:
$article = Article::with('category')
                  ->whereDate('created_at', '>=', $start_date)
                  ->whereDate('created_at', '<=', $end_date)
                  ->get();

Donde hacemos uso de eager loading para que en la misma consulta se carguen las categorías producto de usar la relación belongsTo() declarada en el cuerpo de la clase del modelo Article, donde pasaremos el nombre de esta misma como argumento del método with()

*

*Eager loading


text:
Q: How to check if C# class has security attribute used How can I check and make sure that a class uses my own custom security attribute? I know that I can use reflection to get normal attributes, but if the custom attribute is based on a security attribute as shown below reflection doesn't show it. Is there any way to check that?
Why I would need this is to make sure that a plugin that is loaded to a cloud based system must use security attribute so the class that get's loaded cannot access any restricted files and so on.
Here is the custom security class I'm using:
public class PluginSection : CodeAccessSecurityAttribute
{
    public PluginSection(SecurityAction action)
        : base(action)
    {
    }

    public override IPermission CreatePermission()
    {
        // WebSites.GetInstance().LocalBaseDir returns the base directory where the class has accesss to login
        return new FileIOPermission(FileIOPermissionAccess.Write, WebSites.GetInstance().LocalBaseDir);
    }

}

I must use a class based on CodeAccessSecurityAttribute so that the FileIOPermission would work.
Also if there is another way to restrict the access of the plugin being loaded I could use that too.

A: Reflection seems to work fine for me:
using System;
using System.Diagnostics;
using System.Security;
using System.Security.Permissions;

public class PluginSection : CodeAccessSecurityAttribute
{
    public PluginSection(SecurityAction action)
        : base(action)
    {
    }

    public override IPermission CreatePermission()
    {
        // Removed for demo purposes
        return null;
    }

}

class NotApplied {}

[PluginSection(SecurityAction.Demand)]
class Applied{}

class Test
{
    static void Main()
    {
        Console.WriteLine(IsPluginSection(typeof(Applied)));
        Console.WriteLine(IsPluginSection(typeof(NotApplied)));
    }

    static bool IsPluginSection(Type type)
    {
        return type.IsDefined(typeof(PluginSection), false)
    }
}

A: I don't think it is necessary to use reflection to check, if an attribute is assigned to the plugin. Permissions is based on scope, so they will propagate downwards in your call hierarchy.
If it is possible with your current design, you should just decorate the method that executes your code with the custom attribute:
[SomePermission(SecurityAction.PermitOnly)]
public void PluginExecutor(Plugin plugin)
{
    plugin.Something();
}

Something will only be given the same rights as your PluginExecutor method. Therefore you can assign whatever permissions at this point, without worrying if the plugin uses them - and without having to rely on reflection.

A: I don't have an answer, but if it gives people more information to reproduce the issue:
[TestFixture]
public class SecurityExperiments
{
    [Test]
    public void ShouldGetCustomSecurityAttributes()
    {
        Assert.That(typeof (Applied).GetCustomAttributes(true),
                    Has.Some.InstanceOf<PluginSection>());
    }

    public class PluginSection : CodeAccessSecurityAttribute
    {
        public PluginSection(SecurityAction action)
            : base(action)
        {
        }

        public override IPermission CreatePermission()
        {
            // Removed for demo purposes
            return null;
        }

    }

    [PluginSection(SecurityAction.Demand)]
    class Applied { }
}

Causes (for my test project, at least):
System.TypeLoadException: Could not load type 'PluginSection' from assembly 'StackOverflow, Version=1.0.0.0, Culture=neutral'.
at System.Reflection.PseudoCustomAttribute._GetSecurityAttributes(Void* module, Int32 token, Object[]& securityAttributes)
at System.Reflection.PseudoCustomAttribute.GetCustomAttributes(RuntimeType type, Type caType, Boolean includeSecCa, ref Int32 count)
at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeType type, RuntimeType caType, Boolean inherit)
at System.RuntimeType.GetCustomAttributes(Boolean inherit)
at StackOverflow.SecurityExperiments.ShouldGetCustomSecurityAttributes() in SecurityExperiments.cs: line 13


text:
Q: Why do I get this group-by error in a for-loop in pl/sql? I'm writing an sql procedure and I have to use a for-loop, something like this:
for a in (select first, second
           from table1 t1 join
                table2 t2
                on t1.x = t2.x
           group by t1.id,first,second
          ) loop

and I got this error Error(12,64): PL/SQL: ORA-00934: group function is not allowed here
If you have any idea what could be, please share. Thanks in advance!

A: GROUP BY can only be used with an aggregate function - I would suggest trying this:
create or replace procedure first_second is
begin
   for c in (select t1.id as ID,
         t2.variable as variable,
         avg(x) as average
         from table1 t1
 join table2 t2 on t1.id = t2.id
 group by t1.id, t1.variable)

 loop
   dbms_output.put_line ('The average' || c.ID || ' is ' || c.average);
   exit when c.average <=0;
 end loop;
end first_second;


text:
Q: How to get parameter "par" from link app/page/par in a servlet? I have some app, where a user going to link like "..app/page/par", should be redirected to page "..app/page" and then on it page should be add some data, that I should get using parameter "par"
How can I do it, using java servlets?

A: The session scope can be used to store the parameter value on the server side between the two requests.
Request 1
app/page/par
String parameterValue = request.getParameter("par");
request.getSession().setAttribute("par", parameterValue);
response.sendRedirect("app/page");

Request 2
app/page
// pass the value to the view
request.setAttribute("viewAttributeName", request.getSession().getAttribute("par"));


text:
Q: Query Percona Cluster Nodes For Current Load I'm attempting to put together a mysql load balancer with a mockup php like script. Problem is i've been looking about countless variables in the database and cant find a variable of the current load on that server so I can pick the faster server to give the client.

A: Mysql is not aware of the server resource use, so what to do is to use for example Cacti, get the data from there and use that in your loadbalancing app.
Another way is just to use round robin and assume the systems will be pretty normally distributed over time.
Third option is to auto scale the number of slave servers using for example Kubernetes with NFS & ZFS for central storage and making snapshots of the database available on the slave nodes (for a read only solution


text:
Q: How to copy a file to common desktop (how to address common desktop) with Group Policy? Using Group Policy Object > User > Preferences > Windows Settings > Files I can copy a file to user desktop using a target file name like this: %USERPROFILE%\Desktop\targetfile.txt.
Now I'm trying to do similar task, using Group Policy > Computer > Preferences > Windows Settings > File.
What shortcut should I use instead %USERPROFILE%\Desktop\ to do it right way?

A: The correct environmental variable is %DesktopDir% for the current user, and %CommonDesktopDir% for all users. Group policy environmental variables are different than the standard environmental variables. You can see a list of all of them by pressing F3 in any text field:

A: There is common desktop that you can use to populate files, shortcuts, etc for all users. Change your target to C:\Users\Public\Desktop.
Unfortunately, the only all userprofile variable is %allusersprofile% in my environment it points to c:\programdata which is not useful.


text:
Q: Java sorting collection vs DB fetch collection I have a problem where i try to sort a list of objects in java. I am getting a different result when the list of objects is created manually or fetch from the Database.
This is the object :
public class CompanyRoleProperties implements Serializable {

     private String officeName;

    public CompanyRoleProperties() {
        super();
    }

    public CompanyRoleProperties(String officeName) {
        super();
        this.officeName = officeName;
    }

    public static SQLQuery createQuery(final Session session, final StringBuilder query) {
        final SQLQuery sqlQuery = session.createSQLQuery(query.toString());

         sqlQuery.addScalar("officeName", StandardBasicTypes.STRING);
         sqlQuery.setResultTransformer(Transformers.aliasToBean(CompanyRoleProperties.class));
        return sqlQuery;
    }

....
}

I have a function that retrieve data from the Database and create a list of those objects :
public List<CompanyRoleProperties> getServiceProviders() {

    final StringBuilder query = new StringBuilder();
    query.append("select distinct * from getCompanyRoleProperties()");
    query.append(" ORDER BY startDate DESC , endDate DESC ");
    this.log.info(query.toString());

    return CompanyRoleProperties.createQuery(this.getSessionFactory().getCurrentSession(), query).list();

}

i have this generic comparator i used for the sorting:
public class GenericComparator<T extends Object> implements Comparator<T> {
    private SortOrder   sortType    = null;
    private String      sortField   = null;

    public GenericComparator(String sortField, SortOrder sortType) {
        this.sortType = sortType;
        this.sortField = sortField;
    }

    @SuppressWarnings("unchecked")
    @Override
    public int compare(T o1, T o2) {
        try {
            Comparable data1 = null;
            try {
                data1 = (Comparable) PropertyUtils.getProperty(o1, sortField);
            } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
                data1 = null;
            }

            Comparable data2 = null;
            try {
                data2 = (Comparable) PropertyUtils.getProperty(o2, sortField);
            } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
                data2 = null;
            }

            return ObjectUtils.compare(data1, data2) * (sortType.equals(SortOrder.ASC) ? 1 : -1);
        } catch (final Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    public static <T extends Object> void sortList(List<T> list, String sortField, SortOrder sortType) {
        final GenericComparator<T> comparator = new GenericComparator<T>(sortField, sortType);
        Collections.sort(list, comparator);
    }

}

This is the test i use :
final String sortOrderProperty = "officeName";

List<CompanyRoleProperties> props = myPropertiesMapper.getServiceProviders();
System.err.println("Before DB : " + props);
props.forEach(item -> System.err.println(item));

GenericComparator.sortList(props, sortOrderProperty, SortOrder.ASC);
System.err.println("After DB : " + props);
props.forEach(item -> System.err.println(item));

List<CompanyRoleProperties> names = new ArrayList<>();
names.add(new CompanyRoleProperties("KBL European Private Bankers S.A."));
names.add(new CompanyRoleProperties("BDO Audit, S.A."));
System.err.println("Manual Before : " + names);
names.forEach(item -> System.err.println(item));
GenericComparator.sortList(names, sortOrderProperty, SortOrder.ASC);

System.err.println("Manual After : " + names);
names.forEach(item -> System.err.println(item));

which gives me the following output :
Before DB : [CompanyRoleProperties [officeName=KBL European Private Bankers S.A. ], CompanyRoleProperties [officeName=BDO Audit, S.A.]]
CompanyRoleProperties [officeName=KBL European Private Bankers S.A. ]
CompanyRoleProperties [officeName=BDO Audit, S.A.]

After DB : [CompanyRoleProperties [officeName=KBL European Private Bankers S.A. ], CompanyRoleProperties [officeName=BDO Audit, S.A.]]
CompanyRoleProperties [officeName=KBL European Private Bankers S.A. ]
CompanyRoleProperties [officeName=BDO Audit, S.A.]

Manual Before : [CompanyRoleProperties [officeName=KBL European Private Bankers S.A., ], CompanyRoleProperties [officeName=BDO Audit, S.A., ]]
CompanyRoleProperties [officeName=KBL European Private Bankers S.A., ]
CompanyRoleProperties [officeName=BDO Audit, S.A., ]

Manual After : [CompanyRoleProperties [officeName=BDO Audit, S.A., ], CompanyRoleProperties [officeName=KBL European Private Bankers S.A., ]]
CompanyRoleProperties [officeName=BDO Audit, S.A., ]
CompanyRoleProperties [officeName=KBL European Private Bankers S.A., ]

As you can see the list created manually is sorted as expected however it has no effect the DB one. Why would it be the case ?


text:
Q: Uing Vue.JS v-bind:class with conditional statement of dynamically created array I have a table that is created when an array called shelves is created in my Vue app.

      <input type="number" v-model="shelf.maxWeight">

I want to bind an html class called error to each input box created, based on the length of the value in the input box. I was thinking it would be something like this:

      <input type="number" v-model="shelf.maxWeight" v-bind:class="error: shelf.maxWeight.length < 1">

But whenever I try to do this, the page does not load and I get an error in the console saying:
invalid expression: Unexpected token : in
error: shelf.maxWeight.length < 1
Raw expression: v-bind:class="error: shelf.maxWeight.length < 1"

I've been looking here but can't seem to find any reference on how to specifically do this.
How do I change the class in my input field based on the length of a value in the array that my table is referencing?

A: v-bind:class takes an object as a parameter, as described in the link you provided.
Your code should read

      <input type="number" v-model="shelf.maxWeight" v-bind:class="{error: shelf.maxWeight.length < 1}">

Note the curly braces surrounding the class object

A: You need to bind an object to class:
v-bind:class="{ error: shelf.maxWeight.length < 1 }"
              ^                                   ^


text:
Q: Merging two views data in Google Analytics I have a query in Google analytics. I have two view (one for iOS & another android) in my Google Analytics account. Currently we have to select a view to get analytics information. I have gone below urls but could not get success
http://techin.oureverydaylife.com/merge-google-analytics-profiles-15349.html
So my question is that can we merge two view (iOS & Android) into Single/Master view?

A: You can roll up properties in one single property, but this is a Google Analytics 360 (premium) feature. Otherwise you have no access to this feature.
So if you have access you can simple navigate to the administration panel and select "Roll Up Management" from the properties menu.


text:
Q: Prevent app from shutting down when device is rebooted When I restart the device my app is on it won't preserve the state it had once I open up the app again, it will be as if it's the first time I open, losing the session and having to re-login, how can I make my app preserve its state even through a device reboot? Like Twitter does, for example.

A: I'll try a bit more formal answer based on the comments you added above.  I'll start by saying that the link Tim posted is something you should familiarize yourself with.
When your app is running, it's in the Foreground state.  When you "exit" an app with the Home button, you're not really quitting it; you're just pushing it to the Background state. after a few seconds in background state, the OS automatically moves the app to the Suspended state.  If you come back within a few minutes, your app is still in memory, so the OS just puts it back on the screen the way it was.
However, if you leave the app alone for a while and use other apps, the OS can--at any time and without warning--purge your app from memory.  This is known as the "Not Running" state.  Now, when the open the app again, it has to start from scratch.  Obviously, the same thing happens when the device restarts--all apps are purged from memory.
The trick, then, is to save essential information about the app state whenever it enters the background state.  You can use the app delegate's didEnterBackground method, or register for the UIApplicationDidEnterBackgroundNotification and invoke a method in your active view controller (or any other class, for that matter).  Either way, you should save whatever state information you can.
How do you save this information?  There are several strategies.  For a simple app, perhaps you can register a few setting as NSUserDefaults.  Or maybe you can write out a file containing whatever data the user was working on.  It's really up to you.
Then, whenever the app launches, check for the presence of that saved data (however you chose to write it out), and set up the UI accordingly.  To the user, it will appear as though the app never quit, which is exactly what Apple wants them to think.


text:
Q: UFW rule doesn't work At first enable the ufw status.
root@sai:~# ufw status
Status: active

It blocks both incoming and outgoing connections, tested by using ping
ssh from both sides not working.
root@sai:~# ping 192.168.2.223
PING 192.168.2.223 (192.168.2.223) 56(84) bytes of data.
^C

--- 192.168.2.223 ping statistics ---
4 packets transmitted, 0 received, 100% packet loss, time 2999ms

root@sai:~# ssh durga@192.168.2.223
^C

Added a rule allow ssh, even after that also ssh doesn't work
root@sai:~# ufw allow ssh
Rule added
Rule added (v6)

root@sai:~# ssh durga@192.168.2.223

^C

root@sai:~# ufw status
Status: active

To       Action      From

--       ------      ----

22        ALLOW       Anywhere

22 (v6)   ALLOW       Anywhere (v6)

Suggest me the all possible commands..

A: If ufw is configured to block outgoing traffic (which is not default policy) your ssh connection is blocked. You have to allow it.
sudo ufw allow out 22

On the server side ufw must be configured to allow incoming ssh connection (default port 22)
sudo ufw allow 22


text:
Q: Cancel current transaction with Spring TransactionTemplate I am using a connection pool and the Spring TransactionTemplate. If you want to shutdown the connection pool first all connection have to be returned to the pool, this means connection.close() has to be called. I have one thread using the TransactionTemplate for some queries and another thread that wants to call some shutdown method on the connection pool, but before doing this it first has to tell the TransactionTemplate to close all connection (actually only returning them to the pool).
How can this be done in Spring to immediately call close on the used connection?

A: If you are using Hibernate along with Spring please use:
hibernate.connection.release_mode=after_transaction

If you want to release connection just after transaction.
hibernate.connection.release_mode=after_statement

If you want to release connection after each statement
This two settings are the only ways I know that will make used connection being released faster than the default behavior. At least as far as Hibernate is concerned. If you are using other library please describe which.


text:
Q: get Date in specific format from sqlserver 2012 I have a table named NewsMaster which has a column named NewsDate .
Date is stored as 2016-05-19 00:00:00.000 in this table.
Now i want to retrieve this date as something like October-2016 . that's it. looked so many blogs but nothing found.
DATENAME(month,GETDATE()) 'Month Name'

is this helpful? am i close? need modification.

A: Try this
Select DATENAME(month,GETDATE())+' - '+ convert(nvarchar,DATEPART(yyyy,GETDATE()))

A: You can use Format() function introduced in sql server 2012.
Try this -
SELECT FORMAT(CAST('2016-05-19' AS DATE), 'MMM-yyyy')

Result
May-2016

You can use it in your query like this -
SELECT FORMAT(NewsDate, 'MMM-yyyy') AS NewsDate FROM yourTable


text:
Q: AngularJS directive two way binding for a configurable number of variables When creating a directive, while defining isolate scope with two way binding using = is there any way that I can bind an array of scope variables. ie. if in my controller I have objects defined like $scope.one, $scope.two etc. and there can be any number of those - I want the directive to be able to handle a configurable number of them. How could I do that?
I can't do this, since another controller that uses the directive may have ten, so I want it to be flexible:
.directive("example", function () {
    return {
        scope: {
          one: "=",
          two: "=",
          three: "="
        },
    ...

A: Off course it is:
.directive('example', function() {
   return {
     scope: {
       config: '='
     },
     link: function(scope) {
       var firstOption = scope.config[0];
       var secondOption = scope.config[1];
       //...
     }
   }
}

The array options would have to be stored at a fixed index, so it would be less readable than passing a config object
.directive('example', function() {
       return {
         scope: {
           config: '='
         },
         link: function(scope) {
           var firstOption = scope.config.firstOption;
           var secondOption = scope.config.secondOption;
           //...
         }
       }
    }


text:
Q: Failed to Send data with external file.js to php using XMLHttpRequest() put the javascript code directly in the HTML page, it does work. Howcome it does not work if I reference the script using the src attribute on the script
This is my HTML page:
<html>
  <head></head>
  <body>
    <script src="file.js"></script>
  </body>
</html>

I can not get the following javascript code to send data to a PHP page:
this is inside file.js
var http = new XMLHttpRequest();
var url = 'server.php';
var params = 'a=use&b=12345678';
http.open('POST', url, true); // error javascript stop always here
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200)
{ alert(http.responseText); } }
http.send(params);

and this is inside server.php:
<?php
$username = $_POST['a'];
$password = $_POST['b'];
echo 'username :' . $username;
?>

When I put the javascript code directly in the HTML page, it does work. Howcome it does not work if I reference the script using the src attribute on the script tag?
for example when i put the file.js script in online compiler like 'playcode.io' it does not work

A: It doesn't matter whether you put the javascript code directly in the HTML page or add it to the script using the src attribute on the script. The problem is, you aren't setting a request header with setRequestHeader(). Add the following line of code just after http.open(), but before http.send() and it'll definitely work:
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

The application/x-www-form-urlencoded format provides a way to encode name-value pairs.


text:
Q: Why does require("the-module") from a file in another directory fail? When I did node myfile.js I got an error that a module was not found. I checked module.paths like this:
$ node
> module.paths

The path where the module is installed showed up and I could require the module:
$ node
> require("the-module")

So I added console.log(module.paths) to myfile.js to see if module.paths was the same. It was not.
What is going on?

EDIT:
It was a bit more complicated.
The module.paths are different, but that does not seem to be the problem. The path where the-module is installed is in the list.
When I add require("the-module") in myfile.js it works as expected. However I do require("c:/path-to/other-file.js") and from there I do another require("the-module"). This require fails.

EDIT 2:
module.paths is other-file.js is different. Why? (And the path where the-module is installed is not in this list.)

A: You can see all the rules for how require() loads files when you don't specify a full path here.
When you specific only a filename, as in require("the-module"), node.js looks in the node_modules sub-directory below the directory that the current module you are calling require() from was loaded.  It is done this way so that a module can have its own set of dependencies and can load them relative to it's own directory without regard from where it is in the file system.
So, if the module you are calling require() from was in c:\myprojects\team\module1 and from within a file in that directory, you call require("the-module"), then node.js will look in c:\myprojects\team\module1\node_modules to find the-module.js.
Similarly, any path that starts with ./ is relative to that same directory, but allows you to reference files in the same directory itself.
node.js does not dynamically add paths to a list of search paths.  It sounds like you have an expectation that as you access various  directories they are somehow automatically added to a search path.  That's now how it works.   The rules for where require() looks for relative paths are all spelled out here.
Also, keep in mind that there is not just one module variable across all of node.js.  There's a different one in each file that you load in node.js so module.paths very well may be different in each one.  In reality, most node.js developers never use module.paths in any way.  If you just follow the rules for how relative paths work for require(), you will get what you expect and need.


text:
Q: Jenkins-CLI/Rest API to change the credentials in the created Jenkins Job I am creating a Jenkins Job using the Jenkins CLI/REST API, by copying Jenkins Job template, I am good with this.
Now I need to change the credentials in newly created Jenkins Job(like GIT Credentials, Artifactory, Docker), the created Jenkins Job have someones credentials, i need mine there)
Is there any API/provision to do this?

A: Below jenkins Rest API is used to add the credentials to the user
curl --user username:password -XGET 'http://localhost:8080/credentials/store/system/domain/_/createCredentials' --data-urlencode 'json={
  "": "0",
  "credentials": {
    "scope": "GLOBAL",
    "id": "apicredentials",
    "username": "username",
    "password": "password",
    "description": "apicredentials",
    "stapler-class": "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl"
  }
}'
Once you add the credentials to the jenkins, change the cloned xml with the latest username and ID, and push the updated xml to create new jenkins job.


text:
Q: yahoo api county list append to select box I am new to API calls. I have to use yahoo geoplanet API. I want to append all country list inside one select box. This is my select list
<select id="Country"></select>

and this is my id link
var country = 'http://where.yahooapis.com/v1/countries?appid=w1u_hHfV34HRdninyHHdnigDEeGV9x4PnbnsKOw4';

how should i do?
thanks in advance.

A: You can use jQuery.getJSON and append &output=json to get the data in JSON format.
Then, you can easily parse the returned data as follow:
$.getJSON('http://where.yahooapis.com/v1/countries?appid=w1u_hHfV34HRdninyHHdnigDEeGV9x4PnbnsKOw4&output=json', function (data) {
        for(var i in data.places.place){
            $('#Country').append('<option value="'+data.places.place[i]['woeid']+'">'+data.places.place[i]['name']+'</option>')
        }
});

working demo


text:
Q: How to add specific recipient in jenkins job email loop when the job is triggered manually? I have a situation like want to send e-mail to specific people when that job is manually triggered. If the same job is triggered automatically I just want to include few more people into that loop. Is it possible without creating another duplicate job for this task? Because when our dev., team executing job, the email is triggered to manager which they're not want.

A: Try to use a conditional (build or post-build) step where you use the build cause as discriminator in order to send the e-mail(s).
You will need the 'conditional build step' plug-in for this to work. See https://wiki.jenkins-ci.org/display/JENKINS/Conditional+BuildStep+Plugin

A: In email setting Add trigger and use

Send To Requester

*

*If this is checked, an email will be sent user who triggers the build (if triggered by a user manually).

You can specify the recipient list for manual trigger, however you can't define different recipient list for different users who trigger the build.


text:
Q: Show underline in anchor if having href using css Show underline in anchor if having href using css
click here

show underline on hover
click here

should not show underline on hover
what should i write in myLink css which work for both.

A: a
{
    text-decoration: none;
}

a[href]
{
    text-decoration: underline;
}

JSFiddle

A: Use CSS Attribute Selector

a {
  text-decoration: none;
}
a[href] {
  text-decoration: underline;
}
Anchor with href set

Anchor without href

A: Create a css like..

Remember this will affect the entire anchor tag on your web page.you will give a specific id so as to Avoid this conflict
See this fiddle code for some extra.


text:
Q: C# .NET: How to design a template and multiply it in a form Here is a picture of what I'm trying to say:

You can see in the picture that I want to make a template and multiply it in my application. I came up with an idea that put the controls in a panel and multiply the panel with code, but the constructor of the panel wouldn't allow me to do that. Is there any other way I can multiply it cause I can't drag and drop all the controls into the form?
Thank you in advance.

A: You can create a UserControl and draw your Template inside the UserControl.
Then on the MainForm, you can use a LayoutPanel and dynamically instantiate your UserControl and add it to the Controls Collection of the LayoutPanel.
Step1
Create a new UserControl(say ucTemplate), and add the picture box & labels in it.
Step2
In the Main Form:
Add a new LayoutPanel(or a simple Panel.
And whenever you want to repeat your template, simply call the addTemplate() method.
Public sub addTemplate()
    Dim ucTemplate = new ucTemplate()
    ucTemplate.Dock = Dock.Top

    LayoutPanel1.Controls.add(ucTemplate)
End sub


text:
Q: Drop Down List first row empty using tsql I have a legacy application that using table driven design. I have built a custom drop down list with the years between 1950 and the current year + 1.
My issue is that when I finished it, i got my empty label '' and then the years starting with 1950, and I need to start with the empty label '' and then the current year plus one and desc.
The following shows where I am at. I added an Order by which worked great except now my empty label '' is the very last item in the list. I still want it to be first.
DECLARE @begin int = 1950
DECLARE @end int = YEAR(GETDATE()) + 1;

with foo (Year) as
(
select @begin as num
UNION ALL
SELECT Year+1 from foo
where Year <@end

)
SELECT '' AS Value, '' AS Label UNION
select  CAST(Year AS VARCHAR(4)) AS Value, CAST(Year AS VARCHAR(4)) Label from foo
where Year between @begin and @end

Order by Value desc

A: Simple add one more column for ordering like this:
DECLARE @begin int = 1950
DECLARE @end int = YEAR(GETDATE()) + 1;

with foo (Year) as
(
    select @begin as num
    UNION ALL
    SELECT Year+1 from foo
    where Year <@end
),
DataSource AS
(
SELECT 0 AS [RowID]
      ,'' AS Value
      ,'' AS Label
UNION
SELECT 1 AS [RowID]
      ,CAST(YEAR AS VARCHAR(4)) AS Value
      ,CAST(YEAR AS VARCHAR(4)) AS Label
FROM foo
WHERE YEAR BETWEEN @begin AND @end
)
SELECT Value
      ,Label
FROM DataSource
ORDER BY RowID ASC
        ,Value DESC


text:
Q: Dataframe with a loop I'm trying to make a for loop, where I can create and modify dataframes. The input is a messy data frames, That i want to clean, break into smaller data frames, and merge them togheter. The output would be a clean df.
I found a way for making them but I can't find a way for calling them back after that, in the loop, or another one.
for (i in 1992:2015) {
df<-filter(altdf, date== i)

df<-data.frame(df)

sumdf<- lm(y~log(x), df)
sumdf<-summary(sumdf)

sumdf<-data.frame(sumdf$coefficients)

sumdf<- pivot_longer(sumdf, cols= 1:4, names_to = 'Results', values_to = 'year' )

sumdf$year<-as.numeric(sumdf$year)

assign(paste0('years', i, sep = ''),sumdf)

}

and now i need to access the df I made with 'assign', to continue to modify them.
Do you have any idea how I can make that ?

A: I made a list of all the dataframes, with lapply:
df_list <- lapply(ls(pattern = "df"), function(x) get(x))


text:
Q: Apache not starting; httpd not working I have apache installed on RHEL 7.2 and here is what I see upon starting apache as a root user:
[root@exampledomain conf]# sudo apachectl start
Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details.
[root@exampledomain conf]# systemctl status httpd.service
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled)
   Active: failed (Result: exit-code) since Mon 2017-03-06 10:13:04 CST; 13s ago
     Docs: man:httpd(8)
           man:apachectl(8)
  Process: 6068 ExecStop=/bin/kill -WINCH ${MAINPID} (code=exited, status=1/FAILURE)
  Process: 6061 ExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUND (code=exited, status=1/FAILURE)
 Main PID: 6061 (code=exited, status=1/FAILURE)

Mar 06 10:13:04 exampledomain.com systemd[1]: Starting The Apache HTTP Server...
Mar 06 10:13:04 exampledomain.com httpd[6061]: (99)Cannot assign requested address: AH00072: make_sock: could not bind to address XX.XX.XXX.XX:80
Mar 06 10:13:04 exampledomain.com httpd[6061]: no listening sockets available, shutting down
Mar 06 10:13:04 exampledomain.com httpd[6061]: AH00015: Unable to open logs
Mar 06 10:13:04 exampledomain.com systemd[1]: httpd.service: main process exited, code=exited, status=1/FAILURE
Mar 06 10:13:04 exampledomain.com kill[6068]: kill: cannot find process ""
Mar 06 10:13:04 exampledomain.com systemd[1]: httpd.service: control process exited, code=exited status=1
Mar 06 10:13:04 exampledomain.com systemd[1]: Failed to start The Apache HTTP Server.
Mar 06 10:13:04 exampledomain.com systemd[1]: Unit httpd.service entered failed state.
Mar 06 10:13:04 exampledomain.com systemd[1]: httpd.service failed.
[root@exampledomain conf]#

After running the other command as a root user journalctl -xe, I saw the following:
[root@exampledomain conf]# journalctl -xe
Mar 06 10:10:07 exampledomain.com systemd[1]: Stopping user-0.slice.
-- Subject: Unit user-0.slice has begun shutting down
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit user-0.slice has begun shutting down.
Mar 06 10:13:00 exampledomain.com polkitd[15042]: Registered Authentication Agent for unix-process:5884:119511260 (system bus name :1.10361 [/usr/bin
Mar 06 10:13:00 exampledomain.com systemd[1]: Cannot add dependency job for unit microcode.service, ignoring: Unit is not loaded properly: Invalid ar
Mar 06 10:13:00 exampledomain.com systemd[1]: Starting The Apache HTTP Server...
-- Subject: Unit httpd.service has begun start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit httpd.service has begun starting up.
Mar 06 10:13:00 exampledomain.com httpd[5890]: (99)Cannot assign requested address: AH00072: make_sock: could not bind to address XX.XX.XXX.XX:80
Mar 06 10:13:00 exampledomain.com httpd[5890]: no listening sockets available, shutting down
Mar 06 10:13:00 exampledomain.com httpd[5890]: AH00015: Unable to open logs
Mar 06 10:13:00 exampledomain.com systemd[1]: httpd.service: main process exited, code=exited, status=1/FAILURE
Mar 06 10:13:00 exampledomain.com kill[5898]: kill: cannot find process ""
Mar 06 10:13:00 exampledomain.com systemd[1]: httpd.service: control process exited, code=exited status=1
Mar 06 10:13:00 exampledomain.com systemd[1]: Failed to start The Apache HTTP Server.
-- Subject: Unit httpd.service has failed
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit httpd.service has failed.
--
-- The result is failed.
Mar 06 10:13:00 exampledomain.com systemd[1]: Unit httpd.service entered failed state.
Mar 06 10:13:00 exampledomain.com systemd[1]: httpd.service failed.
Mar 06 10:13:00 exampledomain.com polkitd[15042]: Unregistered Authentication Agent for unix-process:5884:119511260 (system bus name :1.10361, object
Mar 06 10:13:04 exampledomain.com sudo[6052]:   akhare : TTY=pts/1 ; PWD=/etc/httpd/conf ; USER=root ; COMMAND=/sbin/apachectl start
Mar 06 10:13:04 exampledomain.com polkitd[15042]: Registered Authentication Agent for unix-process:6055:119511697 (system bus name :1.10362 [/usr/bin
Mar 06 10:13:04 exampledomain.com systemd[1]: Cannot add dependency job for unit microcode.service, ignoring: Unit is not loaded properly: Invalid ar
Mar 06 10:13:04 exampledomain.com systemd[1]: Starting The Apache HTTP Server...
-- Subject: Unit httpd.service has begun start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit httpd.service has begun starting up.
Mar 06 10:13:04 exampledomain.com httpd[6061]: (99)Cannot assign requested address: AH00072: make_sock: could not bind to address XX.XX.XXX.XX:80
Mar 06 10:13:04 exampledomain.com httpd[6061]: no listening sockets available, shutting down
Mar 06 10:13:04 exampledomain.com httpd[6061]: AH00015: Unable to open logs
Mar 06 10:13:04 exampledomain.com systemd[1]: httpd.service: main process exited, code=exited, status=1/FAILURE
Mar 06 10:13:04 exampledomain.com kill[6068]: kill: cannot find process ""
Mar 06 10:13:04 exampledomain.com systemd[1]: httpd.service: control process exited, code=exited status=1
Mar 06 10:13:04 exampledomain.com systemd[1]: Failed to start The Apache HTTP Server.
-- Subject: Unit httpd.service has failed
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit httpd.service has failed.
--
-- The result is failed.
Mar 06 10:13:04 exampledomain.com systemd[1]: Unit httpd.service entered failed state.
Mar 06 10:13:04 exampledomain.com systemd[1]: httpd.service failed.
Mar 06 10:13:05 exampledomain.com polkitd[15042]: Unregistered Authentication Agent for unix-process:6055:119511697 (system bus name :1.10362, object

I saw this post with the same error and tried to see the list of ports using the command mentioned over there netstat -punta | grep LISTEN but couldn't figure out what's the problem.
The result of netstat -punta command is as follows:
[root@termsprweb1 conf]# netstat -punta
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:139             0.0.0.0:*               LISTEN      1350/smbd
tcp        0      0 0.0.0.0:111             0.0.0.0:*               LISTEN      1/systemd
tcp        0      0 AAA.AAA.AAA.A:53        0.0.0.0:*               LISTEN      2641/dnsmasq
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1718/sshd
tcp        0      0 127.0.0.1:631           0.0.0.0:*               LISTEN      1563/cupsd
tcp        0      0 0.0.0.0:445             0.0.0.0:*               LISTEN      1350/smbd
tcp        0      0 XX.XX.XXX.XX:22         YY.YY.YY.YYY:55863      ESTABLISHED 13706/sshd: myusername
tcp        0     36 XX.XX.XXX.XX:22         YY.YY.YY.YYY:55025      ESTABLISHED 7497/sshd: myusername [
tcp        0      0 XX.XX.XXX.XX:22         YY.YY.YY.YYY:62755      ESTABLISHED 11633/sshd: myusername
tcp        0      0 XX.XX.XXX.XX:22         CC.CC.CC.CCC:54496      ESTABLISHED 9475/sshd: otherusername
tcp        0      0 XX.XX.XXX.XX:22         YY.YY.YY.YYY:55027      ESTABLISHED 7499/sshd: myusername [
tcp        0      0 XX.XX.XXX.XX:22         YY.YY.YY.YYY:62723      ESTABLISHED 11423/sshd: myusername
tcp6       0      0 :::3306                 :::*                    LISTEN      1799/mysqld
tcp6       0      0 :::139                  :::*                    LISTEN      1350/smbd
tcp6       0      0 :::111                  :::*                    LISTEN      1916/rpcbind
tcp6       0      0 :::22                   :::*                    LISTEN      1718/sshd
tcp6       0      0 :::445                  :::*                    LISTEN      1350/smbd
udp        0      0 AAA.AAA.AAA.A:53        0.0.0.0:*                           14932/dnsmasq
udp        0      0 AAA.AAA.AAA.A:53        0.0.0.0:*                           2641/dnsmasq
udp        0      0 0.0.0.0:67              0.0.0.0:*                           14932/dnsmasq
udp        0      0 0.0.0.0:67              0.0.0.0:*                           2641/dnsmasq
udp        0      0 0.0.0.0:111             0.0.0.0:*                           1916/rpcbind
udp        0      0 XX.XX.XXX.XX:123        0.0.0.0:*                           2968/ntpd
udp        0      0 AAA.AAA.AAA.A:123       0.0.0.0:*                           2968/ntpd
udp        0      0 127.0.0.1:123           0.0.0.0:*                           2968/ntpd
udp        0      0 0.0.0.0:123             0.0.0.0:*                           2968/ntpd
udp        0      0 0.0.0.0:43237           0.0.0.0:*                           1672/avahi-daemon:
udp        0      0 0.0.0.0:819             0.0.0.0:*                           1916/rpcbind
udp        0      0 0.0.0.0:5353            0.0.0.0:*                           1672/avahi-daemon:
udp6       0      0 :::111                  :::*                                1916/rpcbind
udp6       0      0 :::123                  :::*                                2968/ntpd
udp6       0      0 :::819                  :::*                                1916/rpcbind

where  YY.YY.YY.YYY  is my system IP address.

       XX.XX.XXX.XX  is the server on which Apache is installed

A: Run
 journalctl -u httpd.service

and find the exact error. if response like
enter image description here
this happen because of

httpd (pid 5228) already running

So kill that process. (find pid using above command)
 kill 9 5228

then start the httpd service.
service httpd start


text:
Q: How can hide and show information using prototype? I'd like to a select box that will show information According a selection, how?
If I select option A will show info1 and if I select option B will show info2.
<select>
  <option>AAAAAAAAAA</option>
  <option>BBBBBBBBBB</option>
</select>

 <select>
   <option>aaaaaaaaaa</option>
   <option>aaaaaaaaaaa</option>
 </select>

 <select>
   <option>bbbbbbbbbbb</option>
   <option>bbbbbbbbbbb</option>
 </select>

*

*Fiddle

A: You can write a javascript function with onchange event of your select box like below:
<select name="select1" id="select1" onchange="showDiv()">
   <option value="A">AAAAAAAAAA</option>
   <option value="B">BBBBBBBBBB</option>
</select>

And write a javascript function like this:
document.getElementById("select1").onchange=function(){

     var value= document.getElementById("select1").value;
    //alert("Test"+value);
    if(value=="A"){
        document.getElementById("info2").style.display="none";
        document.getElementById("info1").style.display="inline";

    }else if(value=="B"){
        document.getElementById("info1").style.display="none";
        document.getElementById("info2").style.display="inline";
    }else{
        document.getElementById("info1").style.display="none";
        document.getElementById("info2").style.display="none";
    }
};

Fiddle: http://jsfiddle.net/HgqNf/29/


text:
Q: Android -- streaming a shoutcast audio file i am trying to stream an shoutcast audio file in my device android 2.2...i heard that this shoutcast will not work in android 2.2. so, i tried with android emulator 2.3 then also song not playing why could you tell me where i am going wrong...and the code is below...
  public class AudioDemo extends Activity {

  final String song_uris="http://stream.radiosai.net:8004/";
  private MediaPlayer mediaplayer;
  @Override
  public void onCreate(Bundle icicle) {
  super.onCreate(icicle);
  setContentView(R.layout.main);

  Button play = (Button) findViewById(R.id.play);
  Button pause = (Button) findViewById(R.id.pause);
  Button Previous = (Button) findViewById(R.id.Previous);
  Button Next = (Button) findViewById(R.id.Next);

  mediaplayer = new MediaPlayer();
  mediaplayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

  play.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {

    try {
        mediaplayer.setDataSource(song_uris);
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
      try {
        mediaplayer.prepare();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } // might take long! (for buffering, etc)
      mediaplayer.start();
}
   });
   }
   }


text:
Q: How to always redraw a @Composable? I have a composable like here.
@Composable
fun MyBasicTextField() {
    val keyboardController = LocalSoftwareKeyboardController.current
    val focusRequester = remember{ FocusRequester() }

    BasicTextField(
        modifier = Modifier
            .focusRequester(focusRequester),
        keyboardActions = keyboardActions ?: KeyboardActions(onAny = { keyboardController?.hide() }),

    )

    LaunchedEffect(Unit) {
        Log.d(TAG, "focusRequester.requestFocus()")
        focusRequester.requestFocus()
    }
}

*

*When the screen where this composable is used opens for the first time, always the keyboard is shown (above log message is visible).

*Then I leave the app at that state and open another app (opening a link on that screen, which opens the default browser for instance)

*Tapping on the BACK button (triangle) leaved the other app (e.g. webbrowser) and comes back to the initial screen: Either with opened Android keyboard on some devices or without any keyboard showing.

I have the feeling that the screen did not notice the missing keyboard (which disappreared while leaving the app for the browser) and thus does not recompose anything?
Can I flag to compose the screen from fresh everytime I re-/compose it?

A: I'm not sure why you need this, because focusing and showing keyboard every time re-composition happens may be undesirable, what if the user is doing something else on the screen which updates the field, you don't want want to show the keyboard but re-composition happens and you pop it again.
Having said this it's of course doable:
For example the argument passed into the LaunchedEffect determines if during re-composition the block will be run.
So you could try something like this:
@Composable
fun MyBasicTextField() {
    val keyboardController = LocalSoftwareKeyboardController.current
    val focusRequester = remember{ FocusRequester() }
    var launchKey by remember { mutableStateOf(0) }

    BasicTextField(
        modifier = Modifier
            .focusRequester(focusRequester),
        keyboardActions = keyboardActions ?: KeyboardActions(onAny = { keyboardController?.hide() }),

    )
    //passing launchKey instead of Unit
    LaunchedEffect(launchKey++) {
        Log.d(TAG, "focusRequester.requestFocus()")
        focusRequester.requestFocus()
    }
}