text:
Q: jquery Mobile pagecreate wont load function I am relatively new to jquery and jquery mobile. I have a new mobile site that uses the ajax loading of pages. The problem of course is that it will not load the script on each page so the script has to go onto the home page with the menu.
I use the pagecreate to listen for the page and then load the script for it.
The problem I am having is that on one page I have a submit button which calls a function. The pagecreate does its job and loads the script but when I click the submit button the function does not get called. The function is ok on it's own, so the problem must be that you cant just put a function into the pagecreate.
I am not sure what is the correct syntax.
        $('#calendar').live('pagecreate',function(event){
            function makeUpDates(){
                // concantenate values to date_start and date_end hidden inputs
                var dateString = document.getElementById('date').value,
                date = new Date(dateString);

                document.getElementById('date_start').value = date.getFullYear() + '-' + (date.getMonth()+1) + '-' + date.getDate();

                var numDays = document.getElementById('slider').value;
                date.setDate(date.getDate() + parseInt(numDays));

                var dateEnd = date.getFullYear() + '-' + (date.getMonth()+1) + '-' + date.getDate();
                document.getElementById('date_end').value = dateEnd;

            }
        });

A: I'm not really sure I'm getting it but why do you define a function in a function? That way it is never called, or do you want to call it later?
When you want that it is going to execute on pagecreate you can simply do:
$('#calendar').live('pagecreate',function(event){
// concantenate values to date_start and date_end hidden inputs
var dateString = document.getElementById('date').value,
date = new Date(dateString);

document.getElementById('date_start').value = date.getFullYear() + '-' + (date.getMonth()+1) + '-' + date.getDate();

var numDays = document.getElementById('slider').value;
date.setDate(date.getDate() + parseInt(numDays));

var dateEnd = date.getFullYear() + '-' + (date.getMonth()+1) + '-' + date.getDate();
});

A: UPDATE:
Would this work
HTML (page with id='calendar'), removed onclick and added id
<button type="submit" name="continue" id="continue" data-icon="arrow-r" data-iconpos="right">Continue</button>

JS
$('#calendar').live('pagecreate',function(event){
    // Call function when live event happens
    $('#continue').click(function() {
        makeUpDates();
    });
});

// Move function outside live event
function makeUpDates() {
    // concantenate values to date_start and date_end hidden inputs
    var dateString = document.getElementById('date').value,
    date = new Date(dateString);

    document.getElementById('date_start').value = date.getFullYear() + '-' + (date.getMonth()+1) + '-' + date.getDate();

    var numDays = document.getElementById('slider').value;
    date.setDate(date.getDate() + parseInt(numDays));

    var dateEnd = date.getFullYear() + '-' + (date.getMonth()+1) + '-' + date.getDate();
    document.getElementById('date_end').value = dateEnd;
}

I'm not sure you even need the live event, you could try this as well
//$('#calendar').live('pagecreate',function(event){
    // Call function when live event happens
    $('#continue').click(function() {
        makeUpDates();
    });
//});


