text:
Q: c++ application crashes when no args are entered I am creating a command line based encryption software. I have an if statement here, to check if there is no arguments, and exit with code 1.
if (argc = 0) {
    errorExit("No arguments listed. Type \"-h\" for help.", 1);
}

errorExit() is in a header file I created.
int errorExit(string errMsg, int errorCode) {
cerr << "Error: ";
cerr << errMsg;
cerr << endl;
exit(errorCode);
return NULL;

}
My program instead crashes when I type in no arguments.
Z:\Code\C++\CodeBlocks\simplecrypt\bin\Debug>simplecrypt.exe
terminate called after throwing an instance of 'std::logic_error'
   what():  basic_string::_S_construct null not valid

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.

Z:\Code\C++\CodeBlocks\simplecrypt\bin\Debug>

To clear up confusion I am using codeblocks with mingw, in case its a bug in mingw.
EDIT: I realized that I have argc = 0 instead of argc == 0. I realized the error but still didnt fix the problem.

A: The main function may be declared like this:
int main (int argc, char *argv[]);

When you call the program in command line, the argv[0] would be the name of executable, which means the argc should be 1 if there is no other arguments.

A: if(argc == 0){...

Write == and not = in the if condiction


text:
Q: Filter on array of objects In elasticsearch we have a type which has an array of objects. When trying to access from Kibana I am getting some inconsistencies while accessing
Here is an extract from my mapping,
{
    "myIndex-2017.08.22": {
        "mappings": {
            "typeA": {
                "properties": {
                    .
                    .
                    .
                    "Collection": {
                        "properties": {
                            .
                            .
                            .
                            "FileType": {
                                "type": "text"
                            }
                        }
                    }
                }
            }
        }
    }
}

Here I can have multiple objects in the Collection i.e., indexing it as an array. When I try too query using one FileType for example FileType: DOCX then I get some records with FileType as HTML as well.
When looking deeper I found that it is because some of the records which has two collection elements one with FileType: DOCX and one with FileType: HTML.
Why is filtering working like this ? Is there any other way to filter and get only FileType: DOCX and not display FileType: HTML.
Am running ES 5.3.

A: Elasticsearch flattens array fields out of the box, so
{
 "files" : [
    {
      "name" : "name1",
      "fileType" :  "doc"
    },
    {
      "name" : "name2",
      "fileType" :  "html"
    }
  ]}

becomes:
{
  "files.name" : [ "name1", "name2" ],
  "files.fileType" :  [ "doc", "html" ]
}

If you want to search for the objects itself in this array you have to use the nested datatype in the mapping of the collection:
{
    "myIndex-2017.08.22": {
        "mappings": {
            "typeA": {
                "properties": {
                    .
                    .
                    .
                    "Collection": {
                        "type": "nested",
                        "properties": {
                            .
                            .
                            .
                            "FileType": {
                                "type": "text"
                            }
                        }
                    }
                }
            }
        }
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to execute mysqli queries while iterating through rows returned using mysqli_use_result? (PHP) I am trying to iterate through all users and call a function on each username from an accounts table I have on a MySQL database.
At first, I tried:
$result = mysqli_query($mysqli, "SELECT username FROM accounts");
while ($row = $result->fetch_assoc()) {
    try {
        getFollowerData($row["username"], $mysqli, $ig);
    } catch (Exception $e) {
        echo "$e \n";
    }
}

But that used too much memory as I have over 4 million records in the table.
So I then tried:
$result = mysqli_query($mysqli, "SELECT username FROM accounts", MYSQLI_USE_RESULT);
while ($row = $result->fetch_assoc()) {
    try {
        getFollowerData($row["username"], $mysqli, $ig);
    } catch (Exception $e) {
        echo "$e \n";
    }
}

However, when I do this I get:
error: Commands out of sync; you can't run this command now

because I have the line:
$result = mysqli_query($mysqli, $insertFollowerData);

in my getFollowerData() function, meaning I'm trying to make an SQL query while I am still making the first query to get all the usernames from accounts.
Is there any way to make these queries simultaneously?

A: Instead of calling this function ( getFollowerData($row["username"], $mysqli, $ig)) in loop You can user inner left join to get the follower data from the database. and you can use limiting the bunch of data and use lazy loading concept via pagination to display those data
$result = mysqli_query($mysqli, "SELECT username, followerdatacolumns FROM accounts LEFT JOIN follower_data_table_name ", MYSQLI_USE_RESULT);
while ($row = $result->fetch_assoc()) {
    try {
         // Your result
    } catch (Exception $e) {
        echo "$e \n";
    }
}


text:
Q: Variadic base class using declaration fails to compile in MSVC I'm trying to implement a variadic visitor class.
template<typename T>
class VisitorBaseFor {
protected:
   virtual ~VisitorBaseFor() = default;

public:
   virtual void visit(T &t) = 0;
};

template<typename... Ts>
class VisitorBase : public VisitorBaseFor<Ts>... {
public:
    using VisitorBaseFor<Ts>::visit...;
};

I know from that overload trick that variadic using declarations should be possible, but MSVC does not compile my code saying I need to expand Ts while both GCC and Clang compile my code without errors, see here.
What am I missing? Is this a MSVC bug or just not (yet) supported? If it is, is there a way to work around this?
Apart from that I have tried to remove the using declaration but then the calls to visit become ambiguous for some reason, even though all classes in Ts are not convertible to each other. This is being diagnosed correctly by MSVC, but why are they even used in overload resolution then?
Update: This is a known bug since at least Sep 03, 2018. See here and here.

A: Code is indeed correct and so bug of msvc.
Workaround is to manually do the recursion:
template<typename T>
class VisitorBaseImpl {
protected:
    virtual ~VisitorBaseImpl() = default;

public:
    virtual void visit(T &t) = 0;
};

template<typename... Ts> class VisitorBase;

template<typename T>
class VisitorBase<T> : public VisitorBaseImpl<T>
{
};

template<typename T, typename... Ts>
class VisitorBase<T, Ts...> : public VisitorBase<T>, public VisitorBase<Ts...>
{
public:
    using VisitorBase<T>::visit;
    using VisitorBase<Ts...>::visit;
};

Demo


text:
Q: Creating CVS view from branch with empty directrories I am using cvs -tag -b "abcdefg" command to tag-branch in my CVS. My CSV repo has an empty directory "obj" in every folder.
Whenever I use the command cvs co -r "abcdefg" REPO, I get a complete repo minus the empty folders. I tried using -f option too but it did not work. What is the way to get out of this?

A: Directories are not versioned in any way in CVS.  When you do a checkout using a branch tag in CVS it only checks out directories that have files matching the requested branch tag.  Since the "obj" directories are all empty CVS doesn't know to check them out.  When you run update it will "fix" the state of your working copy and get the empty directories.

A: Unless you specify -P (prune empty directories) you should automatically get all empty directories.
Have you checked if you maybe have a .cvsrc file which specifies something like
co -P

It should be located in your $HOME directory
If that is not the case, the question is if your tag is set on the empty directoies?
Did you have the empty directories checked out when you did the tag operation?
The tag operation only tags the stuff you have in your sandbox, to tag everything in the repository do an rtag instead.


text:
Q: Java status 400 for URL Hello - I'm trying to download a file using Apache commons fileUtils but it always ends up getting a 400 error. The file's URL is valid because I successfully downloaded it many times using the browser. Any ideas?

java.io.IOException: Server returned HTTP response code: 400 for URL:
  http://www.nikaia-hosp.gr/img/ΤΕΛΙΚΕΣ ΠΡΟΔΙΑΓΡΑΦΕΣ ΓΙΑ ΥΠΕΡΗΧΟ
  ΓΥΝΑΙΚΟΛΟΓΙΚΟ ΜΑΙΕΥΤΙΚΟ ΠΡΟΓΕΝΝΗΤΙΚΟΥ ΕΛΕΓΧΟΥ.pdf     at
  sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1894)
    at
  sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492)
    at java.net.URL.openStream(URL.java:1045)   at
  org.apache.commons.io.FileUtils.copyURLToFile(FileUtils.java:1478)    at
  com.nikaia.main.NikaiaReader.Downloader.download(Downloader.java:17)
    at com.nikaia.main.NikaiaReader.Downloader.main(Downloader.java:32)

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.io.FileUtils;

public class Downloader {

    public static void download(String url,String filename){

        //System.out.println("filename is : "+filename);
        try {
        //  FileUtils.copyURLToFile(new URL(url), new File("C:/downloads/"+filename));
                FileUtils.copyURLToFile(new URL(url), new File(PropertyReader.readProperty("ExtractedFilesPath")+"/"+filename));
            try {
                Thread.sleep(Integer.parseInt(PropertyReader.readProperty("downloadTimeout"))*1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String ar[]){
        download("http://www.nikaia-hosp.gr/img/ΤΕΛΙΚΕΣ ΠΡΟΔΙΑΓΡΑΦΕΣ ΓΙΑ ΥΠΕΡΗΧΟ ΓΥΝΑΙΚΟΛΟΓΙΚΟ ΜΑΙΕΥΤΙΚΟ ΠΡΟΓΕΝΝΗΤΙΚΟΥ ΕΛΕΓΧΟΥ.pdf","stupid.pdf");
    }
}

A: this work for me, the problem was the encoding, you need encode only the path of the url
InputStream in = new URL(url).openStream();
FileUtils.copyToFile(in,new File(filename));

first open a Stream with the url and then copy this stream data in a file. using copyToFile method
your code will be
public static void download(String url,String filename){

        try {
               //changed this 2 lines
               URL encodeUrl = new URL(UriUtils.encodePath(url, "UTF-8"));
               InputStream in = encodeUrl.openStream();
               FileUtils.copyToFile(in, new File(PropertyReader.readProperty("ExtractedFilesPath")+"/"+filename));

            try {
                Thread.sleep(Integer.parseInt(PropertyReader.readProperty("downloadTimeout"))*1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

public static void main(String ar[]){
        download("http://www.nikaia-hosp.gr/img/ΤΕΛΙΚΕΣ ΠΡΟΔΙΑΓΡΑΦΕΣ ΓΙΑ ΥΠΕΡΗΧΟ ΓΥΝΑΙΚΟΛΟΓΙΚΟ ΜΑΙΕΥΤΙΚΟ ΠΡΟΓΕΝΝΗΤΙΚΟΥ ΕΛΕΓΧΟΥ.pdf","stupid.pdf");
}

and add this dependency to your pom.xml
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>3.0.4.RELEASE</version>
</dependency>

this does the magic.
UriUtils.encodePath(host+path, "UTF-8");

A: OK answer found , I checked the encoded browser url and the url that UTF-8 java returns and the difference was that browser had %20 in the url but java had + .
I replaced all + with %20 in java and its working.
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import org.apache.commons.io.FileUtils;

public class Downloader {

    public static void download(String url, String filename) {

        try {

            String base = "http://www.nikaia-hosp.gr/img/";
            if (url.contains("http://www.nikaia-hosp.gr/img/")) {
                FileUtils.copyURLToFile(
                        new URL(base + URLEncoder.encode(url.replace(base, ""), "UTF-8").replaceAll("\\+", "%20")),
                        new File(PropertyReader.readProperty("ExtractedFilesPath") + "/" + filename));
            } else {
                FileUtils.copyURLToFile(new URL(url),
                        new File(PropertyReader.readProperty("ExtractedFilesPath") + "/" + filename));
            }

            try {
                Thread.sleep(Integer.parseInt(PropertyReader.readProperty("downloadTimeout")) * 1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String ar[]) {
        download(
                "http://www.nikaia-hosp.gr/img/ΤΕΛΙΚΕΣ ΠΡΟΔΙΑΓΡΑΦΕΣ ΓΙΑ ΥΠΕΡΗΧΟ ΓΥΝΑΙΚΟΛΟΓΙΚΟ ΜΑΙΕΥΤΙΚΟ ΠΡΟΓΕΝΝΗΤΙΚΟΥ ΕΛΕΓΧΟΥ.pdf",
                "stupid.pdf");
    }
}


text:
Q: LenovoIdeapad s400 Ubuntu 17.04 battery and Acpi issue I am very new to linux ubuntu. I just changed from windows 8.1 to ubuntu 17.04 completely and tadaam problems started. My battery was charging only until 59% then I tried some fixes but now I can not boot my laptop on battery. I have to plug in my AC charger to turn my laptop on. With some solution I read on internet i thought i have some kind of acpi problem but I my terminal says acpi not found. I dont know here can I download acpi. This is the status of my battery;
upower -i /org/freedesktop/UPower/devices/battery_BAT0
native-path:          (null)
  power supply:         no
  updated:              Do 01 Jan 1970 01:00:00 CET (1495714310 seconds ago)
  has history:          no
  has statistics:       no
  unknown
    warning-level:       unknown
    icon-name:          '(null)'
I am using Lenovo ideapad s400 Intel core i5.
Please could some body help me? or I should go back to windows :(
Best regards,

A: To find the path to your battery use the following command:
upower -e

This will output:
/org/freedesktop/UPower/devices/battery_BAT{#}

Now run:
 upower -i {battery path}

This will output full battery information, check the capacity percentage. Not sure what fixes you did so far so cannot guess as to what could cause it not to boot up on battery only.

To install something in terminal, you type:
sudo apt-get install {package name}


text:
Q: Skip login/registration in magento one page checkout I have only one product on my site, so I don't want the hassle of login/register for my users on onepage checkout. Hence I want my onepage checkout to skip and hide login/registration and directly take every checkout as guest checkout. I'm a new magento developer so have very limited knowledge about blocks, models, etc.
Below is the article which shows how it can be done, but I cannot implement it
http://excellencemagentoblog.com/blog/2011/10/17/magento-onestep-checkout-remove-login-step/
Can anyone just help me with the paths I need to create this files. I have asked the same question on magento stackexchange but no one replies there

A: Actually I am new magento developer so don't know how play with model, block etc. which the tutorial in my question did not explained clearly. Followed this tutorial to achieve this in 3 simple steps. Just there's a slide change due to the intro of persistent directory in /template. In step 2, the path you need to edit is template/persistent/checkout/onepage/login.phtml and you are done!


text:
Q: can Mainqueue do background task while using in NSURLConnection? 1)When we use mainQueue in NSURLConnection for sendasynchronousrequest ,How it gets response through running in background?because mainqueue is for updating UI only.For EX:
 [NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue   mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if ([data length] > 0 && error == nil)
    [delegate receivedData:data];
else if ([data length] == 0 && error == nil)
    [delegate emptyReply];
else if (error != nil && error.code == ERROR_CODE_TIMEOUT)
    [delegate timedOut];
else if (error != nil)
    [delegate downloadError:error];
}];

A: When you say mainQueue is for updating UI only is not strictly right.
The exact point is that mainQueue is used to update UI and so developers avoid to do any other tasks on the mainQueue to no introduce delays on the UI. It's not completely forbidden.
But, doing asynchronous task like a network request on the mainQueue is really a bad idea because it will introduce an unbounded delay that will completely break the smoothness of your UI
To not block your mainQueue you should execute your request this way :

*

*Create your own application operation queue
NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];

*then reuse your operationQueue anywhere you need it to execute your network requests
[NSURLConnection sendAsynchronousRequest:urlRequest queue:operationQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
 if ([data length] > 0 && error == nil)
     [delegate receivedData:data];
 else if ([data length] == 0 && error == nil)
     [delegate emptyReply];
 else if (error != nil && error.code == ERROR_CODE_TIMEOUT)
     [delegate timedOut];
 else if (error != nil)
     [delegate downloadError:error]; }];

Another alternative, safer and more effective is to use AFNetworking framework


text:
Q: sql when set default value getdate(), does it set value when run update statement? I know when you insert a value into db, it set that column value as current datetime,
does it apply to it when you run a update statement?
e.g.
table schema:
Id, Name, CreatedDate(getdate())

when i insert into table id = 1 , name = 'john' it will set createdDate = current date
if i run an update statement
update table set name="john2" where id =1

Will it update the createdDate?

A: No, a DEFAULT CONSTRAINT is only invoked on INSERT, and only when (a) combined with a NOT NULL constraint or (b) using DEFAULT VALUES. For an UPDATE, SQL Server is not going to look at your DEFAULT CONSTRAINT at all. Currently you need a trigger ( see How do I add a "last updated" column in a SQL Server 2008 R2 table? ), but there have been multiple requests for this functionality to be built in.
I've blogged about a way to trick SQL Server into doing this using temporal tables:

*

*Maintaining LastModified Without Triggers
But this is full of caveats and limitations and was really only making light of multiple other similar posts:

*

*A System-Maintained LastModifiedDate Column

*Tracking Row Changes With Temporal
Columns

*How to add "created" and "updated" timestamps without triggers

*Need a datetime column that automatically updates

A: wow - hard to understand...
i think NO based on the clues.
if you insert a record with a NULL in a column, and that column has a default value defined, then the default value will be stored instead of null.
update will only update the columns specified in the statement.
UNLESS you have a trigger that does the special logic - in which case, you need to look at the trigger code to know the answer.

A: if your update statement tell to update a column with getfate() it will, but if you just update a name for example and you have a createdate column (which was inserted with getdate()), this columns wont be affected.

A: You can achieve this using DEFAULT  constraint like i did it with OrderDate field in below statement.
CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
OrderDate date DEFAULT GETDATE()
)


text:
Q: Electron app with electron-updater built with "npm run make" does not work I have an Electron application which uses "electron-updater" package. The app works when running from VScode. But if building the app with "npm run make", it failed to load when double clicking the app due to this error:
Uncaught Exception: Error: Cannot find module 'builder-util-runtime'

This line in main.js causes problem:
const { autoUpdater } = require("electron-updater");

If removing this line, the app works from VSCode debugger. "npm run make" build app also works! It proves this line causes the problem.
Build environment (mac):
% node -v
  v18.13.0
% npm -v
  8.19.3
% electron --version
  v22.0.0

electron-updater is installed in above environment, which is installed after electron is installed:
npm install electron-updater

Package.json
"dependencies": {
  ...
  "electron-updater": "^5.3.0",
  ...

"devDependencies": {
  ...
  "electron": "^22.0.0",
  ...

It is noticed, directory "builder-util-runtime/out" with content is installed in "node_modules" after eletron-updater is installed. "builder-util-runtime" is not installed manually.
On mac, checking the built app file by browsing (right click the app) "myapp/Show Package Content/Contents/Resources/app/node_modules/builder-util-runtime". This directory is empty, which is the reason of the failure to load the app.
I tried manually install "builder-util-runtime". Regardless what's been done to "builder-util-runtime" in development environment, the "npm run make" creates this directory in distribution package without content which is root cause of the problem.
How to fix it so that the distribution package has "builder-util-runtime" and content?

A: I have same problem and I use yarn but not pnpm then the problem disappear


text:
Q: Attachments to Documents I have a document library. I want to be able to add supporting documents to a document(I am using a custom content type based on document). Ideally I would like to add them as attachments so everything is contained in one place.
Sadly I don't think is possible.
What ways can you think of to be able to upload additional documents to a content type?
I am happy to do some coding just need to be pointed in the right direction.
Update
I will try and explain the problem in more detail.
I have a document that needs to go through an approval process. This document may need some evidence in the form of supporting documents to confirm what the document content is correct i.e. If facts and figures are included the source document for the facts and figures should be included as well.
I understand that document sets allow the grouping of documents however I don't believe you can highlight one document as being the main. You could add a column to say if main document and make sure only 1 document in the set is set. However I think the UX would be more complex for the user as they need to do things in multiple steps.
I am currently leaning towards creating a Custom Field type that can handle the file upload. Store the document in a separate list. I then have control of the look and feel.
I don't know if it possible to auto generate a folder in document library (using the Doc ID of the document as the folder name). Then include a web part in the view and edit form to show the document library in that folder.

A: If you don't want to go down the document set approach, you could create a lookup column to either a Supporting Files document library or the current document library itself that allows for multiple selections.  This would allow you to add additional related documents to the metadata for the "Main" document.

A: Document Set is an option. I had also used LinkToDocument as it can link to master document. You can also create a unique column (or field) so these can grouped together.

A: You can have below solution:

*

*Create a document library to hold the main documents

*Create a list to hold the supporting documents as attachment to a
list item.

*Create a lookup column in document library which will fetch information from the list. When you create lookup, select in Title(link to item) in 'In this column' dropdown. This will allow you to edit\add attachments(supporting docs) from the document library UI itself.

*Check "Enforce relationship behavior" and select Restrict delete. This
will prevent the deletion of item carrying supporting docs (as attachments) in the list if it is associated to a document in the document library.

A: You can try using InfoPath forms, this allows as many attachments as you want.
Instead of attaching the related documents with InfoPath you can also think of storing them in another OOTB document library and provide the link in the InfoPath.

A: I faced the same problem, tried several built-in or self-built solutions. Finally, a third-party component made it: http://www.sparqube.com/SharePoint-Document-Column/


text:
Q: Убрать перевод строки Что нужно сделать чтобы было так:

текст [картинка-ссылка] текст

а не так:

текст
[картинка-ссылка]
текст

У меня картинка-ссылка меняется при наведении курсора:

Строчка в тексте добавляющая картинку:

дело в том что картинка выше текста когда она должна быть на ровне с ним
A: background-position
A: display: inline;

A: У вас явно какие-то стили влияют на это. Потому как без единого стиля, выглядит именно так, как вам и надо
A: inline-block - выход, но не кроссбраузерно, если можно обойтись без inline-block, то лучше так и делать, а сдесь я уверен можно, вы бы если есть возможность ссылку дали на ресурс я бы взглянул как можно иначе сделать.


text:
Q: Serial vote reversal strangeness? Bug or feature? Something strange has been happening on meta.SciFi recently...
Someone started a poll to see if people wanted to change the name of the main chat room.
But at least twice now, I've voted on the question and on several of the answers, only to have those votes apparently disappear.
The leading speculation is that it's due to the serial vote reversal script: since the question and most of the answers were posted by the same person, if you disagree with the idea of changing the name AND don't like many of the suggested new names, you're casting a lot of votes against the OP.
This raises a few questions:

*

*Since this is a meta site, there's no reputation graph, so can you even tell if your votes are being reversed?

*Since voting on meta doesn't cost points, should serial votes be reversed on a meta site?

*If this is an artifact of serial vote reversal, how should a poll like this be conducted?  (I'm less interested in this.)


text:
Q: I'm unclear on how to use the + selector in SCSS code I was running through a project today and wanted to use the + selector to limit the scope of my style parameters. I ran into an interesting problem though. Something like this was causing issues/Excedrin:
li {
    selector: 10px;
    selector: 12%;
    &:hover {
        text-decoration: underline;
        &+a:after {
            content: "";
            fancyborderstuff: stuff;
        }
    }
}

Don't hold me to that as a functional example. The important part is that I intended to get an ELEMENT+ELEMENT and instead got NOTHING/ZERO. Poof, may as well have typed "derp".
So, what is the proper way to use the + selector when nesting in SCSS?

A: There is no chance how to get li + a in your code.
ULs can have only LI children, so you have these options:
& + li {}   /* next LI */
& a {}      /* A in current LI, shorter just A, without & */
& + li a {} /* A in next LI */


text:
Q: IF statement works but ELSE doesn't? I have the following statement and the IF ELSE doesn't seem to be working? By not working I mean its just running the while loop and display the H1 without checking to see if results isn't null?
Can anybody see any obvious errors?
    if($interests_result != 0) {
        print "
Users with the same interests!

";
        while($interests_row = mysql_fetch_array($interests_result, MYSQL_ASSOC))
        {
            $int_user = $interests_row['user_id'];
            $int_twit_user = $interests_row['twitterUser'];

            $divLeft = '

".$int_twit_user.$divRight."Get ".$interests_row['coff']." <input type='hidden' value='".$interests_row['coff']."' class='credoff' name='credoff'/> credit(s)

$clearDiv

";
        }
        print $clearDiv."
";
    }
    else
    {
        print "No users to display!";
    }

The value assigned to interests_result is...
$interests_query = "SELECT * FROM produgg_users
join user_interests on produgg_users.id = user_interests.user_id
where (interest = '$interest1' OR interest = '$interest2' OR interest = '$interest3') and produgg_users.id != '".$usersClass->userID()."' and credits >= coff and produgg_users.id NOT IN (select concat_ws(',', followedID) from produgg_activity where followerID = '".$usersClass->userID()."') ORDER BY coff DESC LIMIT 30;";

$interests_result = mysql_query($interests_query) or die(mysql_error());

A: $interests_result is a mysql resource. It is not equal to 0, ($interests_result != 0 is true), therefore that block of the if is being executed.
What you want to be checking instead is this:
if (mysql_num_rows($interests_result) != 0) {

A: mysql_query() returns a resource on success, or FALSE on error, not 0

A: mysql_query returns either a resource or FALSE (if there is an error).
You appear to expect it to contain the number of rows returned, which it doesn't.
Use mysql_num_rows for your comparison.

A: You want to check for the number of rows returned.


text:
Q: Use T-SQL Merge to update existing records and insert records that don't exist but avoid duplicates I have two tables of identical structure t1 and t2.
Table t1 has approximately 100+ records more than t2.
Here's a small sample of t1.
| pid   | tid    | amt         | paymentdt  | paymentmnth   | startdate                 | enddate                   | updtby
| 670   | 1      | 690.00      | 2015-07-07 | 2015-07-07    | 2015-10-26 14:36:27.000   | 2015-10-26 15:42:42.000   | NULL
| 670   | 11     | 855.00      | 2015-07-07 | 2015-07-07    | 2015-10-26 14:36:27.000   | NULL                      | NULL
| 670   | 13     | 129.00      | 2015-07-29 | 2015-07-29    | 2015-10-26 14:36:27.000   | NULL                      | NULL
| 670   | 2      | 855.00      | 2015-09-01 | 2015-09-01    | 2015-10-26 15:42:42.000   | NULL                      | NULL
| Z41   | 1      | 62.35       | 2015-05-08 | 2015-05-08    | 2015-10-26 10:15:24.000   | 2015-10-26 13:08:05.000   | NULL
| Z41   | 11     | 800.00      | 2015-05-08 | 2015-05-08    | 2015-10-26 10:15:24.000   | NULL                      | NULL
| Z41   | 2      | 298.00      | 2015-06-01 | 2015-06-01    | 2015-10-26 13:08:05.000   | 2015-10-26 14:36:27.000   | NULL
| Z41   | 3      | 298.00      | 2015-07-01 | 2015-07-01    | 2015-10-26 14:36:27.000   | 2015-10-26 15:15:45.000   | NULL
| Z41   | 4      | 298.00      | 2015-08-01 | 2015-08-01    | 2015-10-26 15:15:45.000   | 2015-10-26 15:42:42.000   | NULL
| Z41   | 5      | 238.00      | 2015-09-01 | 2015-09-01    | 2015-10-26 15:42:42.000   | NULL                      | NULL

And a small sample of t2.
| pid   | tid    | amt         | paymentdt   | paymentmnt   | startdate                 | enddate                   | updtby
| 670   | 1      | 690.00      | 2015-07-07  | 2015-07-07   | 2015-10-02 16:10:50.000   | 2015-10-02 16:35:50.000   | NULL
| 670   | 11     | 855.00      | 2015-07-07  | 2015-07-07   | 2015-10-02 16:10:50.000   | NULL                      | NULL
| 670   | 13     | 129.00      | 2015-07-29  | 2015-07-29   | 2015-10-02 16:10:50.000   | NULL                      | NULL
| 670   | 2      | 855.00      | 2015-09-01  | 2015-09-01   | 2015-10-02 16:35:50.000   | NULL                      | NULL
| Z41   | 1      | 298.00      | 2015-07-01  | 2015-07-01   | 2015-10-02 16:10:50.000   | 2015-10-02 16:23:26.000   | NULL
| Z41   | 11     | 800.00      | 2015-05-08  | 2015-05-08   | 2015-10-02 16:10:50.000   | NULL                      | NULL
| Z41   | 2      | 298.00      | 2015-08-01  | 2015-08-01   | 2015-10-02 16:23:26.000   | 2015-10-02 16:35:50.000   | NULL
| Z41   | 3      | 238.00      | 2015-09-01  | 2015-09-01   | 2015-10-02 16:35:50.000   | NULL                      | NULL
| 173   | 1      | 785.00      | 2015-07-01  | 2015-07-01   | 2015-10-02 16:16:30.000   | 2015-10-02 16:27:36.000   | NULL
| 173   | 11     | 465.00      | 2015-05-01  | 2015-05-01   | 2015-10-02 16:16:30.000   | NULL                      | NULL

Now comparing t1 and t2 shows there are more values in t1 for pid Z41 such as the tid's include 1, 2, 3, 4 5, and 11. But in t2 there exists only 1, 2, 3, and 11.
However the startdate's are completely different between t1 and t2 so this throws a wrench in things. Below is the merge I've tried but it basically just inserts every row with a different startdate from that of t1 in t2.
MERGE INTO t2 AS tgt
USING t1 AS src
    ON tgt.pid = src.pid AND
       tgt.tid = src.tid AND
       tgt.paymentdt = src.paymentdt AND
       tgt.paymentmnt = src.paymentmnt AND
       tgt.startdate = src.startdate
WHEN MATCHED THEN
    UPDATE SET
        tgt.amt = src.amt,
        tgt.paymentdt = src.paymentdt,
        tgt.updatedby = 'MERGEDUPDATE'
WHEN NOT MATCHED THEN
    INSERT (pid, tid, amt, paymentdt, paymentmnt, startdate, enddate, updtby)
    VALUES (src.pid, src.tid, src.amt, src.paymentdt, src.paymentmnt, src.startdate, src.enddate, 'MERGEDINSERT');

With this merge I am left with duplicates of pid and tid where the updtby column reads 'MERGEDINSERT'. But I want to avoid the duplicates.

How do I correctly go about this merge to not produce duplicates but
  insert the rows that exist in t1 but not in t2 while also updating the
  amt, paymentdt, and paymentmnth values while keeping startdate?

A: The way you described it, your merge criteria should be based on pid and tid only . try this
MERGE INTO t2 AS tgt
USING t1 AS src
    ON tgt.pid = src.pid AND
       tgt.tid = src.tid

WHEN MATCHED THEN
    UPDATE SET
        tgt.amt = src.amt,
        tgt.paymentdt = src.paymentdt,
        tgt.paymentmnth  = src.paymentmnth,
        tgt.updatedby = 'MERGEDUPDATE'
WHEN NOT MATCHED THEN
    INSERT (pid, tid, amt, paymentdt, paymentmnt, startdate, enddate, updtby)
    VALUES (src.pid, src.tid, src.amt, src.paymentdt, src.paymentmnt, src.startdate, src.enddate, 'MERGEDINSERT');

A: If you're MERGE is throwing an error because of getting multiple records/matches, you can limit the Source table using aggregates within a subquery, e.g.:
;WITH t1cte AS (
    select pid, tid, amt, paymentdt, paymentmnt, startdate, enddate
    from t1 a
      inner join (select pid,tid,MAX(paymentdt) as maxdt from t1 group by pid,tid) b
        on a.pid = b.pid and a.tid = b.tid and a.paymentdt = b.maxdt
        )

MERGE INTO t2 AS tgt
USING t1cte AS src
    ON tgt.pid = src.pid AND
       tgt.tid = src.tid AND
       tgt.paymentdt = src.paymentdt AND
       tgt.paymentmnt = src.paymentmnt AND
       tgt.startdate = src.startdate
WHEN MATCHED THEN
    UPDATE SET
        tgt.amt = src.amt,
        tgt.paymentdt = src.paymentdt,
        tgt.updatedby = 'MERGEDUPDATE'
WHEN NOT MATCHED THEN
    INSERT (pid, tid, amt, paymentdt, paymentmnt, startdate, enddate, updtby)
    VALUES (src.pid, src.tid, src.amt, src.paymentdt, src.paymentmnt, src.startdate, src.enddate, 'MERGEDINSERT');


text:
Q: Marshal struct with array member in C# I'm using C# with P/Invoke to access to a DLL method. The definition of the method is the following:
[DllImport("userManager.dll")]
static extern int GetUsers(out IntPtr userList);

Original structs:
typedef struct user_list {
   unsigned short NumUsers;
   USER_LIST_ITEM List[VARLEN];
} USER_LIST

typedef struct user_list_item {
   char name[260];
   unsigned char address[256];
} USER_LIST_ITEM

And the struct layout I've done is the following:
[StructLayout(LayoutKind.Sequential)]
public class USER_LIST
{
    public uint NumUsers;
    [MarshalAs(UnmanagedType.ByValArray)]
    public USER_LIST_ITEM [] List;
}

[StructLayout(LayoutKind.Sequential)]
public class USER_LIST_ITEM
{
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
    public string name;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
    public string address;
};

But I get an error when I try to unmarshall it:
USER_LIST userList = new USER_LIST();
// Prepare pointer
IntPtr uList = Marshal.AllocHGlobal(Marshal.SizeOf(userList));
Marshal.StructureToPtr(userList, uList, false);
result = GetUsers(out uList);

Marshal.PtrToStructure(uList, userList); <--

The runtime has encountered a fatal error. The address of the error was at 0x79f82af6, on thread 0x464. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.

I get the NumUsers property right, but it seems the error occurs when unmarshalling the array. Any thoughts?

A: If you specify an array in a structure used as an out parameter, you need to tell the marshaler what length is the array going to be. With your code, the marshaler is probably allocating a zero-length array or just using null, which produces the crash. Unfortunately there seems to be no way to specify a variable-length out array as a member of a structure, because MarshalAs.SizeParamIndex only works for methods. You might get away with specifying a large, constant-size array using MarshalAs.SizeConst, but generally you'd have to parse the (presumably callee-allocated) return buffer like this:
var count = Marshal.ReadInt32 (uList) ;
var users = new List<USER_LIST_ITEM>  () ;
var ptr   = (long)uList + 4 ;
for (int i = 0 ; i < count ; ++i)
{
    users.Add (Marshal.PtrToStructure (typeof (USER_LIST_ITEM),
        new IntPtr (ptr))) ;
    ptr += Marshal.SizeOf (typeof (USER_LIST_ITEM)) ;
}

You'll have to pay extra attention to alignment&padding and 32/64 bit issues.

A: That is because List has not been allocated yet.
You will need initialize all the fields.
Another problem I see is with the following:
IntPtr uList = Marshal.AllocHGlobal(Marshal.SizeOf(userList));
...
result = GetUsers(out uList);

Are you sure that out should not be ref? Else there is no point (not sure if ref is correct either).
Update: Looking at your code again, you should be doing this (and avoid that memory leak poking your eye).
IntPtr uList;
var result = GetUsers(out uList);

var userlist = (USER_LIST) Marshal.PtrToStructure(ulist, typeof(USER_LIST));

Marshal.FreeHGlobal(ulist); // pray here or shoot the author of the C function

Update again:
Your p/invoke signature is likely wrong or you are interpreting it wrong.
I can guess it probably something like:
int GetUsers(USER_LIST* ulist);

And that what you have is not the same thing.
If this is case, the solution is easy.
Change USER_LIST to a class (but keep sequential layout) and use
// pinvoke sig
int GetUsers(USER_LIST ulist);

var ulist = new USER_LIST();
// initialize fields
var r = GetUsers(ulist);

-- or --
Call it by ref.
// pinvoke sig
int GetUsers(ref USER_LIST ulist);

var ulist = new USER_LIST();
// initialize fields
var r = GetUsers(ref ulist);

This way, you dont have to mess with manual marshalling, and I cant see anymore potential for memory leaks.
Final update:
Given the signature you posted, it looks like GetUsers returns a pointer to a list of USER_LIST with the return value being the count. Nice memory leak there.
Anyways, I would probably experiment with an unsafe approach here, and just walk thru the result , and make sure everything gets freed. (I still think you should shoot the author).

A: I think your original code isn't probably so wrong.
You've probably just used the wrong overload of Marshal.PtrToStructure.
Have you tried this?
[DllImport("userManager.dll")]
static extern int GetUsers(out IntPtr userList);

[DllImport("userManager.dll")]
static extern void UMFree(IntPtr userList);

static void Main()
{
    IntPtr userList;               // no need to allocate memory in managed code;
    GetUsers(out userList);        // memory is allocated by native function
    USER_LIST u = (USER_LIST)Marshal.PtrToStructure(userList, typeof(USER_LIST));
    UMFree(userList);
}

Using unsafe code:
public unsafe struct USER_LIST
{
    public uint numUsers;
    public USER_LIST_ITEM* list;
}

public unsafe struct USER_LIST_ITEM
{
    public fixed byte name[260];
    public fixed byte address[256];
}

class Program
{
    [DllImport("userManager.dll")]
    static unsafe extern int GetUsers(USER_LIST** userList);

    [DllImport("userManager.dll")]
    static unsafe extern int UMFree(USER_LIST* userList);

    private static unsafe void Main()
    {
        USER_LIST* list;
        GetUsers(&list);
        UMFree(list);
    }
}


text:
Q: mod_rewrite rewrite_rule syntax question I have the following in my .htaccess currently-
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^go/([^/]*)/([0-9]+)/([0-9]+)/?$ http://foo.com/wp-content/plugins/foo/cloak.php?post_id=$2&link_num=$3&cloaked_url=$0 [L]
RewriteRule ^go/([^/]+)[/]?$ http://foo.com/wp-content/plugins/foo/cloak.php?name=$1&cloaked_url=$0 [L]
</IfModule>

I want to change it so that the domain 'http://foo.com' is auto-detected and inserted (or just left off if it's unnecessary.
I'm hoping to use this .htaccess to manage multiple mapped domains to the same code base and can't really have it work with a specific URI in there.

A: Use RewriteCond for that:
RewriteCond %{HTTP_HOST} !^foo.com$
RewriteRule ...


text:
Q: Substract number from wc cmd in one line Let's suppose test.csv contains 10 lines. I'd like to put 9 into output.txt in one command line.
I tried:
cat test.csv | $(wc -l) - 1 > output.txt

output.txt should contain 9.

A: echo $(( $(wc -l <test.csv) - 1 )) > output.txt

or
wc -l <test.csv | awk '{$1--}1' > output.txt

A: Or just the good old-fashioned:
expr $(wc -l < test.csv) - 1

A: Use this Perl one-liner:
perl -le 'print `wc -l <test.csv` - 1' > output.txt


text:
Q: Reciever SKViaPoint for class message is a forward declaration I was trying to make an instance of SKViaPoint with
SKViaPoint *point = [SKViaPoint viaPoint:1 withCoordinate:coordinate];

But I am getting a following error:

So "No known class method for selector".
I checked and I do have the latest version of Skobbler SDK, but I also checked and there is no actual ViaPoint.h.
Not in mine neither in the Demo project.
So Im wondering is there anything else I should import in order to be able to make SKViaPoint instance?

A: Ok, what solved it was importing the actual class, from SKMaps framework.
Importing framework only didn't do the trick
#import <SKMaps/SKViaPoint.h>

A: Unfortunately, in the 2.5 Swift build, SKMaps.h in SKMaps.framework/Headers is missing some imports: SKViaPoint, SKViaPointState and SKSearch.
You can add them manually or use the header found here.
In the next update we'll fix this issue.


text:
Q: #error "SSE2 instruction set not enabled" when including  I´m trying to compile some C++ code with cmake and make that uses the include <emmintrin.h> and get the following make error:
 #error "SSE2 instruction set not enabled"

I have an Intel Celeron Dual Core processor with a Linux (Mint) system (Kernel 3.5).
According to Wikipedia the Celeron Dual Core is capable to execute SSE2 instructions and the sse2 flag is set according to /proc/cpuinfo. But the author of this question mentions a limited SSE support of the Intel Celeron.
I've already tried to use the SSE compiler options in my CMakeLists.txt:
set(CMAKE_C_FLAGS ${CMAKE_C_FLAGS} "-msse -msse2 -msse3")

..but nothing changed. cmake . works fine but make gives the error message above.
Do I have to change the settings in CMakeLists.txt or does the Celeron Dual Core simply not (fully) support SSE2?

A: You need to call
set(CMAKE_C_FLAGS ${CMAKE_C_FLAGS} "-msse -msse2 -msse3")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -msse -msse2 -msse3")
The CMAKE_C_FLAGS are applied to C files, and from your post's C++ tag, I guess you're compiling C++ files, hence the need to change CMAKE_CXX_FLAGS instead.
As for the positioning of the quotation marks; in your original version, you were setting CMAKE_C_FLAGS to contain 2 separate entries, the first being the starting value of CMAKE_C_FLAGS and the second being the string "-msse -msse2 -msse3".
CMake holds lists like this as semi-colon separated entries.  In the case of CMAKE_<lang>_FLAGS, invariably they are a single value comprised of a string containing all the required flags.


text:
Q: Unity Network.Connect() returns no error I'm trying to create an online game, It works in my computer, and even in two different computers in my house. But it does not connect to room of other players.
I'm testing by trying to connect a closed room, naturally it does not connect, but still the NetworkConnectionError returns "NoError" , and the OnFailedToConnect() function is never called.
My code is this:
if(GUI.Button(Rect,"Connect"))
{
    var error = Network.Connect(element);
    printConsoleEntry("Connection attempt : " + error);
}

which prints "Connection attempt : NoError".
But at some point, I see in the "real console", in the unity editor window,

The connection request to
  192.168.x.x:26500 failed. Are you sure the server can be connected to?

But it does not show immediately I press the "connect" button. It waits a little. And it only shows once, out of a 100 presses, So is there some kind of yielding?
I also tried to yield the error in a coroutine like :
var error = Network.Connect(element);
yield error;
printConsoleEntry("Bağlantı denemesi : "+error);

it always returns NoError.
so where is the error?
How can I see it?


text:
Q: DynamoDB update using NODEjs: Syntax error; token: \"updated\", near: \"set updated =\"" Each item on my dynamoDB looks like the following
 {
  "status": "pending",
  "ccNumber":  "0012",
  "created":  "2018-03-07T16:42:02-04:00",
  "id": "14664d28-ef41-4228-99b5-6381a2a69f62",
  "amount":  "12",
  "invoice": "71200",
  "customerId": "00000"
}

I'm trying to update a field on this specific record and also adding more items.  here's my params variable
 const params = {
  TableName: this.table,
  Key: { id },
  UpdateExpression: `set tranStatus = :status, updated = :updated, authTransacId = :authTransacId, avsResponse = :avsResponse, authCode = :authCode`,
  ExpressionAttributeValues: {
    ':status': data.status,
    ':updated': moment().utcOffset(-4).format(),
    ':authTransacId': data.transId,
    ':avsResponse': data.avsResponse,
    ':authCode': data.authCode
  },
  ReturnValues: "UPDATED_NEW"
}

I can't seem to find the issue with the new field: updated

A: Can you console.log(params)?
I suspect that updated is a reserved word. It is a safe practice to use ExpressionAttributeNames in your params.
I supose you call .update(params), isn't it?
const params = {
  TableName: this.table,
  Key: { id },
  UpdateExpression: `set #a = :status, #b = :updated, #c = :authTransacId, #d = :avsResponse, #e = :authCode`,
  ExpressionAttributeValues: {
    ':status': data.status,
    ':updated': moment().utcOffset(-4).format(),
    ':authTransacId': data.transId,
    ':avsResponse': data.avsResponse,
    ':authCode': data.authCode
  },
  ExpressionAttributeNames: {
    '#a': 'tranStatus',
    '#b': 'updated',
    '#c': 'authTransacId',
    '#d': 'avsResponse',
    '#e': 'authCode',
  },
  ReturnValues: "UPDATED_NEW"
}


text:
Q: Access inner variables from external functions in javascript Is it possible to access an inner variable from an external function like this example?
function a(f) {
  var c = 'test';
  f();
}

a(function() {
  alert(c);  //at this point, c should = "test"
});

A: No, that won't work. What matters is where (lexically) a function is defined, not where it's invoked.
When figuring out what (if anything) "c" refers to, the language looks in the local scope, then in the next scope out based on the definition of the function.  Thus if that invocation of "a" took place in another function that did have its own local "c", then that value would be what the alert showed.
function b() {
  var c = 'banana';
  a(function() {
    alert(c);
  });
}

b(); // alert will show "banana"

A: No, this is not possible.  The scope you declare your anonymous function in does not have access to this c variable -- in fact, nothing but a will ever has access to c.

A: No this will not work because the variable c is defined within the function and is not available outside of the function.  One option though is to pass the variable c into the function provided to a
function a(f) {
  var c = 'test';
  f(c);
}

a(function(c) {
  alert(c);  //at this point, c should = "test"
});

A: As others have said, this isn't possible. You can
1. Declare the c variable outside of the scope of the function
2. Pass an argument to f:
function a(f) { var c = { name: 'test' }; f(c)  };
a(function(o) { alert(o.name) })


text:
Q: Regex for removing a specific BBCode from a string I'm trying to write a simple method for removing specific BBCodes from an input string.
For example, where I have an input of:
string input = "[b]Hello World![/b]";

I would want to be able to do:
Remove(input, "b");

And get an output of:
"Hello World!"

Regex really isn't my strong suit. I've managed to piece together the following from google:
public static string Remove(string input, string code)
{
    string pattern = string.Format(@"\[{0}\].*?\[\/{1}\]", code, code);

    return Regex.Replace(input, pattern, string.Empty, RegexOptions.IgnoreCase);
}

Unfortunately this returns an empty string for my given example.
Can anyone advise me on how I can correct my regex to get the desired output?
Thanks

A: Use this simple regex: \[/?{0}\]
Your regex is removing the whole string

*

*Your regex \[{0}\].*?\[\/{1}\] is removing the entire [b]...[/b] string. That's why you are getting an empty string from the replacement.

*What you need is to remove only the [b] and [b]. In normal regex, this is expressed quite simply with \[/?b\], where the slash is made optional by the ?

*In your parametrized regex, something like \[/?{0}\] will work.

A: The below regex would capture the string Hello World! inside the second group.
^(.*?)((?<=])[^[]*)(.*)$

DEMO
So replace all your input string with the second captured group.

A: If you sure that both starting and trailing special symbol must occur and you don't want them to be in a result, you can use positive look back ((?<=(your symbols here))) and positive  look ahead ((?=(your symbols here))) for specified characters.
Complete answer will look like this:
(?<=(\[{0}\])).*(?=(\[\/{1}\]))


text:
Q: Grabbing only one function call from an included file What's the best way to include a file, but not execute anything except for calling a single defined function, such as register("name","id")?

A: Refactor out that function in a separate file and include that file instead.

A: the only way i know is this: (except of restructuring your file as @Hasan Khan said)
$mode = "call_func_func1";
include("file.php");

in file.php
...
if ($mode=="call_func_func1") { func1(); return; }

that is; check for $mode, execute func and return out.
if you have code in ... this will be executed as well..
also note that in these cases DONT define functions in such files or they
will be defined again! (crash)

A: When you include a php file, only the global code is executed, so if you put all content in (their own) functions, nothing is executed unless you call these functions explicitly


text:
Q: PHP, HTML table create I have little problem with tables when u echo my results.
and this is my code
<?php
    //return data if any
    while ($client = mysqli_fetch_assoc($result)) {
        //output data form each client
        //var_dump($client);
?>

    ID
    name
    lastname
    age
    Username
    Password

    <?php echo $client['id'] ?>
    <?php echo $client['emri'] ?>
    <?php echo $client['mbiemri'] ?>
    <?php echo $client['mosha'] ?>
    <?php echo $client['username'] ?>
    <?php echo $client['password'] ?>

this is my code and the list its echo the first line like id, name ,lastname... for every result. so i want attributes on the top and then down results (i cant post a photo)

A: You just Need to reorder your code:

    ID
    name
    lastname
    age
    Username
    Password

<?php
    //return data if any
    while ($client = mysqli_fetch_assoc($result)) {
        //output data form each client
        //var_dump($client);
?>

    <?php echo $client['id'] ?>
    <?php echo $client['emri'] ?>
    <?php echo $client['mbiemri'] ?>
    <?php echo $client['mosha'] ?>
    <?php echo $client['username'] ?>
    <?php echo $client['password'] ?>

><?php } ?>

You had Everything in youre While so for every Entry everything got printed.
And put your Style Tag in the Head Section of your HTML DOC


text:
Q: Unable to lookup JNDI with Weblogic 12.1.2 + Spring 4.1.9.RELEASE+Hibernate 4.3.11.Final I upgraded my application to Spring v4.1.9.RELEASE and Hibernate v4.3.11.Final versions and upgraded to Weblogic 12.1.2 too, after that I am facing the JNDI lookup issue.
Error Stack:
org.hibernate.engine.jndi.JndiException: Unable to lookup JNDI name [java:comp/env/jdbc/xxxxx]
    at org.hibernate.engine.jndi.internal.JndiServiceImpl.locate(JndiServiceImpl.java:117)
    at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.configure(DatasourceConnectionProviderImpl.java:115)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAccess(JdbcServicesImpl.java:260)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:94)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
    at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1887)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1845)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:857)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850)
    at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:425)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:849)
    at org.hibernate.jpa.HibernatePersistenceProvider.createContainerEntityManagerFactory(HibernatePersistenceProvider.java:152)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:343)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1631)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1568)
    ... 53 more
Caused by: javax.naming.NameNotFoundException: While trying to look up /comp.env.jdbc.xxxxx in /app/webapp/xxxxx/1037358259.; remaining name '/comp/env/jdbc/xxxxx'
    at weblogic.jndi.internal.BasicNamingNode.newNameNotFoundException(BasicNamingNode.java:1180)
    at weblogic.jndi.internal.ApplicationNamingNode.lookup(ApplicationNamingNode.java:143)
    at weblogic.jndi.internal.WLEventContextImpl.lookup(WLEventContextImpl.java:253)
    at weblogic.jndi.internal.WLContextImpl.lookup(WLContextImpl.java:426)
    at weblogic.jndi.factories.java.ReadOnlyContextWrapper.lookup(ReadOnlyContextWrapper.java:45)
    at weblogic.jndi.internal.AbstractURLContext.lookup(AbstractURLContext.java:135)
    at javax.naming.InitialContext.lookup(InitialContext.java:415)
    at org.hibernate.engine.jndi.internal.JndiServiceImpl.locate(JndiServiceImpl.java:114)
    ... 73 more

The JNDIs I configured are correct and I tried changing the jndi from java:comp/env/jdbc/xxxx to jdbc/xxxx  but still on the same page.
Can you please help...
--Update--
I changed my datasource xml file from java:comp/env/jdbc/xxxx  to jdbc/xxxx from code side not from the JNDI config in the admin console, in the admin console it was jdbc/xxxx and finally it worked.
Thanks


text:
Q: Development Cordova App with Red5pro live stream I'm trying to understand Cordova & Red5pro for streaming mobile. I need to create an application that live streams phone to phone.
I have so many questions and from bottom to top.
Can anybody help me with that?


text:
Q: How to return html on get method in Spring app? I have maybe very ease question, I already using Spring mvc + jsp, but now I can not understand why the controller does not return the html file. Now I use Spring Boot with the Web module.
@Controller
@RequestMapping(value = "/test")
public class Main {
    private static final Logger logger = Logger
            .getLogger(Main.class.getName());

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String index() {
        return "templates/hello.html";
    }

And my html file:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>HelloWorld</title>
</head>
  <body>
  HELLO
  </body>
</html>

I always get error:

Whitelabel Error Page
  This application has no explicit mapping for /error, so you are seeing this as a fallback.
  Sat Feb 17 20:22:24 EET 2018
  There was an unexpected error (type=Not Found, status=404).
  No message available

Build file:
buildscript {
    ext {
        springBootVersion = '1.5.10.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'mikhailov.diplom.ae'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile('org.springframework.boot:spring-boot-starter-data-rest')
    compile('org.springframework.boot:spring-boot-starter-web')
    testCompile('org.springframework.boot:spring-boot-starter-test')
    // https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf
    compile group: 'org.thymeleaf', name: 'thymeleaf', version: '3.0.9.RELEASE'

}

A: As from your build file, you are using thymeleaf:
dependencies {
    compile('org.springframework.boot:spring-boot-starter-data-rest')
    compile('org.springframework.boot:spring-boot-starter-web')
    testCompile('org.springframework.boot:spring-boot-starter-test')
    // https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf
    compile group: 'org.thymeleaf', name: 'thymeleaf', version: '3.0.9.RELEASE'

}

The "problem" with this approach is that you must explicitly define the thymeleaf templateResolver bean and the templateEngine.
On the other side, spring-boot comes with an out-of-the-box solution, that is
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

which has everything conventionally configured. In this case, you don't need to define your templeteResolver or your templateEngine (unless you don't really need to) and you can start using your templates simply by returning the String with the correct name.
With the spring dependency, you just remove the "templates" prefix and the .html ext from the returned string, and it will work as expected:
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String index() {
    return "hello";
}


text:
Q: wiki: trouble setting up .htaccess for nice URLs I am trying to configure a wikimedia installation. The wiki is installed in a subfolder of my server (www.mydomain.com/wiki) and is serverwise redirected to wiki.mydomain.com which was working fine.
I was able to use wiki.mydomain.com/index.php?title=Main_Page to access the site. But then I tried to use even shorter URLS like: wiki.mydomain.com/Main_Page.
So I created a .htaccess file in the wiki subfolder (which is accesed by wiki.mydomain.com) with the following content:
RewriteBase /
RewriteCond %{REQUEST_URI} !=/index.php
RewriteRule ^(.*) /index.php?title=$1 [L,QSA]

Which also works for the sites!
But: The css sheets seem to be missing. - The sites look really ugly.
How can I assure that only the page requests are redirected but not the file requests to the needed files?

A: Check if requested filename is an existing file. If so, don't rewrite. Otherwise, forward it to index
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /index.php?title=$1 [L,QSA]


text:
Q: Im using Django and in my views.py file line 11: user = form.save() is resulting in a UNIQUE constraint failed: auth_user.username error I've looked at the questions asked and but I cant figure out what I'm missing. When I try to test my register page it throws the UNIQUE constraint failed. I know it has some relation to form.save() in my views. Another questions solution stated that they were attempting to save the form twice. I'm sure I'm not doing that but I could be wrong.
Views.py
from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import UserRegisterForm, bUserRegisterForm, UserProfileForm

from django.contrib.auth import authenticate, login, logout

def studentreg(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form .is_valid():
            form.save()
            first_name = form.cleaned_data.get('first_name')
            messages.success(request, f'account created for {first_name}!')
            return redirect ('/home/studentlogin.html')
    else:
        form = UserRegisterForm() #this will return an empty form
    return render(request, 'users/studentregisterform.html', {'form': form})

def getstarted(request):
    return render(request, 'home/getstarted.html')

def chooseaccount(request):
    return render(request, 'home/chooseaccount.html')

def businessreg(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        profile_form = UserProfileForm(request.POST)

        if form .is_valid () and profile_form.is_valid():
            user = form.save()

            profile = profile_form.save(commit=False)
            profile.user = user

            profile.save()
            first_name = form.cleaned_data.get('first_name')
            messages.success(request, f'account created for {first_name}!')
            return redirect ('admin/')
    else:
        form = bUserRegisterForm()
        profile_form = UserProfileForm()
    return render(request, 'users/businessregisterform.html', {'form': form, 'profile_form' : profile_form})

def bloginpage(request):

    if request.method == 'POST':
        Email_Address = request.POST.get('Email_Address')
        password = request.POST.get('Password')

        user = authenticate(request, Email_Address = email, Password = password)

        if user is not None:
            login(request, Email_Address)
            return redirect('')

    context = {}
    return render(request, 'home/studentlogin.html', context)

Models.py
from django.db import models
from django.contrib.auth.models import User

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    company_name = models.CharField(max_length=50)

    def __str__(self):
        return self.user.email

forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import UserProfile

class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()

    class Meta:
        model = User
        fields = ['email', 'first_name', 'last_name', 'password1', 'password2']

class bUserRegisterForm(UserCreationForm):
    email = forms.EmailField()

    class Meta:
        model = User
        fields = ['email', 'first_name', 'last_name', 'password1', 'password2']

class UserProfileForm(forms.ModelForm):

    class Meta:
        model = UserProfile
        fields = ('company_name',)

Any help would be appreciated. I'm still learning and would like to understand what I'm doing wrong so I understand things better in the future


text:
Q: How Can I compare the microsoft word file with it previous version programatically? need the output like git compare of file I want to compare the word file with it previous version in sharepoint online. either by power automate or by programatically. I used encodian connector and able to compare however it is paid tool so need open source solution. for same. need the output like git compare of code file or as attached image.

A: AFIK, there isn't an easy way to do this. For example, look at WinMerge https://github.com/winmerge/winmerge.
Although it's written in C++ you can see that it's a pretty involved process


text:
Q: How do I select specific MySQL row in Java using Scanner user_input Integer variable in ResultSet? I have my tables already set up in MySQL and believe they are all connected correctly, and I am simply trying to display specific information.  I am asking for user input and using that integer value as an object for result.absolute().  Whenever I run the timeresult input, I get the incorrect row for "actualtime".  Is it the java code or some MySQL setting that results in the incorrect row to be displayed?  All of the other info from println's is correct.
public static void main(String[] args) throws Exception {

    Scanner user_input = new Scanner( System.in );

    String dayinput;
    System.out.print("Choose A Day (1-7): ");
    dayinput = user_input.next();

    //Accessing driver from the JAR file
    Class.forName("com.mysql.jdbc.Driver");

    //Creating a variable for the connection called "con"
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/axamschedule","root","password");
    //jdbc:mysql://localhost:3306/shows-----> This is the database
    //root is the database username
    //password is the database password

    System.out.println("Connected To Database");

    //Creating query for Sundays Table
    if (dayinput.equals("1")){
            PreparedStatement statement = con.prepareStatement("select * FROM suntimes, days, shows WHERE (days.idday = suntimes.idday and suntimes.idshow = shows.idshow)");

            //Creating a variable to execute query
            ResultSet result = statement.executeQuery();

            System.out.println("---------------------");

            Integer timeinput;
            System.out.print("Choose A Timeslot (1-24): ");
            timeinput = 0;
            timeinput = user_input.nextInt();

            if(result.absolute(timeinput)){

                    System.out.println("Time: " + result.getString("actualtime"));
                    System.out.println("Day: " + result.getString("day"));
                    System.out.println("Title: " + result.getString("title"));
                    System.out.println("Length: " + result.getString("length"));
                    System.out.println("Host: " + result.getString("author"));
            }
    }

     user_input.close();
   else{
         System.out.println("No Info");
   }

A: The resultset that you are getting is not sorted.  The order that they are being returned is determined my mysql.
try
select * FROM suntimes, days, shows WHERE (days.idday = suntimes.idday and suntimes.idshow = shows.idshow) order by actualtime;


text:
Q: Symfony form edit I use Symfony 3.
I have an entity (Book) that I can create and edit. So I have created two actions and forms to do this. But, I want to save historical of this change.
I have imagine a solution. Two Entity, Book and SubBook to inherit of BaseBook. SubBook is the history of all edit of Book and is linked by a field "parent".
public function editAction(Request $request, ...)
{
    $book = ...
    $form = $this->createForm(BookType::class, $book);
    $form->handleRequest($request);
    if ($form->isSubmitted() && $form->isValid()) {
        $subbook = new SubBook($book);

        $em = $this->getDoctrine()->getManager();
        $em->persist($subbook);
        $em->flush();
        // ...
    }
    // ...
}

AppBundle/Entity/Book
class Book extends BaseBook {
    // ...
}

AppBundle/Entity/SubBook
class SubBook extends BaseBook {
    // ...
    public function __construct($book)
    {
        parent::__construct();
        // ...
        $this->parent = $book;
    }
}

AppBundle/Model/BaseBook
abstract class BaseBook
{
    // ...
}

But my problem is that when I submit the edit form, my Book ($book) is automatically persist when I execute $em->flush(); so it is updated even if I don't execute $em->persist($book);.
So, do you have any idea to do this ? or to solve this error ?
Thanks !

A: You should use $em->detach($book);. You can find more information in the documentation

A: So, I finally did this. My Book is the entity with last update and I save in an SubBook entity all values that have changed.
My SubBook entity is so almost like Book but all value (not changed) can be null. So I abandoned the model.
public function editAction(Request $request, $id)
{
    $book = ...
    $form = ...
    if ($form->isSubmitted() && $form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $uow = $em->getUnitOfWork();
        $uow->computeChangeSets();
        $changeset = $uow->getEntityChangeSet($book);
        $subbook = new SubBook($book, $changeset);

        $em->persist($subbook);
        $em->persist($book);
        $em->flush();
        // ...
    }
    // ...
}

AppBundle/Entity/SubBook
public function __construct($book, $changeset)
{
    // ...
    $this->parent = $book;
    foreach ($changeset as $key => $values) {
        $this->$key = $values[0]; // values[0] => Hold value, [1] => New value
    }
}


text:
Q: Undefined variable in blade view (single valued data) I'm trying to pass variable $cMonth to my view. I tried looping it using foreach even if its a single valued data and error still says undefined variable .. I tried dd($cMonth) and the correct output is shown.
This is a snippet of my controller.
$cMonth = date("F", mktime(0, 0, 0, $month, 1));

return view('admin.request',compact('showData','cMonth', 'year'));

In view, I am calling cMonth like this --
{{ ($cMonth) }}

A: With this route code
Route::get('/test', function() {
    $month = 3;
    $showData = true;
    $year = 2019;
    $cMonth = date("F", mktime(0, 0, 0, $month, 1));
    return view('test', compact('cMonth', 'showData', 'year'));
});

And this view
{{ $cMonth }}

It works as expected.
Have you tried using just that code for the view and see if it works?
You should post your complete view code, because it seems that somewhere/somehow the variable get unset.


text:
Q: How to make a picturebox hide when dragged over another picturebox? So I nailed the ability to drag a picturebox around the Windows form. I need it to hide itself when it's dragged and dropped over another picture. I've tried a few methods but none seem to work and I am now back at square one, the only code I have is so that I can move the picturebox around the form.

A: I Solved Your Problem
Here Is How The Form Should Look Like

And Here Is The Code I Made:
    Private Sub CheckTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckTimer.Tick
    CheckTimer.Stop()
    CheckTimer.Interval = 1
    If PictureBox2.Location = New System.Drawing.Point(TextBox1.Text, TextBox2.Text) Then
        PictureBox2.Visible = False
    End If
    CheckTimer.Start()
End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    TextBox1.Text = PictureBox1.Location.X
    TextBox2.Text = PictureBox1.Location.Y
    CheckTimer.Start()
End Sub

Hope This Code Was Helpful To You.

A: I made an better code than the old one,  try it.
Here Is How The Form Should Look Like:

and here is the code :
Public Class Form1
Dim Point As New Point
Dim X, Y As Integer

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    Timer1.Stop()
    Timer1.Interval = 1
    Point = Cursor.Position
    PictureBox2.Location = New System.Drawing.Point(Point.X - X, Point.Y - Y)
    Timer1.Start()
End Sub

Private Sub PictureBox2_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox2.MouseDown
    X = Cursor.Position.X - PictureBox2.Location.X
    Y = Cursor.Position.Y - PictureBox2.Location.Y
    Timer1.Start()
End Sub

Private Sub PictureBox2_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox2.MouseUp
    Timer1.Stop()
    If PictureBox2.Location.X < PictureBox1.Size.Width Then
        PictureBox2.Visible = False
    End If
End Sub

End Class
I hope this code was useful to you.


text:
Q: Using SSH server and vi editor inside SSH, how do i copy lines of code and paste into notepad So I have to use SSH for my computational physics course, and with that we have to use VI editor. I'm coding in fortran 77 because that's the only language I have been taught through this course, but my professor has focused mainly on the physics portion and very little on the coding.
The code that I have written stores 400,001 lines of data into a data.dat file.
I need to copy those 400,001 lines of data into an excel file so that I can make a graph.
The problem I am having is when highlighting the text manually, selecting the select all option, or the select screen option, I am only able to select about 200 lines of code and they usually repeat themselves.
I've seen several shortcuts but I can't get them to work.
I used :%y* and :%y+ and all it says is E488 trailing character.
I have also tried gg"*yG and gg"+yG and all it says is 400,001 lines yanked but then I cannot paste them into my excel file.
I have run myself ragged working on this code for over a month and I am now so close to turning it in but i really need that data and I really need that graph.
Please help me figure this out, I am literally driving myself insane trying to do this.

A: You ask the wrong question.
Ask instead - transfer file through ssh - and You will get many possibillities
Here is just one
https://help.ubuntu.com/community/SSH/TransferFiles
If you are on a windows machine - just install winscp:
https://winscp.net/eng/download.php


text:
Q: How to find and click :javascript links using Selenium Ruby? I want to click on all :javascript links on page that I am loading in Firefox using Selenium Ruby.
What could be the correct method for doing this?
I did for simple links like this:
require 'rubygems'
require 'selenium-webdriver'

driver = Selenium::WebDriver.for :firefox
driver.get " http://www.testfire.net "
driver.find_elements(:tag_name, "a").each {|link| link.open}

Though its not working properly due to some error
Selenium Test.rb:6: private method `open' called for #<Selenium::WebDriver::Element:0x4c155f0> (NoMethodError)
        from Selenium Test.rb:6:in `each'
        from Selenium Test.rb:6

Can :javascript links can be clicked using find_element method?
The problem I am facing here is that if it clicks one link successfully and open it , it crashes while going for next.
How to keep this continue till all links in page gets clicked.

A: I see two problems with the script:

*

*You are trying to use private method of Element class. To open link you need to all element.click, not element.open:
This should work
driver.find_elements(:tag_name, "a")[0].click

*Don't iterate through the links on the page an try to click them without assuring that you get back to initial page before the next click. Otherwise Selenium loses context and will give you following message:
Selenium::WebDriver::Error::StaleElementReferenceError

A:
Try below code.I am not that much familiar to Ruby,Still below code
  may be helpful for you

link = driver.find_elements(:tag_name, "a")
i = 0
link.times do
{
link[i].click
driver.navigate.back
i=i+1
link = driver.find_elements(:tag_name, "a")
}


text:
Q: Printing a column from a .txt file I'm a beginner at Python.
I'm having trouble printing the values from a .txt file.
  NFL_teams = csv.DictReader(txt_file, delimiter = "\t")
  print(type(NFL_teams))
  columns = NFL_teams.fieldnames
  print('Columns: {0}'.format(columns))
  print(columns[2])

This gets me to the name of the 3rd column ("team_id") but I can't seem to print any of the data that would be in the corresponding column. I have no idea what I'm doing.
Thanks in advance.
EDIT: The .txt file looks like this:
team_name   team_name_short team_id team_id_pfr team_conference team_division   team_conference_pre2002 team_division_pre2002   first_year  last_year
Arizona Cardinals   Cardinals   ARI CRD NFC NFC West    NFC NFC West    1994    2021
Phoenix Cardinals   Cardinals   ARI CRD NFC -   NFC NFC East    1988    1993
St. Louis Cardinals Cardinals   ARI ARI NFC -   NFC NFC East    1966    1987
Atlanta Falcons Falcons ATL ATL NFC NFC South   NFC NFC West    1966    2021
Baltimore Ravens    Ravens  BAL RAV AFC AFC North   AFC AFC Central 1996    2021
Buffalo Bills   Bills   BUF BUF AFC AFC East    AFC AFC East    1966    2021
Carolina Panthers   Panthers    CAR CAR NFC NFC South   NFC NFC West    1995    2021

There are tabs between each item.


text:
Q: WPF DropShadow Effect disapear when setting background color of control In this example, I have a TextBlock with a DropShadowEffect:
<TextBlock Foreground="Black" Text="All Tasks">
    <TextBlock.Effect>
        <DropShadowEffect ShadowDepth="1.2"
                          Direction="270"
                          Opacity="0.6"
                          BlurRadius="1"
                          Color="Red"/>
    </TextBlock.Effect>
</TextBlock>

This produces the following output:

If I set any Background color for the TextBlock, the shadow should disappear:

How can I set this property while keeping the drop shadow?

A: The DropShadowEffect doesn't disappear - it now applies to the whole rectangle.
This gives the desired effect:
<Border Background="Green">
    <TextBlock Foreground="Black" Text="All Tasks">
        <TextBlock.Effect>
            <DropShadowEffect ShadowDepth="1.2"
                              Direction="270"
                              Opacity="0.6"
                              BlurRadius="1"
                              Color="Red"/>
        </TextBlock.Effect>
    </TextBlock>
</Border>


text:
Q: how to display salesforce attachments in asp.net website to download we are creating asp.net website which uses salesfoce webservice api and pull all the information. We have a functionality within the site to display a contact "notes and attachments" which can be downloaded. I have been googling a lot about it, but no use.
Can any one guide me please.?
thanks,

A: You have to query the Attachment table, either directly:
SELECT Id, Name, Body, BodyLength, ContentType, CreatedBy.Name, CreatedDate, Description, Owner.Name, ParentId
FROM Attachment
LIMIT 10

Or indirectly with a subquery:
SELECT Id, Name, Email, (SELECT Name FROM Attachments ORDER BY CreatedDate DESC)
FROM Contact
LIMIT 10

The actual content of the file is stored in the Body column, base64-encoded. You'll have to decode it and (based on content type?) save as text / binary file, server to the user with the proper content header...
The inclusion of the Body column slows things down a bit - I'd recommend you skip it initially in the "see attachments related list" part of your ASP application and retrieve them (by Id for example) only when user actually wants it... I've noticed that you can get just 1 row returned (initially) with Body queried for so if you really want to do it all in one go - check out the documentation for queryMore() function and make sure your app has processed whole query locator ("cursor" if you're familiar with that word).
So, the above should work both in SOAP API and REST API as long as you can send queries (you didn't specify which one you use... "webservice api" sounds like you're limited to using few selected Apex classes exposed as webservice). Additionally REST API has special retrieve() command.


text:
Q: TypeError: member.guild.channels.get is not a function What can I do to fix the "TypeError: member.guild.channels.get is not a function"
client.on('guildMemberRemove', member => {
member.guild.channels.get('692319439542157435').send('**' + member.user.username + '**, has left the server');
})

A: member.guild.channels.cache.get('692319439542157435') for discord v12.
client.on('guildMemberRemove', member => {
    member.guild.channels.cache.get('692319439542157435').send('**' + member.user.username + '**, has left the server');
})


text:
Q: how to create search box to filter data first of all I'm using this site as a template for what I'm trying to do except im adding a search box on top of this: http://www.dougv.com/demo/jquery_sort_records/js.php (due to reference blocking you should copy and paste the link to view it. else you will run into a 403 forbidden error)
I want to create a simple search box that will search upon a certain attribute and display any results found (basically a filter). Here's what I have so far as part of the code.
so far the table appears well however I want to add a search box that will search upon the first name attribute.
any help?

<?php
            if(!$link = mysql_connect("database_server", "user_name", "password")) {
                echo "Cannot connect to db server";
            }
            elseif(!mysql_select_db("database_name")) {
                echo "Cannot select database";
            }
            else {
                if(!$rs = mysql_query("SELECT * FROM table")) {
                    echo "Cannot parse query";
                }
                elseif(mysql_num_rows($rs) == 0) {
                    echo "No records found";
                }
                else {
                    echo "
\n";
                    echo "
\n
";
                    echo "Record ID	";
                    echo "First Name	";
                    echo "Last Name	";
                    echo "Birthday	";
                    echo "Department	";
                    echo "
\n
\n";
                    while($row = mysql_fetch_array($rs)) {
                        echo "
$row[person_id]	$row[person_name]	$row[person_surname]	$row[person_birthdate]	$row[person_department]
\n";
                    }
                    echo "

\n";
                }
            }
?>

<form name="search_form" method="POST" action="js.php">

Search: <input type="text" name="search_b" value="" />
<input type="submit" name="search" value="Search for your term..."> </input>
</form>

A: First i would advise you to enclose array acces in strings like this: `" some tring {$array['key']} " thus you won't run into any problems accessing arrayfields directly in your string.
But that should do it now:

    <?php
    if (!$link = mysql_connect("database_server", "user_name", "password")) {
        echo "Cannot connect to db server";
    } elseif (!mysql_select_db("database_name")) {
        echo "Cannot select database";
    } else {
        $searchString = "";
        if(!empty($_POST['search_b'])){
            $searchString = "WHERE user_name LIKE '%{$_POST['search_b']}%'";
        }
        if (!$rs = mysql_query("SELECT * FROM table $searchString")) {
            echo "Cannot parse query";
        } elseif (mysql_num_rows($rs) == 0) {
            echo "No records found";
        } else {
            echo "
\n";
            echo "
\n
";
            echo "Record ID	";
            echo "First Name	";
            echo "Last Name	";
            echo "Birthday	";
            echo "Department	";
            echo "
\n
\n";
            while ($row = mysql_fetch_array($rs)) {
                echo "
{$row[person_id]}	{$row[person_name]}	{$row[person_surname]}	{$row[person_birthdate]}	{$row[person_department]}
\n";
            }
            echo "

\n";
        }
    }
    ?>

    <form name="search_form" method="POST" action="js.php">

        Search: <input type="text" name="search_b" value="" />
        <input type="submit" name="search" value="Search for your term..."> </input>
    </form>


text:
Q: What's going on in the opening comic? Cloubreakers is awesome, but I'm still not exactly sure what the premise (such as it is) is all about.  The little comic that shows every time you launch the game is a bit vague.
I can see Japan Friend in that third panel breaking apart, which explains why you need to collect three pieces of each character to unlock them, but everything else about this image is kind of confusing.  Is Strong Bro attacking them in the first panel?

A: Looking at the image provided, it looks like all the characters are attempting to help the one hanging off the side of the cliff and pull him back up, while the cliff gives in and breaks. As a result, everyone ends up falling and breaking apart.
I have not played this game before, so all of this is just an educated guess based on what I can see in the image.


text:
Q: Proof by induction that $n! > n^3$ where $n>5$ I have to prove by induction that $n! > n^3.$
This how far I've reached:
Induction Hypothesis:
$k! > k^3$.
Induction step:
Basically for Inductive step, I have to show that, $(k+1)! > (k+1)^3$.
L.S = $(k+1)! = k!(k+1)$
Where do I go from here? Any clues are appreciated. Thank you.

A: The induction from $k-1$ to $k$ is a little simpler.
$$k!=k(k-1)!>k(k-1)^3=k^3\frac{(k-1)^3}{k^2}=k^3\left(k-3+\frac{3k-1}{k^2}\right).$$
The last factor certainly exceeds $1$ as of $k=4$.

For a non-inductive proof,
$$n!=2\cdot3\cdots(n-2)(n-1)n>n^3$$ follows from
$$2(n-2)(n-1)>n^2$$
or $$n^2-6n+4>0$$
which is true for $n\ge6$.

A: For $k>5, $ $k>1+1+1>\frac3k+\frac3{k^2}+\frac1{k^3}$, so $k+1>(1+\frac1k)^3.$
Therefore, $k!>k^3\implies (k+1)!>(k+1)^3$.


text:
Q: Why we shouldn't use the primitive's boxed type version? Typescript manual mentions that we almost always must use the primitive types, but doesn't explain the reason behind it:

It can be tempting to think that the types Number, String, Boolean,
Symbol, or Object are the same as the lowercase versions recommended
above. These types do not refer to the language primitives however,
and almost never should be used as a type.

https://www.typescriptlang.org/docs/handbook/basic-types.html#about-number-string-boolean-symbol-and-object
https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html#number-string-boolean-symbol-and-object
If we shouldn't use them, then why are they even exist?
Can you elaborate it please?


text:
Q: Dynamically add or remove elements according to the value of checked radio button I've got some radio buttons with numeric values, that stand for the number of elements that should be rendered when I select one or another button. Here are they:
<input type="radio" id="one" class="render-input" name="renderVal" value="1" />
<input type="radio" id="two" class="render-input" name="renderVal" value="2" />
<input type="radio" id="three" class="render-input" name="renderVal" value="3" />
<input type="radio" id="four" class="render-input" name="renderVal" value="4" />

And I've got, for example, a

, which should be rendered the number of times that corresponds to checked input value. For example, if I check input#one, I should get rendered a

. If I check input#two, there must be

, and so on. Accordingly, if I checked, for example input#three and got rendered three

s,  and then check an input with lesser value (i.e. 1 or 2), it should display exactly this number of elemets, and not appending the new to existing ones. I tried to make it like this
$('.render-input').change(function () {
    for (var i = 1; i <= $(this).val(); i++)
        $(this).append('

');
});

But then the only way to decrement the number of elements rendered if an input with lesser value was checked is to remove all the elements and render them again, and this doesn't seem as a right and proper way to do that. How could I achieve that?

A: Your main issue here is that you're trying to append a div to an input, which is not possible. It would make more sense to specify a containing element and append them there. Also note that you should parse the value of the selected radio as an integer. Try this:

$('.render-input').change(function() {
  var html = '';
  for (var i = 0; i < parseInt(this.value, 10); i++) {
    html += '

';
  }
  $('#container').html(html);
});
#container div {
  width: 15px;
  height: 15px;
  border: 1px solid #c00;
  display: inline-block;
  margin-right: 10px;
}

<input type="radio" id="one" class="render-input" name="renderVal" value="1" />
<input type="radio" id="two" class="render-input" name="renderVal" value="2" />
<input type="radio" id="three" class="render-input" name="renderVal" value="3" />
<input type="radio" id="four" class="render-input" name="renderVal" value="4" />

A: Try this snippet
<input type="radio" id="one" class="render-input" name="renderVal" value="1" />
<input type="radio" id="two" class="render-input" name="renderVal" value="2" />
<input type="radio" id="three" class="render-input" name="renderVal" value="3" />
<input type="radio" id="four" class="render-input" name="renderVal" value="4" />

$('.render-input').change(function () {
var val="";
for (var i = 1; i <= $(this).val(); i++)
    val+='
Hi
';
$("#output").html(val);

});

Check its output here https://jsfiddle.net/11Lrwtue/


text:
Q: Converging sequence implies limit point Is it true that if a sequence in a metric space converges to a value, then that value is a limit point of the set of all terms in the sequence?

$E = \{ p_1, p_2, \dots, p_n , \dots \} \subset X$, where $X$ is some metric space. Say $ \left( p_n \right)_1^\infty$ converges to $p \in X$. Then $p$ is a limit point of $E$ or in other words, every open ball about $p$ has an element, different from $p$, in $E$.

Convergence of the sequence means $$ \forall \varepsilon >0, \exists N \in \mathbb{N}: n \geqslant N \implies d(p_n, p) < \varepsilon \ . $$
Fix an arbitrary $\varepsilon > 0$. Then we can always pick the open ball of radius $2 \varepsilon$ about $p$ which contains the point $p_n$. So every open ball about $p$ will have an element in $E$. But how can we be sure that $p_n \neq p$?
I suspect the hypotheses lack something and some extra requirement needs to be added e.g. $p_n \neq p$ for every $n \geqslant 1$. So the result may not be as general as expected?


text:
Q: adding acknowledgement in .tex file
Possible Duplicate:
Creating unnumbered chapters/sections (plus adding them to the ToC and/or header)

I want to thank my professor with mention in my LaTeX document, so I need to add a section (without section number) "acknowledgement" before the introduction in my .tex file . How can I write there?

A: To add a non numbered section you just use
\section*{Acknowledgement}

If you want to insert this section on the table of contents, use
\addcontentsline{toc}{section}{Acknowledgement}

after the first command.


text:
Q: Heap allocation of abstract class I am wondering why I cannot initialize an array of abstract objects to the stack but not the heap.
Here is some C++ code similar to mine that fails on the last line. I'm mainly just curious with the reasons behind this problem dealing with the heap vs. the stack. Thanks in advance!
#define ARRAY_SIZE 10

class Obj {
public:
    virtual void fn() =0;
};

class Sub : public Obj {
public:
    void fn() {
        // ...
    }
};

Obj * o1_array[ARRAY_SIZE];
Obj * o2_array = new Obj[ARRAY_SIZE]; // Compiler Error

A: You are doing two very different things. In the "stack" case,
Obj * o1_array[ARRAY_SIZE];

you are initializing an array of pointers. You don't need a complete or non-abstract type for this. In the "heap" case,
Obj * o2_array = new Obj[ARRAY_SIZE];

you are initializing an array of objects on the RHS and assigning the address of the first element to a pointer in the LHS. You need a complete, non-abstract type to build the array. If you want a dynamically-sized collection of pointers, a good bet is to use a container of pointers (assuming something else takes care of the management of the pointees' lifetime) or a container of smart pointers (where the smartness of the pointer decides who manages the pointee).
Non-managing:
std::vector<Obj*> o1_array(ARRAY_SIZE);

Managing (unique ownership):
std::vector<std::unique_ptr<Obj>> o1_array(ARRAY_SIZE);

For more options on containers managing "pointers", see the boost pointer container library.


text:
Q: How to receive HTML Post in console application? I'm currently using MVC to fetch data from a HTML POST ajax call. I want to transform my web application to a console application.
Ajax call:
$.ajax({
                  type: "POST",
                  url: '/Home/Final/',
                  dataType: "json",
                  data: JSON.stringify(response),
                  contentType: "application/json; charset=utf-8",
                  success: function () {
                      $('#messge').html('Response Saved').fadeIn();
                  },
                  error: function () {
                      $('#message').html('Error occured').fadeIn();
                  }

MVC code:
[HttpPost]
    public ActionResult Final(Something thing)
    {
        saveSomething(thing);
        return null;
    }

In other words, I currently call selenium to automatically fill some information on a website which then makes a POST call back to a MVC controller. Entity Framework works with or without MVC anyways.
I want to change my application to an .EXE so that I can call it periodically.
Is this possible?

A: read this post
http://www.asp.net/web-api/overview/hosting-aspnet-web-api/use-owin-to-self-host-web-api

i hope that helps you

A: Create a powershell script which invokes a web request to your controller by using Invoke-WebRequest function.
Invoke-WebRequest -ContentType application/json -Method POST -Uri https://yoururl

Then create a scheduled task in your web server and call that powershell script every 5 minutes
powershell -command "C:\Sample.ps1"


text:
Q: Why do data types like int and float have maximum values in C#, an int data type has a maximum value of 2,147,483,647 and
a float maximum value is 340282300000000000000000000000000000000
what causes these data types to have maximum values, where do those numbers come from?

A: They come from the fact that those types are limited to a certain number of bits. In the case of 2,147,483,647, we're talking about a 32-bit signed value. For 32-bits there are only 4,294,967,294 possible combinations of 1s and 0s. Half of those representations will be negative values, and half will be positive. (Well, actually, one of them will be 0, which is neither negative or positive, but you get the point.)
Let's look at a simple example. Let's take a 2-bit number. There are 4 possible combinations:
00 = 0
01 = 1
10 = 2
11 = 3

We can have 4 non-negative values. Or, if we want to include negatives, we can have 2 negatives, 0, and 1 positive:
00 = 0
01 = 1
10 = -2
11 = -1

For 3 bits, we get:
000 = 0
001 = 1
010 = 2
011 = 3
100 = 4
101 = 5
110 = 6
111 = 7

For signed values, we'd get:
000 = 0
001 = 1
010 = 2
011 = 3
100 = -4
101 = -3
110 = -2
111 = -1

To understand how the negative values are created you can read the Wikipedia article on 2s compliment format.
To understand floating point is more complicated, but it comes down to the same reason, ultimately. The number of bits used to represent the number limits how many values can be represented. (If you're interested you can read about IEEE 754 floating point format.)

A: Because those types are supposed to take up a single word (under most architectures), which allows arithmetic operations to be extremely fast due to ISA-level support. You can absolutely make a "true" integer or rational type (this is the approach taken by many functional and scripting languages), but this may reduce performance in certain programs.


text:
Q: getting only the last plot when plotting by below code I am getting c,d,e plots  but I am getting only the last plot for plt.plot
def normalize(x):
    return (x - x.min(0)) / x.ptp(0)
c=sns.distplot(mk[0]['mass'], hist=True, label='p', rug=True)
d=sns.distplot(mk[1]['mass'], hist=True, label='q', rug=True)
e=sns.distplot(mk[2]['mass'], hist=True, label='r', rug=True)
datadist=[c,d,e]
xd=dict()
yd2=dict()
for i in datadist:
    line = i.get_lines()[0]
    xd[i] = line.get_xdata()
    yd = line.get_ydata()
    yd2[i] = normalize(yd)
plt.plot(xd[c], yd2[c],color='black')
plt.plot(xd[d], yd2[d],color='yellow')
plt.plot(xd[e], yd2[e],color='green')

A: sns.distplot() returns the ax (the subplot) on which the histogram was drawn. All 3 are drawn on the same subplot, so the return value is the same three times.
The array lines = ax1.get_lines() contains exactly 3 elements: one for each of the kde curves, so you can extract them as follows:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

def normalize(x):
    return (x - x.min(0)) / x.ptp(0)

fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(14, 4))
sns.distplot(np.random.randn(30) + 10, hist=True, label='p', rug=True, ax=ax1, color='black')
sns.distplot(np.random.randn(30) + 15, hist=True, label='q', rug=True, ax=ax1, color='gold')
sns.distplot(np.random.randn(30) + 20, hist=True, label='r', rug=True, ax=ax1, color='green')

for line in ax1.get_lines():
    ax2.plot(line.get_xdata(), normalize(line.get_ydata()), color=line.get_color())
plt.show()

Now, if you just want the kde-curves and "normalize" them, you could use scipy.stats import gaussian_kde:
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde

def normalize(x):
    return (x - x.min(0)) / x.ptp(0)

fig, ax = plt.subplots(figsize=(12, 4))

mk0mass = np.random.randn(30) + 10
mk1mass = np.random.randn(30) + 15
mk2mass = np.random.randn(30) + 20
all_mkmass = [mk0mass, mk1mass, mk2mass]
x = np.linspace(min([mki.min() for mki in all_mkmass]) - 2,
                max([mki.max() for mki in all_mkmass]) + 2, 1000)
for mki, color in zip(all_mkmass, ['black', 'gold', 'green']):
    kde = gaussian_kde(mki)
    yd = normalize(kde(x))
    ax.plot(x, yd, color=color)
    ax.fill_between(x, 0, yd, color=color, alpha=0.3)
plt.show()