text:
Q: How to delete a Contact in Android 2.2 with name ? I want to delete A Contact with special name.
I try below code to find my target :
public Cursor searchByName(String name)
    {
        try
        {
            ContentResolver cr = getContentResolver();
            Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
            if (cur.getCount() > 0)
            {
                while (cur.moveToNext())
                {
                    //String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                    String Name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                    if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
                    {
                        if(Name.equals(name))
                        {
                            return cur;
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
        }
        return null;
    }

and below Function to remove it :
public void removeContactByName(String name)
{
    try
    {
        Cursor cur = searchByName(name);
        if(cur!=null)
        {
            Uri uri ; // what should it be?
            getContentResolver().delete(uri,null, null);
        }
        else
        {
            Toast.makeText(getApplicationContext(), "Not Found",Toast.LENGTH_SHORT).show();
        }
    }
    catch (Exception e)
    {
        Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
    }
}

but what should uri be?

A: you can search for the Contact by name, and get it _id, after that, delete it by _id

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I send an array from a ViewController File to a Swift File (with no view controller)? I have looked at questions like this one, but they are not the same or I can't get a clear answer.
I have one array,
var numbers = ["one", "two", "three", "four", "five"]

located in a file attached to a view controller called numbers.swift. In a different file, a swift file that is not connected to any view controller called numbersTwo.swift has an array with nothing in it. How can I send numbers from numbers.swift to numbersTwo.swift and replace the array in the file?
Thanks in advance! :)

A: You can create the NumbersTwo.Swift file as a Singleton.
Read here: Apple -Singleton
Numbers ViewController:
class Numbers: ViewController{

    var numbers = ["one", "two", "three", "four", "five"]

    let numbersTwo = NumbersTwo.sharedInstance

    override func viewDidLoad() {
        super.viewDidLoad()

        numbersTwo.emptyArray.append(contentsOf: numbers)
    }
}

NumbersTwo Swift file:
class NumbersTwo{

    static let sharedInstance = NumbersTwo()

    var emptyArray = [String]() // this will no longer be empty
}


text:
Q: Changing the synched on-premise active directory to azure AD I've got a new customer which already has an Azure AD sync from his on-premise active directory with Azure AD Connect. The goal is to set up a new Azure AD Connect to sync a new different on-premise AD to the existing Azure AD. The customer is using Exchange Online primarily.
Is there anything I need to keep in mind beside having the same UPN for the users in the new onprem AD or has someone done such a migration before?
Unfortunately I didn't find any usefull informations yet for that specific topic.

A: It's not clear to me what you're trying to accomplish. Are you trying to sync users in a new on premises Forest/Domain to existing Azure AD users that were synced from a different on premises Forest/Domain?
You cannot have more than one Azure AD Connect instance syncing to one Azure AD instance. You can sync multiple on premises Forests/Domains to Azure AD with a single Azure AD Connect instance. The Azure AD Connect instance needs only network connectivity and DNS name resolution between the on premises Forests/Domains. No Forest/Domain trust is required.
https://docs.microsoft.com/en-us/azure/active-directory/hybrid/plan-connect-topologies
The users in the new Forest/Domain don't need to have the same UPN as the users in the existing Forest/Domain. They only need to have a UPN that matches one of your verified domains in Azure AD.
Forest/Domain A = user@contoso.com
Azure AD Verfified Domain A = contoso.com
Forest/Domain B = user@example.com
Azure AD Verified Domain B = example.com


text:
Q: Dynamically Select/Highlight Specific Rows on a DataGrid in WPF I'm trying to dynamically select/highlight a specific row on a DataGrid in WPF.
The grid rows are being validated as I iterate through them.  If a row's validation fails then I want the row to be selected/highlighted again so that the user will be prompted to fix the errors.
Which property in the DataGrid can I use to select/highlight a row after failed validation?

A: You wanna try something like this to highlight the row as you iterate through your results:
grid.Rows[i].DefaultCellStyle.BackColor = Color.Red;


text:
Q: What's the difference between require.config and requirejs.config I'm trying to set up requirejs and then optimise it using r.js, but then I'm confuse with these method. I've used require.config() before, but then I saw they also have requirejs.config() and I don't know what's the difference. Sample code:
require.config({
    baseUrl: 'js/lib',
    paths: {
        app: '../app'
    }
});

requirejs.config({
    baseUrl: 'js/lib',
    paths: {
        app: '../app'
    }
});

They both do the same thing. And when I optimise it, the result is exactly the same. I want to know what's the difference? When should I use on or the other?

A: "requirejs" is just an alias to the same API, since "require" is used by other libraries. From the documentation:

If you just want to load some JavaScript files, use the require() API. If there is already a require() in the page, you can use requirejs() to access the RequireJS API for loading scripts.

Even though it makes no technical difference, just by convention I would stay with require.config unless you have a naming conflict with some other module loader.
Results as of 6-Jun-2013:
https://stackoverflow.com/search?q=require.config (609 results)
https://stackoverflow.com/search?q=requirejs.config (258 results)


text:
Q: How can I recover XFS partitions from a formatted HD? I deleted the partition table of my HD. I wanted to format another one, but by mistake, I formatted the wrong one. Then I also created some new partition on it. Now I would like, if possible, to recover my old data. The old configuration was this:
A primary NTFS partition with Windows, and a secondary partition with four logical partitions: a swap and three XFS partitions (two for Ubuntu and OpenSuSE, and one with the home for both systems).
This is the output I get when I run gpart in a terminal:

ubuntu@ubuntu:~$ sudo gpart /dev/sdb
Begin scan...
    Possible partition(Windows NT/W2K FS), size(39997mb), offset(0mb)
    Possible extended partition at offset(39997mb)
        Possible partition(Linux swap), size(8189mb), offset(39997mb)
        Possible partition(SGI XFS filesystem), size(40942mb), offset(48187mb)
        Possible partition(SGI XFS filesystem), size(40942mb), offset(89149mb)
        Possible partition(SGI XFS filesystem), size(175044mb), offset(130112mb)
     End scan.
Checking partitions...
     Partition(OS/2 HPFS, NTFS, QNX or Advanced UNIX): primary
        Partition(Linux swap or Solaris/x86): logical
        Partition(Linux ext2 filesystem): logical
        Partition(Linux ext2 filesystem): orphaned logical
        Partition(Linux ext2 filesystem): orphaned logical
     Ok.
Guessed primary partition table:
     Primary partition(1)
        type: 007(0x07)(OS/2 HPFS, NTFS, QNX or Advanced UNIX)
        size: 39997mb #s(81915360) s(63-81915422)
        chs:  (0/1/1)-(1023/254/63)d (0/1/1)-(5098/254/51)r
Primary partition(2)
        type: 015(0x0F)(Extended DOS, LBA)
        size: 265245mb #s(543221849) s(81915435-625137283)
        chs:  (1023/254/63)-(1023/254/63)d (5099/0/1)-(38912/254/2)r
Primary partition(3)
        type: 000(0x00)(unused)
        size: 0mb #s(0) s(0-0)
        chs:  (0/0/0)-(0/0/0)d (0/0/0)-(0/0/0)r
Primary partition(4)
        type: 000(0x00)(unused)
        size: 0mb #s(0) s(0-0)
        chs:  (0/0/0)-(0/0/0)d (0/0/0)-(0/0/0)r

Looking the first eight lines, it seems the data are still there... but I don't know how to recover them. I have a free second HD of about 500 GB (the formatted one is 320 GB) that I can use for the recovery process.

A: gpart -W won't work, as it'll write out the new partition table that is being displayed after the first eight lines - which is in fact the new partition table.  TestDisk is an alternative that will allow you to select the partitions that then want restoring.

A: FIRST, do a copy of your hard disc to your free one, I think the best option would be to do read dd man page and then copy the disc
man dd
dd if=/dev/sda of=/dev/sdb

assuming /dev/sda is the old one with data and /dev/sdb is the new empty one.
SECOND, use devices from /dev/disk/by-id/* . This way you could avoid errors.
THIRD, remove the newly created partitions, so the found ones can be rewritten to the partition table. Use parted or fdisk.
FOURTH, read ALL the gpart mnan page, specially the "-W" option
man gpart
sudo gpart -W /dev/sdb

Hope this helps. But you have a backup, don't you?


text:
Q: Why the ZGC subphase of JVMTIWeakExport is always increasing? When I use ZGC on JDK11.0.8 in an online service, I find the time of Subphase weak roots JVMTIWeakExport is always increasing as our service is running. I want to know want made that?
Hope you will teach me.
enter image description here


text:
Q: InstantiationException for controllers in Play Framework after upgrading IntelliJ I keep getting an InstantiationException for my home controller with the following error:
[InstantiationException: project.ui.controllers.HomeController]
case project_ui_controllers_HomeController_index37(params) => {
   call {
        invokeHandler(play.api.Play.maybeApplication.map(_.global).getOrElse(play.api.DefaultGlobal).getControllerInstance(classOf[project.ui.controllers.HomeController]).index(), HandlerDef(this, "project.ui.controllers.HomeController", "index", Nil,"GET", """""", Routes.prefix + """"""))
   }
}

Here is the log output:
play.api.Application$$anon$1: Execution exception[[InstantiationException:     project.ui.controllers.HomeController]]
at play.api.Application$class.handleError(Application.scala:293) ~[play_2.10.jar:2.2.3]
at play.api.DefaultApplication.handleError(Application.scala:399) [play_2.10.jar:2.2.3]
at play.core.server.netty.PlayDefaultUpstreamHandler$$anonfun$3$$anonfun$applyOrElse$3.apply(PlayDefaultUpstreamHandler.scala:264) [play_2.10.jar:2.2.3]
at play.core.server.netty.PlayDefaultUpstreamHandler$$anonfun$3$$anonfun$applyOrElse$3.apply(PlayDefaultUpstreamHandler.scala:264) [play_2.10.jar:2.2.3]
at scala.Option.map(Option.scala:145) [scala-library.jar:na]
at play.core.server.netty.PlayDefaultUpstreamHandler$$anonfun$3.applyOrElse(PlayDefaultUpstreamHandler.scala:264) [play_2.10.jar:2.2.3]
at play.core.server.netty.PlayDefaultUpstreamHandler$$anonfun$3.applyOrElse(PlayDefaultUpstreamHandler.scala:260) [play_2.10.jar:2.2.3]
at scala.concurrent.Future$$anonfun$recoverWith$1.apply(Future.scala:344) [scala-library.jar:na]
at scala.concurrent.Future$$anonfun$recoverWith$1.apply(Future.scala:343) [scala-library.jar:na]
at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:32) [scala-library.jar:na]
at play.api.libs.iteratee.Execution$$anon$1.execute(Execution.scala:43) [play-iteratees_2.10.jar:2.2.3]
at scala.concurrent.impl.CallbackRunnable.executeWithValue(Promise.scala:40) [scala-library.jar:na]
at scala.concurrent.impl.Promise$DefaultPromise.tryComplete(Promise.scala:248) [scala-library.jar:na]
at scala.concurrent.Promise$class.complete(Promise.scala:55) [scala-library.jar:na]
at scala.concurrent.impl.Promise$DefaultPromise.complete(Promise.scala:153) [scala-library.jar:na]
at scala.concurrent.Future$$anonfun$map$1.apply(Future.scala:235) [scala-library.jar:na]
at scala.concurrent.Future$$anonfun$map$1.apply(Future.scala:235) [scala-library.jar:na]
at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:32) [scala-library.jar:na]
at scala.concurrent.forkjoin.ForkJoinTask$AdaptedRunnableAction.exec(ForkJoinTask.java:1361) [scala-library.jar:na]
at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260) [scala-library.jar:na]
at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339) [scala-library.jar:na]
at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979) [scala-library.jar:na]
at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107) [scala-library.jar:na]
Caused by: java.lang.InstantiationException: project.ui.controllers.HomeController
at java.lang.Class.newInstance(Class.java:359) ~[na:1.7.0_55]
at play.api.GlobalSettings$class.getControllerInstance(GlobalSettings.scala:181) ~[play_2.10.jar:2.2.3]
at play.api.DefaultGlobal$.getControllerInstance(GlobalSettings.scala:189) ~[play_2.10.jar:2.2.3]
at Routes$$anonfun$routes$1$$anonfun$applyOrElse$38$$anonfun$apply$110.apply(routes_routing.scala:496) ~[na:na]
at Routes$$anonfun$routes$1$$anonfun$applyOrElse$38$$anonfun$apply$110.apply(routes_routing.scala:496) ~[na:na]
at play.core.Router$HandlerInvoker$$anon$7$$anon$2.invocation(Router.scala:183) ~[play_2.10.jar:2.2.3]
at play.core.Router$Routes$$anon$1.invocation(Router.scala:377) ~[play_2.10.jar:2.2.3]
at play.core.j.JavaAction$$anon$1.call(JavaAction.scala:56) ~[play_2.10.jar:2.2.3]
at play.core.j.JavaAction$$anon$3.apply(JavaAction.scala:91) ~[play_2.10.jar:2.2.3]
at play.core.j.JavaAction$$anon$3.apply(JavaAction.scala:90) ~[play_2.10.jar:2.2.3]
at play.core.j.FPromiseHelper$$anonfun$flatMap$1.apply(FPromiseHelper.scala:82) ~[play_2.10.jar:2.2.3]
at play.core.j.FPromiseHelper$$anonfun$flatMap$1.apply(FPromiseHelper.scala:82) ~[play_2.10.jar:2.2.3]
at scala.concurrent.Future$$anonfun$flatMap$1.apply(Future.scala:251) ~[scala-library.jar:na]
at scala.concurrent.Future$$anonfun$flatMap$1.apply(Future.scala:249) ~[scala-library.jar:na]
at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:32) [scala-library.jar:na]
at play.core.j.HttpExecutionContext$$anon$2.run(HttpExecutionContext.scala:37) ~[play_2.10.jar:2.2.3]
at akka.dispatch.TaskInvocation.run(AbstractDispatcher.scala:42) ~[akka-actor_2.10.jar:2.2.0]
at akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(AbstractDispatcher.scala:386) ~[akka-actor_2.10.jar:2.2.0]
... 4 common frames omitted

I also find it interesting that i have no problem with this once i move the same code to production.
The route in conf/routes
GET / @project.ui.controllers.HomeController.index()

Guice Injector Global.java:
public class Global extends GlobalSettings {

private static final Injector INJECTOR = createInjector();

@Override
public void onStart(Application app) {
    super.onStart(app);
    new DatabaseSeeder().seed();
}

@Override
public <A> A getControllerInstance(Class<A> controllerClass) throws Exception {
    return INJECTOR.getInstance(controllerClass);
}

private static Injector createInjector() {
    return Guice.createInjector(new BusinessLayerModule(), new DataLayerModule(), new UtilitiesModule());
}
}

A: This was a problem with IntelliJ 13.1 not picking up the proper location for environment variables, and in turn, not being able to initialize Guice via Global.Java (for me, the location of Global.Java is defined in application.conf).
Prior to using IntelliJ 13.1, I had been able to specify an environment variable via a relative path:
config.file - application.dev.conf
Now, I have to use an absolute path:
config.file - /home/user/Enviroment/projects/project/conf/application.dev.conf


text:
Q: What is the best way to handle cross-thread events in C# I'm trying to develop a way to fire events from a thread and handle then on the main UI thread. In the event handlers I will be updating the UI, and I would rather not have to check for InvokeRequired everywhere.
I've seen a lot about this from searching, but I've not seen an example anywhere that will work 100% without the possible problems. I've come up with a solution which appears to work, and to the best of my knowledge, addresses the various problems I have read about. I would be keen to hear peoples opinions on this:
public static void SafeInvoke<T>(this EventHandler<T> source, object sender, T args) where T : System.EventArgs
{
    EventHandler<T> handler;

    lock (SyncRoot)
    {
        handler = Volatile.Read(ref source);
    }

    if (handler == null)
    {
        return;
    }

    foreach (Delegate d in handler.GetInvocationList())
    {
        ISynchronizeInvoke target = d.Target as ISynchronizeInvoke;

        if (target == null)
        {
            continue;
        }

        if (target.InvokeRequired)
        {
            target.BeginInvoke(d, new[] { sender, args });
        }
        else
        {
            handler(sender, args);
        }
    }
}

A: If you are working in .Net 3.5 or higher, you can use Reactive Extensions.  It is well suited for this kind of thing.
http://msdn.microsoft.com/en-us/data/gg577609.aspx


text:
Q: Oracle - Create Surrogate key for 300 million records There is a table with millions of records which has duplicate records as well. what is the process of creating a new entity as surrogate key (which denotes sequence no.)
E.g table structure
col1 col2
101   A
101   A
101   B
102   A
102   B
I would like to create a new column (col3) - which denotes a seq no.

col1 col2 col3
101   A    1
101   A    2
101   B    3
102   A    1
102   B    2
Please suggest me steps to follow to create surrogate key for existing records(300 million), and even when new records are loaded ( I assume trigger is needed to while inserting).

A: Just use row_number function to populate col3 :
For already existing records apply :
SQL> create table tab(col1 int , col2 varchar2(1));

Table created
SQL> insert all
  2         into tab values(101,'A')
  3         into tab values(101,'A')
  4         into tab values(101,'B')
  5         into tab values(102,'A')
  6         into tab values(102,'B')
  7  select * from dual;

5 rows inserted
SQL> create table tab_ as
  2  select col1, col2,
  3         row_number() over (partition by col1 order by col2) as col3
  4    from tab;

Table created
SQL> drop table tab;

Table dropped
SQL> alter table tab_ rename to tab;

Table altered

OR Alternatively ( without recreating the table ) :
SQL> create table tab(col1 int , col2 varchar2(1));

Table created
SQL> insert all
  2            into tab values(101,'A')
  3            into tab values(101,'A')
  4            into tab values(101,'B')
  5            into tab values(102,'A')
  6            into tab values(102,'B')
  7     select * from dual;

5 rows inserted
SQL> alter table tab add col3 integer;

Table altered
SQL> declare
  2   i pls_integer := 0;
  3 begin
  4   for c in
  5     (
  6      select rowid, col1, col2,
  7         row_number() over (partition by col1 order by col2) as col3
  8        from tab
  9     )
 10   loop
 11    update tab t
 12       set t.col3 = c.col3
 13     where t.rowid = c.rowid;
 14     i:= i+1;
 15     if ( ( i mod 10000 ) = 0 ) then commit; end if;
 16   end loop;
 17  end;
 18  commit;
 19  /

PL/SQL procedure successfully completed

SQL> select * from tab;

COL1 COL2  COL3
---- ---- -----
  101 A       1
  101 A       2
  101 B       3
  102 A       1
  102 B       2

  5 rows selected

For upcoming (newly inserted) records you may use a trigger as you mentioned :
SQL> create or replace trigger trg_ins_tab
  2  before insert on tab
  3  referencing new as new old as old for each row
  4  declare
  5  begin
  6      select nvl(max(col3),0) + 1
  7        into :new.col3
  8        from tab
  9       where col1 = :new.col1;
 10  end;
 11  /

Trigger created
SQL> insert into tab(col1,col2) values(101,'C');

1 row inserted
SQL> select *
  2    from tab t
  3   order by t.col1, col3;

COL1 COL2  COL3
---- ---- -----
  101 A       1
  101 A       2
  101 B       3
  101 C       4
  102 A       1
  102 B       2

  6 rows selected


text:
Q: WMIC command to find update Is there a way to find if multiple MS updates are installed using WMIC command:
wmic qfe | find  ?
Thanks

A: Similar to what you have in your question, you can do this:
wmic qfe | findstr /G:C:\Temp\KBs.txt

where C:\Temp\KBs.txt is the full path to a text file of the updates you are looking for.  You can list the KB #s on separate lines in the file to search for multiple updates.


text:
Q: I can't connect to my Database This is my error:

MySQL ERROR: Access denied for user 'www-data'@'localhost' (using password: NO)

And this is my set.php
<?php
$sitename = "http://www.URL.COM";
$link = mysql_connect("(ip site)", "root", "password");
$db_selected = mysql_select_db('database', $link);
mysql_query("SET NAMES utf8");

function fetchinfo($rowname,$tablename,$finder,$findervalue) {
    if($finder == "1") $result = mysql_query("SELECT $rowname FROM $tablename");
    else $result = mysql_query("SELECT $rowname FROM $tablename WHERE `$finder`='$findervalue'");
    $row = mysql_fetch_assoc($result);
    return $row[$rowname];
}
?>

I search all time answer but with no success.

A: As you're not using password, why you write like this:
$link = mysql_connect("(ip site)", "root", "password");

If your username = "root" on localhost then try to write the connection like the following way:
<?php

$link = mysql_connect('localhost', 'root', '{Your Password}');
if (!$link) {
    die('Not connected : ' . mysql_error());
}

$db_selected = mysql_select_db('{Your DB Name}', $link);
if (!$db_selected) {
    die ('Can\'t use {Your DB Name} : ' . mysql_error());
}

For details check: MySQL
Note: Try to use PDO or mysqli
MySQLi
PDO


text:
Q: receive api data from variable I'm trying to get the api data from the link which is stored in myData variable. But the error I get is
TypeError: myData.find is not a function
axios.get('https://hacker-news.firebaseio.com/v0/item/23150699.json')
  .then(res => {
    console.log(res.data.title)
  })
  .catch(err => {
    console.log(err);
});

let myData = 'https://hacker-news.firebaseio.com/v0/item/23150699.json';

app.get('/search/:name',(req, res) => {
  myData.find(req.params.name, (err, myData) => {
    if(err){
      res.send(err);
    }
      res.json(myData);
  });
});

A: there is not enough data to understand your post entirely, but the code will work and extract 'title' from the response

       let myData = 'https://hacker-news.firebaseio.com/v0/item/23150699.json';
       $.get(myData,(req, res) => {
          console.log(req.title);
       });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


text:
Q: Flask API facing InterfaceError with PostgreSQL I have a Flask API based on Flask RestPlus extension and is hosted on Google App Engine. The API does a basic job of fetching data from a Google Cloud SQL PostgreSQL. The API is working fine otherwise but sometimes it starts returning InterfaceError: cursor already closed.
Strangely, when I do a gcloud app deploy, the API starts working fine again.
Here's a basic format of the API:
import simplejson as json
import psycopg2

from flask import Flask, jsonify
from flask_restplus import Api, Resource, fields
from psycopg2.extras import RealDictCursor

app = Flask(__name__)
app.config['SWAGGER_UI_JSONEDITOR'] = True
api = Api(app=app,
          doc='/docs',
          version="1.0",
          title="Title",
          description="description")

app.config['SWAGGER_UI_JSONEDITOR'] = True
ns_pricing = api.namespace('cropPricing')

db_user = "xxxx"
db_pass = "xxxx"
db_name = "xxxxx"
cloud_sql_connection_name = "xxxxxx"

conn = psycopg2.connect(user=db_user,
                        password=db_pass,
                        host='xxxxx',
                        dbname=db_name)

@ns_pricing.route('/list')
class States(Resource):
    def get(self):
        """
        list all the states for which data is available

        """
        cur = conn.cursor(cursor_factory=RealDictCursor)
        query = """
                SELECT
                    DISTINCT state
                FROM
                    db.table
                """
        conn.commit()
        cur.execute(query)
        states = json.loads(json.dumps(cur.fetchall()))
        if len(states) == 0:
            return jsonify(data=[],
                           status="Error",
                           message="Requested data not found")
        else:

            return jsonify(status="Success",
                           message="Successfully retreived states",
                           data=states)

What should I fix to not see the error anymore?

A: It would be good to use the ORMs such as SQLAlchemy / Flask-SQLAlchemy which would handle the establishing / re-establishing the connection part.
Though, if using psycopg2. you can use try except to catch the exception and re-establish the connection again.
try:
    cur.execute(query)
except psycopg2.InterfaceError as err:
    print err.message
    conn = psycopg2.connect(....)
    cur = conn.cursor()
    cur.execute(query)


text:
Q: drop down menu href link not working on mobile view but working on desktop My code does not work on MOBILE VIEW but works on desktop, I have been trying to figure out what went wrong but have come to no solution.
This is my code:

.

              About

About Us

Leadership

Careers

Contact

Log in


text:
Q: php/mysql search query syntax I have a problem with my search query, $s_query.
The user can search a type (Date, Title, or Location) which corresponds to a colum in my mysql database
$search_type =mysql_real_escape_string($_POST['type']);
$search_query =mysql_real_escape_string($_POST['search_query']);

if ($search_query == "") {
  echo "
Please enter a search...
";
  exit;}

$s_query = "SELECT * FROM `posts` WHERE `$search_type` == `$search_query` ";

$s_result1=mysql_query($s_query);

if (!$s_result1) {
    die('Invalid query: ' . mysql_error());
    //header ("Location: /UC_page.html");
}

$s_row = mysql_fetch_array($s_result1);
$s_num1=mysql_numrows($s_result1);
mysql_close();

mysql_error says:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '== 1956'
i have tried every operator possible and every kind of syntax i could find, but im stuck.
at one point i got the date to work, but not any of the strings.
thanks in advance.

A: Actually you have two problems. First, you're surrounding your value with `, which is invalid. Use " or ' instead.
Also, == is not valid syntax, you need to use a single = instead. Although, looking at what you're doing, you probably want to use LIKE instead, for a case-insensitive search.
So this query should work:
SELECT * FROM `posts` WHERE `$search_type` = '$search_query'

Or with LIKE:
SELECT * FROM `posts` WHERE `$search_type` LIKE '$search_query'

A: You are putting ` (on top of the tab button) around your insert value. Those only go on the field. YOu shoudl use ' (on top of the slash button) for the value.

A: This might help you understand what query MySQL is expecting:
$s_query = "SELECT * FROM `posts` WHERE `" . $search_type . "` = " . $search_query;

Also make sure you add the necessary quotes to $search_query. EG: If it is a string then surround it with '.


text:
Q: How can I regenerate vendor/magento/module-directory/etc/config.xml? I am making changes in my store configuration. They are changing in the database but they don't actually appear in the frontend. It appears this file- vendor/magento/module-directory/etc/config.xml is overriding them. Can I regenerate that file based off what is in the database?

A: Did you do follow a tutorial similar to the following?
https://www.magestore.com/magento-2-tutorial/removedisable-magento-2-state-option/
Have you updated the config for every store scope? Have you cleared cache manually (delete var/cache)?
XML shouldn't override database.

A: For other people that run across this problem. My database was missing a line after the upgrade. This fixed it-
UPDATE core_config_data SET scope = "stores", path = 'general/region/display_all', value=1 WHERE config_id=1243;


text:
Q: Paginação com grande quantidade de dados Pensando em desempenho, qual a melhor maneira de paginar uma grande quantidade de dados?
Atualmente estou usando um List<Produtos>, guardando em torno de 500 produtos nela, e utilizando subList(min,max), retorna o que preciso. Porem, creio que essa não sejá a melhor solução e gostaria de saber outras alternativas para esse problema.
Edit
A ideia é maximizar o desempenho entre consultas desnecessarias no banco, pois o pool maximo do banco é 4.

A: Tive esse problema, resolvi com a dica da algaworks:
public List<Produto> filtrados(FiltroProduto filtro) {
    Criteria criteria = criarCriteriaParaFiltro(filtro);

    criteria.setFirstResult(filtro.getPrimeiroRegistro());
    criteria.setMaxResults(filtro.getQuantidadeRegistros());

    if (filtro.isAscendente() && filtro.getPropriedadeOrdenacao() != null) {
        criteria.addOrder(Order.asc(filtro.getPropriedadeOrdenacao()));
    } else if (filtro.getPropriedadeOrdenacao() != null) {
        criteria.addOrder(Order.desc(filtro.getPropriedadeOrdenacao()));
    }

    return criteria.list();
}

É claro que pode-se melhorar o filtro.
https://github.com/algaworks/aula-datatable-lazy-loading-primefaces


text:
Q: Python: Run a function of each n-th element of the lists contained in a list In Python, we have a list of list. For example:
a1 = [[1,4,3,5,6],[6,7,5,3,12],[1,6,4,1,2],[1,9,4,2,1]]

or
a2 = [[4,3,5,6],[6,7,5,12],[1,6,4,2],[1,9,2,1],[3,2,5,11]]

Both the length of a and the length of inside lists may vary. But all inside list always have the same length.
I'd like to apply some function to all lists made of the n-th element of each list.
Considering a2 for example, I'd like to apply iteratively a function to the list [4,6,1,1,3] (list of first elements), then to the list [3,7,6,9,2] (list of the second elements), etc…
the idea resemble to the function:
map(a2, my_function)

Except that my_function should not be applied to each inside list but to each list of n-th elements.
Hope that makes sense!
What is most pythonic way for performing such thing?

A: Use zip with * operator:
>>> a1 = [[1,4,3,5,6],[6,7,5,3,12],[1,6,4,1,2],[1,9,4,2,1]]
>>> a2 = [[4,3,5,6],[6,7,5,12],[1,6,4,2],[1,9,2,1],[3,2,5,11]]

>>> zip(*a1)
[(1, 6, 1, 1), (4, 7, 6, 9), (3, 5, 4, 4), (5, 3, 1, 2), (6, 12, 2, 1)]
>>> zip(*a2)
[(4, 6, 1, 1, 3), (3, 7, 6, 9, 2), (5, 5, 4, 2, 5), (6, 12, 2, 1, 11)]

>>> map(sum, zip(*a1)) # [1+6+1+1, 4+7+6+9, ...]
[9, 26, 16, 11, 21]


text:
Q: Mac App Store shows an update available for an app I didn't install Like this the picture below.
For the record, I did install some cracked apps which isn't available for demo from MAS to try them out. Could this be problem?
I'm on Mountain Lion, latest update. But I have experienced this problem on Lion as well.

A: According to http://hints.macworld.com/article.php?story=20120727110524438, you would want to check the /private/var/db/receipts/ folder for any files related to the app.
If the piracy messed with receipts, you may need exceptional records to clean up another app's receipt so this confusion might still be a result of your abuse of the normal app purchasing process.


text:
Q: Outlook 2010 integration with Gmail - configure trash location How can I configure Outlook 2010 to save deleted items to the Gmail/All Mail folder instead of the Gmail/Trash folder?
I have two computers, both with Outlook 2010 installed.  Using the same Gmail account simultaneously on two different computers,  Computer A saves deleted messages to the Gmail/Trash folder, while computer B saves deleted messages to the Gmail/All Mail folder.   Because both computers have these different behaviors using the same gmail account, I believe this is behavior is caused by a setting in outlook.
Additionally, computer A has a trashcan icon next to the Gmail/Trash folder

while computer B has the trashcan icon next to the Gmail/All Mail folder.  Note these are occurring simultaneously using the same gmail account.

How can I control this behavior?

A: To set the folder for Deleted items, go to File -> Account Settings and double click on the IMAP account. Click More Settings then follow the Deleted Items tab to make your selection.


text:
Q: Add progression bar to perl script Still new to perl and easy ways to work around it so I am seeking help !
I am sure this issue isn't a very difficult one to solve but I am still stuck nonetheless...
I would like to see the progression of this bit of my script:
my @goods = map {   my @vals = @{$ids_for{$_}};
                    my @matches = map { my $tf_id = $_;
                                        grep {$_ =~ $tf_id} @vals } @tf_ids;
                    my $num_match = scalar(@matches);
                    ## $num_match
                    for my $match ( @matches[0..($num_match-1)] ){
                        say {$out} "./" . $_ . ".fasta:" . $match if (scalar(@matches) > 0);
                    }

        } @keys;

## @goods

The input of the script is a file containing ids looking like this:
>7_54 lcl
>7_264 lcl
>7_332 lcl
>7_427 lcl
>7_598 lcl
>7_772 lcl

There are a couple thousands of them which is why I would like to know the progress made !
Thanks for your replies ! Let me know if you need any more essential info that I might have forgotten.

A: These methods was used for ages and does not require any modules or GUI and nevertheless they performed their function nicely.
NOTE: sleep delay added to simulate working progress for visual effect
use strict;
use warnings;
use feature 'say';

my @data = <DATA>;
chomp @data;        # snip eol
my $count = 0;
my $total = @data;

say "\nMethod #1";
for (@data) {
    $count++;
    say "[$count/$total] $_";
    sleep 1;
}

$| = 1;             # turn off output buffering

say "\nMethod #2";
$count = 0;
for (@data) {
    $count++;
    printf "[%d/%d] %s            \r",
            $count, $total, $_;
    sleep 1;
}

say "\nMethod #3";
$count = 0;
for (@data) {
    $count++;
    printf "[%.2f %%] %s            \r",
            100*$count/$total, $_;
    sleep 1;
}

say "\nMethod #4";
$count = 0;
for (@data) {
    $count++;
    my $percent = 100*$count/$total;
    printf "%-16s %6.2f %% %-51s 100%%\r",
            $_, $percent , '=' x int($percent/2) . '>';
    sleep 1;
}

say "\nBonus";
my @spinner = ('-','\\','|','/');
for (@data) {
    $count++;
    printf "[%d/%d] %6.2f%%  %s\r",
        $count, $total,
        100*$count/$total,
        $spinner[$count%4];
    sleep 1;
}

say "\nDone...";

__DATA__
>7_54 lcl
>7_264 lcl
>7_332 lcl
>7_427 lcl
>7_598 lcl
>7_772 lcl
>7_54 lcl
>7_264 lcl
>7_332 lcl
>7_427 lcl
>7_598 lcl
>7_772 lcl
>7_54 lcl
>7_264 lcl
>7_332 lcl
>7_427 lcl
>7_598 lcl
>7_772 lcl
>7_54 lcl
>7_264 lcl
>7_332 lcl
>7_427 lcl
>7_598 lcl
>7_772 lcl


text:
Q: iPhone Programming Table I added a table to my app, and with that table, I added a scroll bar, just like the contancts in the iPhone.  The scroll is working with the letters, but i have a problem with it,  under letter A, i get letter A names, but in letter B I'm getting the same names of letter A.
The same words in the .plist of the array of list A is repeating in all the rest of the lists.
What can I do??
Note: add your own .plist file to see what outcome it gives.
#import "SimpleTableViewController.h"

@implementation SimpleTableViewController

@synthesize exercises;

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {

    if(searching)
        return nil;

    NSMutableArray *tempArray = [[NSMutableArray alloc] init];
    [tempArray addObject:@"A"];
    [tempArray addObject:@"B"];
    [tempArray addObject:@"C"];
    [tempArray addObject:@"D"];
    [tempArray addObject:@"E"];
    [tempArray addObject:@"F"];
    [tempArray addObject:@"G"];
    [tempArray addObject:@"H"];
    [tempArray addObject:@"I"];
    [tempArray addObject:@"J"];
    [tempArray addObject:@"K"];
    [tempArray addObject:@"L"];
    [tempArray addObject:@"M"];
    [tempArray addObject:@"N"];
    [tempArray addObject:@"O"];
    [tempArray addObject:@"P"];
    [tempArray addObject:@"Q"];
    [tempArray addObject:@"R"];
    [tempArray addObject:@"S"];
    [tempArray addObject:@"T"];
    [tempArray addObject:@"U"];
    [tempArray addObject:@"V"];
    [tempArray addObject:@"W"];
    [tempArray addObject:@"X"];
    [tempArray addObject:@"Y"];
    [tempArray addObject:@"Z"];

    return tempArray;
}

- (void)viewDidLoad {

    NSString *myFile = [[NSBundle mainBundle] pathForResource:@"A" ofType:@"plist"];

    exercises = [[NSArray alloc]initWithContentsOfFile:myFile];
    [super viewDidLoad];

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    if (section ==0) return 5;
    if (section ==1) return 2;
    if (section ==2) return 5;
    if (section ==3) return 5;
    if (section ==4) return 6;
    if (section ==5) return 5;
    if (section ==6) return 5;
    if (section ==7) return 5;
    if (section ==8) return 5;
    if (section ==9) return 5;
    if (section ==10) return 5;
    if (section ==11) return 5;
    if (section ==12) return 5;
    if (section ==13) return 5;
    if (section ==14) return 5;
    if (section ==15) return 5;
    if (section ==16) return 5;
    if (section ==17) return 5;
    if (section ==18) return 5;
    if (section ==19) return 5;
    if (section ==20) return 5;
    if (section ==21) return 5;
    if (section ==22) return 5;
    if (section ==23) return 5;
    if (section ==24) return 5;
    if (section ==25) return 5;
    return 0;

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell= [tableView dequeueReusableCellWithIdentifier:@"cell"];

    if (cell == nil)
    {
    cell=[[UITableViewCell alloc]
                           initWithStyle:UITableViewCellStyleSubtitle/*Default*/// change default to subtitle
                           reuseIdentifier:@"cell"];
    }

    cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    //cell.accessoryType=UITableViewCellAccessoryDetailDisclosureButton;

    cell.textLabel.text=[exercises objectAtIndex:indexPath.row];
    cell.detailTextLabel.text=@"Click me...";

    return cell;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 26;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:
(NSInteger)section
{
        if (section == 0) return @"Letter A";
        if (section == 1) return @"Letter B";
        if (section == 2) return @"Letter C";
        if (section == 3) return @"Letter D";
        if (section == 4) return @"Letter E";
        if (section == 5) return @"Letter F";
        if (section == 6) return @"Letter G";
        if (section == 7) return @"Letter H";
        if (section == 8) return @"Letter I";
        if (section == 9) return @"Letter J";
        if (section == 10) return @"Letter K";
        if (section == 11) return @"Letter L";
        if (section == 12) return @"Letter M";
        if (section == 13) return @"Letter N";
        if (section == 14) return @"Letter O";
        if (section == 15) return @"Letter P";
        if (section == 16) return @"Letter Q";
        if (section == 17) return @"Letter R";
        if (section == 18) return @"Letter S";
        if (section == 19) return @"Letter T";
        if (section == 20) return @"Letter U";
        if (section == 21) return @"Letter V";
        if (section == 22) return @"Letter W";
        if (section == 23) return @"Letter X";
        if (section == 24) return @"Letter Y";
        if (section == 25) return @"Letter Z";

        return @"Other";

}

- (void)viewDidUnload {
}

- (void)dealloc {
    [super dealloc];
}

@end

A: You're ignoring the section number in cellForRowAtIndexPath, so if when the tableView asks for section 1 row 3 (the fourth entry in the B section), then you're returning the fourth entry in your exercises array in the "A" section.  You'll either need to restructure "exercises" to allow you to index by section (first letter), then by row, OR calculate the appropriate entry in exercises.
You should read Apple's documentation on TableViews. See "Creating and Configuring a Table View" section called "Populating an Indexed List" for help in creating an array of arrays. There's an example in Apple's TableView suite.
If you really don't want to restructure your plist into an array of arrays as suggested, then you can brute-force calculate the appropriate row in your exercises matrix as follows...
Instead of
cell.textLabel.text=[exercises objectAtIndex:indexPath.row];

Try:
int realRow = indexPath.row;
for (int i = 0; i < indexPath.section; i++ ) {
    realRow += [self tableView:tableView numberOfRowsInSection:i];
}

cell.textLabel.text=[exercises objectAtIndex:realRow];

A: you should definitely change the structure of your data. I would recommend you to use nested arrays.
You would create one rootarray. And in this array you put 26 arrays where each array holds the content for one section.
and instead of writing if (section ==0) return 5;
    if (section ==1) return 2;
    if (section ==2) return 5;
    if (section ==3) return 5;
    if (section ==4) return 6; ... you could write return [[exercises objectAtIndex:section] count];
One line instead of 26. Cool, isn't it?
And in cellForRowAtIndexPath you would write something like this:
cell.textLabel.text= [[exercises objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];


text:
Q: recursion, how branch exploration works? so, I kinda know how recursion works, to simplify, a function call itself until a condition is met. Now, I am reading eloquentJavaScript, its great. It explain recursion with the following example:

function findSolution(target) {
  function find(current, history) {
    if (current == target) {
      return history;
    } else if (current > target) {
      return null;
    } else {
      return find(current + 5, `(${history} + 5)`) ||
             find(current * 3, `(${history} * 3)`);
    }
  }
  return find(1, "1");
}

console.log(findSolution(13));
// result: (((1 * 3) + 5) + 5)

Now this function with the help of recursion find out how, starting from 1, you can obtain a number only by multiplying by three or adding 5, if possible. If not it returns null, if you match the number it will print the passages (history),thus exiting the recursion.
What I can't understand is how can it guess the sequence of adding and multiplying and do the branching thing. The find function return null if the number more than target, return history if equal, try to add 5 calling itself, or multiplying by 3 also by calling itself. So it shouldn't be able to guess the path to 13, instead it works.
Javascript wise, how is this possible?
Here is how it explains it
To better understand how this function produces the effect we're looking for, let's look at all the calls to find that are made when searching for a solution for the number 13.
  find(6, "(1 + 5)")
    find(11, "((1 + 5) + 5)")
      find(16, "(((1 + 5) + 5) + 5)")
        too big
      find(33, "(((1 + 5) + 5) * 3)")
        too big
    find(18, "((1 + 5) * 3)")
      too big
  find(3, "(1 * 3)")
    find(8, "((1 * 3) + 5)")
      find(13, "(((1 * 3) + 5) + 5)")
        found!

How can it goes back? Please help me

A: What may be missing in your knowledge is how the memory stack is handled during the recursions. Let's do it step by step.
Calling
find(1, "1")

Those variables are in memory stack #0:

*

*current is 1

*history is "1"

*target is 13
Makes:
find(1 + 5, `(${"1"} + 5)`) || find(1 * 3, `(${"1"} * 3)`);

The first operand will be attempted... So

Calling
find(1 + 5, `(${"1"} + 5)`)

Those variables are in memory stack #1:

*

*current is 6

*history is "(1 + 5)"

*target is 13
Makes:
find(6 + 5, `(${"(1 + 5)"} + 5)`) || find(6 * 3, `(${"(1 + 5)"} * 3)`);

Calling
find(6 + 5, `(${"(1 + 5)"} + 5)`)

Those variables are in memory stack #2:

*

*current is 11

*history is "((1 + 5) + 5)"

*target is 13
Makes:
find(11 + 5, `(${"((1 + 5) + 5)"} + 5)`) || find(11 * 3, `(${"((1 + 5) + 5)"} * 3)`);

Calling
find(11 + 5, `(${"((1 + 5) + 5)"} + 5)`)

Those variables are in memory stack #3:

*

*current is 16

*history is "(((1 + 5) + 5) + 5)"

*target is 13
It now hits the condition
else if (current > target) {
  return null;
}

// That is:
else if (16 > 13) {
  return null;
}

Memory stack #3 is discarded and memory stack #2 is popped, so the second operand will be evaluated:

*

*current is 11

*history is "((1 + 5) + 5)"

*target is 13
We now have:
null || find(11 * 3, `(${"((1 + 5) + 5)"} * 3)`);

Get it? We never attempted the second operand yet...
Continue doing it step by step like this and note down the variable values for each recursion step. When it returns, pop a stack and continue until it is all popped.
Also carefully note down who is the caller for each recursion step to know where the returned value goes.


text:
Q: Unable to fetch cookies, set by Play framework server, in Angular $http call? I have been trying to get hold of the cookies I am setting in the server using PlayFramework:
response().setHeader(SET_COOKIE, AppConstants.COOKIE_USER_SESSIONID+"="+appSession.getSid());

in the angular app, but am not able to.
If I use the Advanced Rest client, I get the SetCookie header and the cookies get set in the call that follows. However when I call the same api through my angular app, I am not able to  get the header in the response and hence no cookies for the app.
Here's what I have already tried:

*

*renaming the environment from localhost to xyz.com since I read on multiple answers that cookies do not work at localhost.

*Tried the api form a separate rest client, was able to fetch the header successfully, so the API looks fine to me.

There should be some catch in angular code which I am not able to figure out. Any help on this is highly appreciated. Thanks.
Angular code snippets:
LoginController:
angular.module('wratApp')
  .controller('LoginCtrl', function (postService, wratSettings, wratRoutes, $location, $cookies) {
    $("#header").hide();

    this.user= {};

    this.logUserin = function(){
        console.log("User: " + this.user.email + " & pwd: " + this.user.pwd);
        var payLoad = {};
        payLoad.ldap = this.user.email;
        payLoad.pwd = this.user.pwd;
        postService.postPromise(wratRoutes(wratSettings).POST_USER_LOGIN(),payLoad)
          .then(function(){ //login success
              console.log("login success");
              $location.path(wratRoutes().CLIENT_HOME());
          }, function(){ //error in login
              console.log("Login failed");
          })
        ;
    }

  });

postService:
angular.module('wratApp')
  .factory('postService', function ($http, $q, $cookies, $location) {

    function postService() {

      var self = this;

      self.postPromise = function (uri,payload){

        var deferred = $q.defer();

        $http.post(uri,payload)
          .success(function(data, status, headers, config){
            console.log("Got response cookies: "+$cookies.getAll());
            deferred.resolve(data);
          })
          .error(function(data, status, headers, config){
            if(status == 401){
              angular.forEach($cookies.getAll(), function (v, k) {
                $cookies.remove(k);
              });
              $location.path('/login');
            }else{
              deferred.reject(data);
            }
          });

        return deferred.promise;

      }

    }

    return new postService();
  });

Now, my login succeeds but without any cookies being set by the server. Also, the PlaySession cookie which is somehow visible in the debugger(the manually set ones are even absent from debugger), is not in the angular $cookies variable(refer image below).

Please suggest how can I resolve this. Thanks.
Update 1:
If I run the Play server not in debug mode, the cookies are appropriately being sent by the server. It's an issue with the angular app where in the following call, it's not transferring the values form the Set-Cookie header to the cookies for the next call. It might be some silly mistake on my end too. Please see if you can help me figure out.
Server response /login:
HTTP/1.1 200 OK
Vary: Origin
Set-Cookie: sid=1e6823e24554598b0521ca5f64d7746b; Path=/
Set-Cookie: PLAY_SESSION=953d9d5730bf1b77cccaadef6b78c209e59d924b-sid=1e6823e24554598b0521ca5f64d7746b; Path=/; HTTPOnly
Content-Type: application/json; charset=utf-8
Access-Control-Allow-Origin: http://wrat.com:9009
Access-Control-Allow-Methods: OPTIONS, GET, POST
Access-Control-Allow-Credentials: true
Date: Thu, 24 Sep 2015 22:27:03 GMT
Content-Length: 429

The following request which should have cookies set, but no cookies there :-( :
GET /products/all HTTP/1.1
Host: wrat.com:9000
Accept: application/json, text/plain, */*
Origin: http://wrat.com:9009
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36
Referer: http://wrat.com:9009/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8

Taking off the Play framework tag since it's not a play issue anymore.

A: Adding the withCredentials option to the $http calls worked for me and resolved the issue.
$http.post(uri,payload, {withCredentials: true})

The issue is with the ajax calls where if this withCredentials flag is not truthy at both server and client, the cookies set by server are not maintained for cross-origin calls. Hence it was totally ignoring the cookies I was setting from the server.
Text from following question helped resolve the problem:
Why is jquery's .ajax() method not sending my session cookie?
from:

I am operating in cross-domain scenario. During login remote server is
  returning Set-Cookie header along with
  Allow-Access-Control-Credentials set to true.
The next ajax call to remote server should use this cookie.
CORS's Access-Control-Allow-Credentials is there to allow cross-domain
  logging. Check https://developer.mozilla.org/En/HTTP_access_control
  for examples.
For me it seems like a bug in JQuery (or at least feature-to-be in
  next version).
UPDATE:
Cookies are not set automatically from AJAX response (citation:
  http://aleembawany.com/2006/11/14/anatomy-of-a-well-designed-ajax-login-experience/)
Why?
You cannot get value of the cookie from response to set it manually
  (http://www.w3.org/TR/XMLHttpRequest/#dom-xmlhttprequest-getresponseheader)
I'm confused..
There should exist a way to ask jquery.ajax() to set
  XMLHttpRequest.withCredentials = "true" parameter.
ANSWER: You should use xhrFields param of
  http://api.jquery.com/jQuery.ajax/
The example in the documentation is:
$.ajax({    url: a_cross_domain_url,    xhrFields: {
        withCredentials: true    } }); It's important as well that server answers correctly to this request. Copying here great comments
  from @Frédéric and @Pebbl:
Important note: when responding to a credentialed request, server must
  specify a domain, and cannot use wild carding. The above example would
  fail if the header was wildcarded as: Access-Control-Allow-Origin: *
So when the request is:
Origin: http://foo.example Cookie: pageAccess=2 Server should respond
  with:
Access-Control-Allow-Origin: http://foo.example
  Access-Control-Allow-Credentials: true
[payload] Otherwise payload won't be returned to script. See:
  https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials


text:
Q: Downloadable product event if someone click on the document (pdf) included I need to trigger an event if an user click a downloadable product, i mean the document (pdf, word, etc...) included because i need my customer read those documents, and after that i need to do some action
Is there any event dispatched by downloadable product or i need to create a custom event?
Thank you very much

A: When you check on linkAction()(This action is responsible when you click on download) from
app\code\core\Mage\Downloadable\controllers\DownloadController.php . From this action, I can say that there is no event used by Magento. I think you need to overwrite this action to dispatch your event to perform some action.


text:
Q: Learning automated trading in X3: Albion Prelude So I finally managed to learn trading in X3: Albion Prelude and equipped my Mercury with the MK3 trading software.
Since then the function "Start sector trading" is available. But when I use it, the status of the ship switches to "buying 0 energy cells" and then switches back to "standby". Why does automated trading not work? Am I doing something wrong?
Any help is highly appreciated.

A: Your trader isn't doing any work because there are no good trades available in the sector. Find a sector where things that are produced also get consumed (Power Plant -> Wheat Farm -> Distillery, for example), or, if you believe the sector they are in fits that criteria, leave them alone and they will try again after a while (You can also reissue the command to get them to seek new traders immediately, as they will standby for some time before attempting to find another deal).
As your trader levels up, you will be able to increase the range in which they will seek deals, and when they reach level 8, they will be able to become Universe Traders (though their range for finding deals will still be limited, they will not feel obliged to stick around the same neighbourhood, and their trading may take them to any point in the galaxy where profitsss can be made).
You will need to reissue the sector trader command to get the option to increase the number of jumps in which they will seek deals.
It may be a good idea to leave them as sector traders with a big radius even after they've leveled up, as some parts of the universe are much more dangerous than the others (The area around Argon Prime, for example, is super safe, while Omicron Lyrae is close to many pirate and Xenon sectors).
P.S. the reason your automated traders sometimes loop through wares with "Buy x ware" orders is because that's how they assess available trades.


text:
Q: unhide rows on sheet2 based on the values of checkboxes on sheet1 I have a workbook with three worksheets. On the first worksheet the user is asked to click "relevant" checkboxes that relate to their project. Based on these checkboxes one thing happens but on two worksheets:
On the first worksheet (same as checkboxes)
1. related rows appear when checked and disappear when not checked. This I have managed to figure out using the following code for each checkbox (I have 8 checkboxes):
Private Sub CheckBox1_Click()
    [22:25].EntireRow.Hidden = Not CheckBox1
End Sub

On the second worksheet
2. Same as above but on a different sheet, I would like the same result of related rows appearing when checked and disappear when not checked. I am not sure how to refer to another worksheet, and / or if there is a way to insert another line to the above.
Any help is appreciated.


text:
Q: Price: In or For When talking about price, we usually use for ... for $1 or ...for a dollar.
But in the following question using for sounds strange to me. I think in suits better. Maybe, it's because of my first language.

What would you buy, an apple in $1 or an apple, a cherry and an orange in $1?

for sounds natural if rephrased

What would you buy for a dollar, an apple or an apple, a cherry and an orange?

Is it ok to say, use only for when talking about price?


text:
Q: Atomic aggregate check before update I have a table with many records, an enumerated column, and a highly multithreaded environnement.
CREATE TYPE status AS ENUM
    ('UNCONFIRMED', 'REGISTERED', 'VALIDATED', 'PAID');

Our system allows 6000 validated statuses, precisely. This value is dynamic and will increase later but will never go down.
We have to check the number of validated records before allowing the update:
SELECT count(*) FROM table WHERE status='VALIDATED';

*

*If the result is below < 6000 (for a start), we change the status to
validated.

*If the result is >= 6000, we do not change the status, and
throw an Exception.

*We must never go above that number

I though about:

*

*isolation levels

*table lock

*select for update

*update where + a subquery (see below)

*another?

UPDATE table
   SET status='VALIDATED'
   WHERE (
        SELECT count(*)<6000 FROM table WHERE status='VALIDATED'
   ) AND id=:id;

Which would be the best way to do this and guarantee atomicity between hundred of threads?

A: My suggestion :
(a) Create a dedicated status_counter table with a constraint on the counter column which checks that its value remains under the limit (6000) :
CREATE TABLE status_counter (status status primary key, counter integer CHECK (counter < 6000)) ;

(b) Set up the counter :
INSERT INTO status_counter
SELECT 'VALIDATED', count(*) FROM my_table WHERE status='VALIDATED' ;

(c) Update the status_counter table by trigger on table when a new row is inserted or updated :
CREATE OR REPLACE FUNCTION table_insert ()
RETURNS trigger LANGUAGE plpgsql AS
$$
BEGIN
  IF NEW.status = 'VALIDATED'
  THEN
      UPDATE status_counter
         SET counter = counter + 1
       WHERE status='VALIDATED' ;
  END IF ;
  RETURN NEW ;
END ;
$$ ;

CREATE OR REPLACE TRIGGER table_insert BEFORE INSERT ON table
FOR EACH ROW EXECUTE FUNCTION table_insert() ;

CREATE OR REPLACE FUNCTION table_update ()
RETURNS trigger LANGUAGE plpgsql AS
$$
BEGIN
  IF NEW.status IS NOT DISTINCT FROM 'VALIDATED'
  AND OLD.status IS DISTINCT FROM 'VALIDATED'
  THEN
      UPDATE status_counter
         SET counter = counter + 1
       WHERE status='VALIDATED' ;
  ELSEIF NEW.status IS DISTINCT FROM 'VALIDATED'
  AND OLD.status IS NOT DISTINCT FROM 'VALIDATED'
  THEN
      UPDATE status_counter
         SET counter = counter - 1
       WHERE status='VALIDATED' ;
  END IF ;
  RETURN NEW ;
END ;
$$ ;

CREATE OR REPLACE TRIGGER table_update BEFORE UPDATE OF status ON table
FOR EACH ROW EXECUTE FUNCTION table_update() ;

(d) Starting from now, each time a user inserts or updates a row in table, the counter is updated by trigger, and the update fails when the counter reaches the limit raising an exception and preventing the row to be inserted or updated.
The atomicity between hundred of threads should be guaranteed because they all attempt to update the same unique row in table status_counter.
demo in dbfiddle.

A: "update where + a subquery" will not be sufficient, you would need to couple it with a table lock, an advisory lock, or an increased isolation level.  Otherwise it will allow multiple updates in flight at the same time to complete and exceed the count.
"select for update" seems like a horrible idea. It would have to lock every row in the table for every attempt, which would generate a huge amount of churn.  And it still might miss some depending whether rows are ever inserted with status='VALIDATED'


text:
Q: Is it possible to dump my Oracle Database to rebuild it on another machine? As the title asks, i have a complete oracle Xe11g database, that i have to export on my teacher machine in order to "show" it, i saw some examples of databases dumps all over the internet but i couldn't quite understand the process, is someone kind enough to explain me if a database dump can be rebuilt into another machine with the same oracle Xe11g ?
I have preserved the original sql queries files, but those are a little bit messy.

A: As it is 11gXE, a simple option is to use (the original) export and import utilities. Why not data pump? These two are simpler and will do the job.
Here's an example: I have user named mike which will "act" as if it was your user, in your XE database.
c:\Temp>exp system/pwd owner=mike file=mike.dmp log=mike_exp.log

Export: Release 11.2.0.2.0 - Production on ╚et Svi 14 20:56:52 2020

Copyright (c) 1982, 2009, Oracle and/or its affiliates.  All rights reserved.

Connected to: Oracle Database 11g Express Edition Release 11.2.0.2.0 - 64bit Production
Export done in EE8MSWIN1250 character set and AL16UTF16 NCHAR character set
server uses AL32UTF8 character set (possible charset conversion)

About to export specified users ...
. exporting pre-schema procedural objects and actions
. exporting foreign function library names for user MIKE
. exporting PUBLIC type synonyms
. exporting private type synonyms
. exporting object type definitions for user MIKE
About to export MIKE's objects ...
. exporting database links
. exporting sequence numbers
. exporting cluster definitions
. about to export MIKE's tables via Conventional Path ...
. . exporting table                           TEST          0 rows exported
. exporting synonyms
. exporting views
. exporting stored procedures
. exporting operators
. exporting referential integrity constraints
. exporting triggers
. exporting indextypes
. exporting bitmap, functional and extensible indexes
. exporting posttables actions
. exporting materialized views
. exporting snapshot logs
. exporting job queues
. exporting refresh groups and children
. exporting dimensions
. exporting post-schema procedural objects and actions
. exporting statistics
Export terminated successfully without warnings.

c:\Temp>

I'll now drop it so that my database won't have mike any more, and that will "act" as if it was your teacher's XE database. You - or your teacher - will not do that.
c:\Temp>sqlplus sys/pwd as sysdba

SQL*Plus: Release 11.2.0.2.0 Production on ╚et Svi 14 20:29:28 2020

Copyright (c) 1982, 2014, Oracle.  All rights reserved.

Connected to:
Oracle Database 11g Express Edition Release 11.2.0.2.0 - 64bit Production

SQL> drop user mike cascade;

User dropped.

SQL>

Now, you'd put the mike.dmp file to USB memory stick (or mail it to your teacher if it isn't too large). Teacher will first have to create user mike and then import your mike.dmp file.

This will your teacher do:
c:\Temp>sqlplus sys/pwd as sysdba

SQL*Plus: Release 11.2.0.2.0 Production on ╚et Svi 14 20:50:20 2020

Copyright (c) 1982, 2014, Oracle.  All rights reserved.

Connected to:
Oracle Database 11g Express Edition Release 11.2.0.2.0 - 64bit Production

SQL> select tablespace_name from dba_tablespaces;

TABLESPACE_NAME
------------------------------
SYSTEM
SYSAUX
UNDOTBS1
TEMP
USERS

SQL> create user mike identified by lion
  2  default tablespace users
  3  temporary tablespace temp
  4  quota unlimited on users;

User created.

SQL> grant create session to mike;

Grant succeeded.

SQL>

Import:
c:\Temp>imp system/pwd file=mike.dmp full=y log=mike_imp.log

Import: Release 11.2.0.2.0 - Production on ╚et Svi 14 21:00:04 2020

Copyright (c) 1982, 2009, Oracle and/or its affiliates.  All rights reserved.

Connected to: Oracle Database 11g Express Edition Release 11.2.0.2.0 - 64bit Production

Export file created by EXPORT:V11.02.00 via conventional path
import done in EE8MSWIN1250 character set and AL16UTF16 NCHAR character set
import server uses AL32UTF8 character set (possible charset conversion)
. importing SYSTEM's objects into SYSTEM
. importing MIKE's objects into MIKE
. . importing table                         "TEST"          0 rows imported
Import terminated successfully without warnings.

c:\Temp>

That's it; teacher how has your schema in their database, can connect as mike and review everything you've done.

A: If the target host has oracle installed you can import
the dump
https://docs.oracle.com/en/database/oracle/oracle-database/19/sutil/oracle-data-pump.html#GUID-501A9908-BCC5-434C-8853-9A6096766B5A


text:
Q: Fast copy of mysql database gets error I need to copy over a large mysql database with myisam tables. The fastest way for me to do it is by copying over the mysql/data directory. The .MYI and .MYD files copy over smoothly. However, copying the .frm file is causing mysql to show an error when I query the database. :
#1033 - Incorrect information in file: 'mytable.frm'

When I did the copy I stopped the mysql server. Also, I made sure that the owner and permissions are set correctly. The repair table command wouldn't work either because of the same aforementioned error. What am I doing wrong here?
(A possible solution would be to do a mysqldump of just the data structure which would be a fast process and then I would only need to copy over the .MYI and .MYD files. However, I would like to know what I am doing wrong with the copy before I go on a more complicated route)
Update
Following up on @RickJames comments - Here is a more detailed explanation of what I am doing:
I'm using cp command on a Linux server to copy files from one db to another db on the same server. The version that I am using  mysql  Ver 14.12 Distrib 5.0.77 did not work. Inspired by @RickJames comment, I  tried doing the same operation on a different server with mysql  Ver 14.14 Distrib 5.6.29 and it worked beautifully. That being said, I'm still intrigued as to why it doesn't work with the older version


text:
Q: Import pandas throws errors on one server, works fine on another. Same python install (via conda) I have one of the simplest scripts in the world:
import pandas as pd

and throws errors when I run it:
python3 pandas_import.py

Errors
Traceback (most recent call last):
  File "pandas_import.py", line 1, in <module>
    import pandas as pd
  File "/environment/anaconda3/envs/conda_env/lib/python3.9/site-packages/pandas/__init__.py", line 11, in <module>
    __import__(dependency)
  File "/environment/anaconda3/envs/conda_env/lib/python3.9/site-packages/numpy/__init__.py", line 155, in <module>
    from . import random
  File "/environment/anaconda3/envs/conda_env/lib/python3.9/site-packages/numpy/random/__init__.py", line 180, in <module>
    from . import _pickle
  File "/environment/anaconda3/envs/conda_env/lib/python3.9/site-packages/numpy/random/_pickle.py", line 1, in <module>
    from .mtrand import RandomState
  File "mtrand.pyx", line 1, in init numpy.random.mtrand
  File "bit_generator.pyx", line 40, in init numpy.random.bit_generator
  File "/environment/anaconda3/envs/conda_env/lib/python3.9/secrets.py", line 19, in <module>
    from random import SystemRandom
  File "random.py", line 10, in <module>
    FOUT.write(line('a',2))
  File "/environment/anaconda3/envs/conda_env/lib/python3.9/gzip.py", line 284, in write
    data = memoryview(data)
TypeError: memoryview: a bytes-like object is required, not 'str'

The weird thing is I have a shared conda environment on a shared directory. I can access the exact same conda install via multiple servers.  This works fine on one server and errors out like the above on a different server.  I even cleared out my .bashrc and .bash_profile scripts and that didn't help.
Any suggestions?  I've been banging my head on this one all day.  Not sure what's causing a single line python script to error out.


text:
Q: Questions about phonegap I built a mobile website using jquery mobile (client side) and php/mysql (server side)
I found phonegap to put it in a native app. But despite many researches, i didnt found the answer for those questions :

*

*how do phonegap loads pages in those two cases :
When the page refreshes without ajax
When a jqm page is loaded and injected with ajax

This question is crucial because if the page is loaded from my server, i would be able to put php into it. If pages are stored and brought directly from the client where the app is installed, I have to remove all php from my pages. On the other side, storing pages on the client would improve drastically the speed of the loading.
The best would be to choose for each ajax call of jqm, by a parameter, whether the first or the second scenario. Controlers written in php and returning json would be loaded from the server each time, but the jqm pages would be stored into the client phone as he download the app.
I have a second question:i ve downloaded the phonegap desktop app but i still dont know how to build an entiere app sendable to the stores. I found several technologies like phonegap build, do you recomand it ? i dont know a word in java..
Thanks for your help and please excuse me if Im wrong with english sometime.


text:
Q: My Panel's components are not drawn if JOptionPane is drawn So I have a class which creates the following GUI the first time it the weapon's button is clicked on:

Every button on the side I click on should switch to a different panel accordingly. However, currently, I am just working on the weapons panel. To save on memory I decided to save whatever was typed in the search box and if the user decides to open the panel again the application searches up the list again. Currently, I have only one item called test as you see, my problem is if I type something in the search box, that is not available and I switch panels, this is my result:

The expected result is supposed to be the error message but with the search box, buttons and the JList still available with the JList showing "No Weapons Listed".
Now when I remove the JOptionPane I get the following which is half the result:

I would like to know why when the error message appears the panel is not drawn?
PS: I had entered some console messages, one after the Joptionpane and the other before the return statement and they both get printed correctly
Here is my code for the panel:
    private static JPanel searchMenu() {

    JPanel pnl = new JPanel();
    pnl.setOpaque(false);
    pnl.setLayout(new BorderLayout());

    Object[] search = search();

    if(search.length == 0) {
        JOptionPane.showMessageDialog(MyFrame.getFrame(),
                  "No weapons with your search criteria has been found.\n"
                + "What you type in the search box is searched for in the weapon names, classnames and their description.\n",
                "No Weapon found", JOptionPane.ERROR_MESSAGE);

        search = new Object[] {"No Weapons listed"};
    }

    System.out.println(search.length);

    DefaultListModel list = new DefaultListModel();
    for(Object o: search) list.addElement(o);

    JList searched = new JList();

    searched.setModel(list);
    searched.setPreferredSize(new Dimension(250, 700));
    searched.setFont(new Font("Tahoma", Font.PLAIN, 15));

    pnl.add(searched, BorderLayout.WEST);

    pnl.add(weaponDisplay(lastSelec),BorderLayout.CENTER);

    JPanel space = new JPanel();
    space.setOpaque(false);
    pnl.add(space,BorderLayout.SOUTH);

    return pnl;
}

A: It looks like you're adding components to a container after it's been made visible. At a minimum, you'll need to validate() the enclosing container, as shown here, and possibly invoke repaint(). A better approach is to add the view component, e.g. JList, to the layout and update its model, e.g. ListModel, as required. In this example, a JList listens to a nearby table's model.

A: JOptionPane's dialogs are modal, so they stop execution of the calling code until the dialog is closed. So you'll want to populate and show the list first, with "No weapons listed" as its contents, before showing the message dialog.


text:
Q: 'str' object has no attribute 'to_string' in Pandas I have a dataframe:
| column1  | column2        |
| -------- | -------------- |
| abc      | 1              |
| def      | 16             |
| ghi      | 982            |

I'm selecting a row and using to_string(index=False) on it.
something = df.loc(df['column2'] == 982]
print(something.column1.to_string(index=False))

I'm doing this repeatedly over a large dataframe and 99 times out of 100 it's fine. Every once in a while though, I get AttributeError: 'str' object has no attribute 'to_string'.
There's nothing unusual about the data in the instances where this happens. What could be causing this?

A: One case I can think of where this might happen if your column name happens to be the name of a string property of the DataFrame itself, since you end up calling to_string() on an actual string.
Here's an (unlikely) example to demonstrate.
df = pd.DataFrame({"col1": ['foo', 'foo', 'bar'], "_info_axis_name": [1,2,3]})
df._info_axis_name.to_string()

> AttributeError: 'str' object has no attribute 'to_string'

Perhaps check your column names are not clashing, or use df['col'] instead of df.col to select the column?


text:
Q: what are the differences between JSLINK and Client Side rendering in SharePoint Server 2013 I have read many articles about client side rendering & JSLINKs but i am unable to differentiate between these two topics. now I have used JSLINK to implement 2 things inside my SharePoint server:-

*

*I wanted to prevent users from editing a site column inside the Quick Edit grid. and to achieve this i created a JavaScript file, which mainly disable the column inside the quick edit (AllowGridEditing = false), then i define the javascript file to be the JSLINK for the site column using powershell code .
$web = Get-SPWeb http://*****
$field = $web.Fields["Item Number"]
$field.JSLink = "~siteCollection/Style Library/JS/HideItemNumberInQuickEdit.js"
$field.update($true)

*I also used JSLINK to create a non-standard list view, where i define a javascript which render the view, and I link the list view's JSLINK with the javascript.
so I am a bit confused if JSLINK is a sub topic under client side rendering? or client side rendering in SharePoint 2013, means creating JSLINKs for site columns, list views etc.?

A: Client-Side Rendering is simply a term for when the data is transformed using the client rather than the server. This means using client-side technologies, such as HTML and JavaScript. It allows us to style SharePoint elements using JavaScript, rather than having to write XSLT. You can use it to style complete List Views, Fields, Search Results and more. This makes it a lot simpler and more intuitive, especially for web developers who haven't used SharePoint before.
When talking about Client Side Rendering in SharePoint, there are really 2 mechanisms: search Display Templates, and JSLink.
So JSLink is nothing but one of the mechanisms in Client Side Rendering. It is a property available on many SharePoint objects, including Fields, Lists, Views, and Content Types. In its simplest form, the JSLink property simply adds a JavaScript file to the page. Depending on the JavaScript, this could then do anything – either related to the object of which it was attached, or something completely irrelevant if desired.
This is an excellent blog which I referenced about Introduction to Client-Side Rendering in SharePoint 2013.


text:
Q: Why does maven install give this error with npm? I did a merge of two branches and just after that I get the following error:

[ERROR] Failed to execute goal
  com.github.eirslett:frontend-maven-plugin:1.6:install-node-and-npm
  (install node and npm) on project frontend: Could not extract the npm
  archive: Could not extract archive:
  'C:\Users\User.m2\repository\com\github\eirslett\npm\5.6.0\npm-5.6.0.tar.gz':
  EOFException -> [Help 1]

I looked on google and stackoverflow but didn't find anything that fixes it.
What should I try?
(Spring back-end with Angular front-end)

A: Just delete this folder from your local repository, and run your build again:
**delete => C:\Users\User.m2\repository\com\github\eirslett**

It seems that npm tar.gz was corrupted during the download.


text:
Q: Case in-sensitive Jboss 7 web application context root Is there a way to make web application context case in-sensitive?
Basically i'm doing the following in jboss-web.xml
<jboss-web>
    <context-root>cap</context-root>
</jboss-web>

I'm able to access the app via localhost:8080/cap, but trying to make it accessible via localhost:8080/Cap or localhost:8080/CAP. Any ideas please?

A: Put apache+mod_proxy in front of jboss and use url-rewriting or redirection (easier option).
Example of rewrite:
RewriteEngine on
RewriteRule ^/Cap$ /cap/ [R]
RewriteRule ^/CAP$ /cap/ [R]

You would put the above to httpd.conf or a similar location.


text:
Q: MongoDB tweet hashtags coincidence count I have some tweets downloaded to my mongodb.
The tweet document looks something like this:
{
    "_id" : NumberLong("542499449474273280"),
    "retweeted" : false,
    "in_reply_to_status_id_str" : null,
    "created_at" : ISODate("2014-12-10T02:02:02Z"),
    "hashtags" : [
       "Canucks",
       "allhabs",
       "GoHabsGo"
    ]
    ...
}

I want a construct a query/aggregation/map-reduce that will give me the count of tweets that have the same two hash tags. For every pair of nonequal hashtags it gives me the count of tweets eg.:
{'count': 12, 'pair': ['malaria', 'Ebola']}
{'count': 1, 'pair': ['Nintendo', '8bit']}
{'count': 1, 'pair': ['guinea', 'Ebola']}
{'count': 1, 'pair': ['fitness', 'HungerGames']}
...

I've made a python script to do this:
hashtags = set()

tweets = db.tweets.find({}, {'hashtags':1})
#gather all hashtags from every tweet
for t in tweets:
    hashtags.update(t['hashtags'])

hashtags = list(hashtags)

hashtag_count = []
for i, h1 in enumerate(hashtags):
    for j, h2 in enumerate(hashtags):
        if i > j:
            count = db.tweets.find({'hashtags' : {'$all':[h1,h2]}}).count()
            if count > 0:
                pair = {'pair' : [h1, h2], 'count' : count}
                print(couple)
                db.hashtags_pairs.insert(pair)

But I want to make it just with a query or JS functions to use the map-reduce.
Any ideas?

A: There's no aggregation pipeline or query that can compute this from your given document structure, so you'll have to use map/reduce if you don't want to drastically change the collection structure or construct a secondary collection. The map/reduce, however, is straightforward: in the map phase, emit a pair (pair of hashtags, 1) for each pair of hashtags in the document, then sum the values for each key in the reduce phase.
var map = function() {
    var tags = this.tags;
    var k = tags.length;
    for (var i = 0; i < k; i++) {
        for (var j = 0; j < i; j++) {
            if (tags[i] != tags[j]) {
                var ts = [tags[i], tags[j]].sort();
                emit({ "t0" : ts[0], "t1" : ts[1] }, 1)
            }
        }
    }
}

var reduce = function(key, values) { return Array.sum(values) }


text:
Q: Best way to track maximal distance in a set of points? Assume that I have a collection of 2 dimensional points, and a way to determine the distance between them.  This collection is frequently modified, with additional points being added and existing points being removed.  At any given time, I need to know the maximal and minimal distances between the points, that is, the distance between the two points furthest apart, and the distance between the two points closest together.  is there a data structure or algorithm that lends itself particularly well to this task?  I would prefer not to have to recalculate the entire set of distances each time that the points change.

A: Theoretically, you can do this efficiently by storing the convex hull of the points you have.
Whenever you add a new point, test to see if it lies in the interior of this polytope or not. If so, the max distance is preserved. If not, then it may have changed.
Similarly, if you delete a point from the interior, the maximum distance (diameter) is preserved, so change nothing. However, if you delete a boundary point, then the convex hull must be recomputed.
If you are in 2 dimensions, then when you add or remove from the boundary, at most two sides of the polygon are affected. These should be easy to compute, depending on how you store the information (a sequence of line segments, for example).
Coding this may be a bit of a pain, but the simplest way is to mark the points on the boundary, and then have a function that tests if a point lies inside the convex hull of the marked points or not.

A: Rather than using a convex hull (as suggested in another answer) can you use a Delaunay triangulation??
Min distance:
To calculate the minimum distance from a node to any other in the set you should only need to check the immediate neighbours of the node, i.e. the ones connected to it by an edge in the triangulation.
So if a new node is inserted, update the triangulation, find the neighbours of the new node and any other nodes that were "involved" in the update, compute the distances for all nodes in this local "updated" set and check whether a new minimum was found. Similarly, if an existing node is deleted, again update the triangulation and recompute the distances for all nodes "involved".
There are a class of so-called "incremental" algorithms that can be used to build Delaunay triangulations that only require local modifications of the overall triangulation when inserting/deleting new nodes, so this is the type of approach I'd suggest for frequent insertions/deletions.
Max distance:
As suggested in the convex hull style answer, you would only need to recompute the distances between boundary nodes if a new node was added outside of the existing triangulation or if an existing boundary node was deleted.
Hope this helps.

A: I'm not at all sure this is best, but it's the best I can think of right now.
Save the max together with a set of pairs of points at that distance.  (The max is not necessarily unique.)
Same of course for the min.

*

*When you add a point, compute the new point's distance to all other points, and replace your saved max and min together with its corresponding set of endpoint pairs if the new point participates in a better max or min, or update the set of endpoints if it matches the current best.

*When you remove a point, check whether that clears an entire remembered minimum or maximum enpoint set.  If not, you need do nothing.  But if it is, I think you'll need to recompute everything.
For the maximum computation, I believe PengOne's suggestion can tell you if you can skip the computation entirely.


text:
Q: how to change Mysql server hostname I run my service in docker-compose. And MySQL host name is "mysql", when I develop in my computer, MySQL host name is "localhost".
Now I want to change my computer MySQL hostname to "mysql". So I can connect MySQL on my computer by mysql+pool://root:password@mysql/test_db.
Please help me, I find solution spend lots of time.

A: It is recommended to separate this connection string setting to an environment variable.
If you really want to use mysql, you can modify your OS's hosts file (e.g. for macOS or many linux distros, it should be /etc/hosts).
and put 127.0.0.1    mysql at the end of the file.


text:
Q: Convert Array to JSON, with Same Key, in Ruby I'm trying to parse an array of hashes, grab a value from a specific key, and output to json with one predefined key for each value - and I'm stuck.
Array:
[{:object_id=>"jon-59",
  :name=>"jon-59-gw (8db8fcae-055a-4b35-9f8f-739b68c0bd5d)",
  :client_handle=>nil,
  :extended_attributes=>nil,
  :appliances_summary=>
   {:vm_version=>"5.5.3",
    :vm_build_info=>"5.5.3-2135647"},
  :hypervisor_assist=>false,
  :allowed_actions=>
   {:string=>
     ["Change Log Level",
      "Edit Dns",
      "Edit Syslog"]},
  :edge_assist_id=>"0"},
 {:object_id=>"jon-60",
  :name=>"jon-60-gw (d63ddc45-gd3c-40c3-9046-e7afa996934a)",
  :client_handle=>nil,
  :extended_attributes=>nil,
  :appliances_summary=>
   {:vm_version=>"5.5.3",
    :vm_build_info=>"5.5.3-2168697"},
  :hypervisor_assist=>false,
  :allowed_actions=>
   {:string=>
     ["Change Log Level",
      "Edit Dns",
      "Edit Syslog"]},
  :edge_assist_id=>"0"}]

Desired Output
{
  "data":[
    { "{#JONNAME}":"jon-59-gw" },
    { "{#JONNAME}":"jon-60-gw"},
  ]
}

Where I'm at:
def jon_discover
  jon_summary.sort_by { |jon| jon[:object_id] }.each do |jon|
    name = jon[:name].slice!(/\A\S*/)
    my_hash = {'{#JONNAME}' => name}
    puts JSON.generate(my_hash)
  end
end

The above returns:
{ "{#JONNAME}":"jon-59-gw" }
{ "{#JONNAME}":"jon-60-gw" }
But I don't know where to take it from here, or if I'm on the right track. How can I get this into the desired output?

Thanks, cheers!

A: This is too complex:
my_hash = {"{#JONNAME}" => "#{name}"}

Keep it simple:
my_hash = {JONNAME => name}

the data is for Zabbix low level discovery

Then use single-quotes instead of double quotes for the key and use the bare name for the value:
my_hash = {'{#JONNAME}' => name}

so it's more apparent that {# is not a typo.

Instead of:
"jon-60-gw (d63ddc45-gd3c-40c3-9046-e7afa996934a)".slice!(/\A\S*/) # => "jon-60-gw"

Use:
"jon-60-gw (d63ddc45-gd3c-40c3-9046-e7afa996934a)".split.first # => "jon-60-gw"

Putting it all together:
require 'json'

ary = [
  {
    :object_id => "jon-59",
    :name => "jon-59-gw (8db8fcae-055a-4b35-9f8f-739b68c0bd5d)",
    :client_handle => nil,
    :extended_attributes => nil,
    :appliances_summary =>
    {
      :vm_version => "5.5.3",
      :vm_build_info => "5.5.3-2135647"
    },
    :hypervisor_assist => false,
    :allowed_actions =>  {
      :string =>  ["Change Log Level", "Edit Dns", "Edit Syslog"]
    },
    :edge_assist_id => "0"
  },
  {
    :object_id => "jon-60",
    :name => "jon-60-gw (d63ddc45-gd3c-40c3-9046-e7afa996934a)",
    :client_handle => nil,
    :extended_attributes => nil,
    :appliances_summary =>  {
      :vm_version => "5.5.3",
      :vm_build_info => "5.5.3-2168697"
    },
    :hypervisor_assist => false,
    :allowed_actions =>  {
      :string =>  ["Change Log Level", "Edit Dns", "Edit Syslog"]
    },
    :edge_assist_id => "0"
  }
]

Here's how to walk through the data:
data = ary.map{ |hash|
  {
    '{#JONNAME}' => hash[:name].split.first
  }
}

Here's how to generate the JSON:
puts JSON[{'data' => data}]
# >> {"data":[{"{#JONNAME}":"jon-59-gw"},{"{#JONNAME}":"jon-60-gw"}]}

If you need it sorted:
puts JSON[{'data' => data.sort_by{ |s| s['{#JONNAME}'] }}]
# >> {"data":[{"{#JONNAME}":"jon-59-gw"},{"{#JONNAME}":"jon-60-gw"}]}


text:
Q: Access db as localhost from docker container I'm pretty new to Docker but am trying to use it to clean up some of my projects. One such project is a fairly simple PHP/MySQL application. I've "docker-ized" the app by adding a docker-compose.yml with db and php services. Here's my docker-compose.yml:
version: '2'
services:
  php:
    build: .
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./public_html:/var/www/html
    links:
      - db
  db:
    image: mysql:5.5
    ports:
      - "3306:3306"
    environment:
        MYSQL_USER: root
        MYSQL_PASSWORD:
        MYSQL_ROOT_PASSWORD:
        MYSQL_ALLOW_EMPTY_PASSWORD: 'yes'
    volumes:
      - /c/dockerdata:/var/lib/mysql

This works correctly however I have to change all my PHP scripts to use "db" instead of "localhost" when connecting to the mysql database. I'm adding the docker stuff just as a way to clean up development so I'm trying to avoid changing the PHP code itself. Is there a way I can configure this so I'm able to use localhost or 127.0.0.1 to connect?

A: You can achieve this using below two steps
1) Add below CMD to your Dockerfile
CMD sed -e '/localhost/ s/^#*/#/' -i /etc/hosts
2) Replace 'db' with 'localhost' in docker-compose.yml
links:
      - db
  db:
    image: mysql:5.5
as
links:
      - localhost
  localhost:
           image: mysql:5.5

A: Docker doesn't allow you to modify /etc/hosts on containers Known issue
You can edit /etc/hosts with entrypoint option
Create entrypoint.sh script
#!/bin/bash
cp /etc/hosts /tmp/hosts
sed -e '/localhost/ s/^#*/#/' -i /tmp/hosts
cp /tmp/hosts /etc/hosts
# add your command here to run php application

Add execute permissions to entrypoint.sh
chmod +x entrypoint.sh

Add below two lines to Dockerfile
ADD entrypoint.sh /entrypoint.sh
ENTRYPOINT /entrypoint.sh

Now do the step 2) from my previous answer.


text:
Q: Performance comparison between MySQL queries and static caching I am planning to implement a caching system for my site that receives decent traffic. Sometimes MySQL server is overloaded that's why I'm caching MySQL results in static (cached) files. Here is what I do:

*

*First of all, I check for cache file (page specific)

*If it doesn't exist, I query database and I serialize the results

*I write results to the cache file

*When file exists, I get content with file_get_contents() function and unserialize the data

Now my question is, will my caching strategy improve performance or should I keep using database queries for every request?

A: There are many ways to speed up your web site and to lower database load. Those are much better then trying to make manual cache files. Here are some of them:

*

*Optimize database settings (so many interesting moments!)

*Use memory tables

*Add CPU\RAM to web server

*Use caching servers like nginx or varnish (those can put whole static pages to cache)

*Use special data caching in PHP - like memcached

*Use sockets instead of TCP\IP connection to database

*Use mysql-nd instead of mysql

And here is the answer to your exact question: PHP - Is it good practice to cache MYSQL queries in a txt file?


text:
Q: EL 5.0 toggling logging on/off I am using enterprise library 5.0 for logging and I am not sure how to switch off the logging. Currently it is switched on and workng as it should.
Here is my web.config section on logging, it was created with automatically with the EL 5.0 GUI.
<loggingConfiguration name="" tracingEnabled="true" defaultCategory="Logging Only">
    <listeners>
      <add name="Flat File Trace Listener"
           type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=..."
           listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=..."
           fileName="WMSlog.log" formatter="Text Formatter" />
      <add enabled="false" name="Formatted EventLog TraceListener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=..."
           listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=..."
           source="Exception Handling" formatter="Text Formatter" />
    </listeners>
    <formatters>
      <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=..."
           template="Timestamp: {timestamp}{newline}
Message: {message}{newline}
Category: {category}{newline}
Machine: {localMachine}{newline}
App Domain: {localAppDomain}{newline}
ProcessId: {localProcessId}{newline}
Process Name: {localProcessName}{newline}
Thread Name: {threadName}{newline}
Win32 ThreadId:{win32ThreadId}{newline}"
           name="Text Formatter" />
    </formatters>
    <categorySources>
      <add switchValue="Information" name="Logging Only">
        <listeners>
          <add name="Flat File Trace Listener" />
        </listeners>
      </add>
      <add switchValue="Error" name="Errors Only">
        <listeners>
          <add name="Formatted EventLog TraceListener" />
        </listeners>
      </add>
    </categorySources>
    <specialSources>
      <allEvents switchValue="All" name="All Events" />
      <notProcessed switchValue="All" name="Unprocessed Category" />
      <errors switchValue="Information" name="Logging Errors & Warnings" />
    </specialSources>
  </loggingConfiguration>

I have replaced my data with ... in some lines above.
At the moment I'm using this to log to a file:
if (Logger.IsLoggingEnabled())
{
    Logger.Write("Some text...");
}

I need to be able to make Logger.IsLoggingEnabled() return false, how do I do that?

A: Just use the Logging Enabled filter for this. See http://msdn.microsoft.com/en-us/library/ff664548%28v=PandP.50%29.aspx.


text:
Q: Time selections on InfluxDB I have some stock price data in InfluxDB with columns Ticker and Price. For example:
 Time  Ticker Price
------ ------ ------
 12:02  IBM   100.12
 12:02  MSFT   50.15
 12:03  IBM   100.15
 12:04  MSFT   51.00
 12:05  AMZN  200.00

I would like to extract the latest prices for each stock, even though they may be on different times. So the final selection should look like
 Time  Ticker Price
------ ------ ------
 12:03  IBM   100.15
 12:04  MSFT   51.00
 12:05  AMZN  200.00

In regular SQL, one would usually do it like this:
SELECT values.*
  FROM (SELECT Ticker, MAX(Time) AS MaxTime
          FROM StockHistory
         GROUP BY Ticker) as keys
       INNER JOIN StockHistory as values
               ON keys.Ticker  = values.Ticker
              AND keys.MaxTime = values.Time

The problem is, Influx does not seem to support INNER JOIN or any other kind of join. I am just starting to learn it, and for a time series db, this type of a problem must be one of the most frequent ones it is built for. How do you do this in a fast way?
Speed is of concern for me, since I am looking at roughly 5-15 million rows in the table, and 150,000 different tickers (not all are stocks, there are many instruments I am storing).
Thank you very much.
PS If it matters, I will be accessing Influx through the Python API and can do this filtering in the code, but would strongly prefer to do it on the DB side to minimize transmission of a huge number of rows over the network...
UPDATE
I saw this question about a left join, but it seems to be outdated, and i need an inner one on time, something the answer specifically implies would be supported...
Possible Approach
Will this work?
SELECT LAST(Time), Price
  FROM StockHistory
 GROUP BY Ticker

If yes, how fast would it be on a large table (see above for measurements)?