text:
Q: Cannot read property 'join' of null error with node and GA analytics api I'm trying to use Google Analytics Core Reporting API from Node.js by following this tutorial http://www.2ality.com/2015/10/google-analytics-api.html. I'm launching the script directly from my terminal with babel-node mygaapiscript.js.  but I've got the following error :
  /Users/me/Desktop/dashboard/dashboard-ga/node_modules/gtoken/lib/index.js:160
        this.scope = options.scope.join(' ');
                                  ^

    TypeError: Cannot read property 'join' of null
        at GoogleToken._configure (/Users/me/Desktop/dashboard/dashboard-ga/node_modules/gtoken/lib/index.js:160:31)
        at new GoogleToken (/Users/me/Desktop/dashboard/dashboard-ga/node_modules/gtoken/lib/index.js:19:8)
        at JWT.GoogleToken [as gToken] (/Users/me/Desktop/dashboard/dashboard-ga/node_modules/gtoken/lib/index.js:17:12)
        at JWT._createGToken (/Users/me/Desktop/dashboard/dashboard-ga/node_modules/google-auth-library/lib/auth/jwtclient.js:218:24)
        at JWT.refreshToken_ (/Users/me/Desktop/dashboard/dashboard-ga/node_modules/google-auth-library/lib/auth/jwtclient.js:133:15)
        at JWT.authorize (/Users/me/Desktop/dashboard/me-MacBook-Pro:routes

What does this error mean ?
here is my script :
#!/usr/bin/env babel-node
import google from 'googleapis';
'use strict';

import key from './client_id.json';
const VIEW_ID = 'ga:70810323';

let jwtClient = new google.auth.JWT(
    key.client_email,
    key.private_key,
    ['https://www.googleapis.com/auth/analytics.readonly'],null);

    jwtClient.authorize(function (err, tokens) {
      if (err) {
        console.log(err);
        return;
      }
      let analytics = google.analytics('v3');
      queryData(analytics);
    });

    function queryData(analytics) {
      analytics.data.ga.get({
        'auth': jwtClient,
        'ids': VIEW_ID,
        'metrics': 'ga:uniquePageviews',
        'dimensions': 'ga:pagePath',
        'start-date': '30daysAgo',
        'end-date': 'yesterday',
        'sort': '-ga:uniquePageviews',
        'max-results': 10,
      }, function (err, response) {
        if (err) {
          console.log(err);
          return;
        }
        console.log(JSON.stringify(response, null, 4));
      });
    }

module.exports = {queryData};

Got the module.exports because I'm using it inside express.

A: Your arguments to google.auth.JWT() seem to be wrong. See the example in the documentation and the JWT example in the googleapis repo here. The third argument should be the literal key data if you are not passing a key filename for the second argument. So just add null for the third argument:
let jwtClient = new google.auth.JWT(
  key.client_email,
  key.private_key,
  null,
  ['https://www.googleapis.com/auth/analytics.readonly'],
  null
);


text:
Q: Merge 2 dictionaries in Python without deleting first dictionary How can i merge dict1 and dict2 so that i get res? Preferably using .update()
dict1 = {'a':[1, 2, 3], 'b':[4, 5, 6]}
dict2 = {'a':[100, 101, 103], 'b':[104, 105, 106]}
res = {'a':[1, 2, 3, 100, 101, 103], 'b':[4, 5, 6, 104, 105, 106]}

A: If dicts have same keys:
>>> {k: v + dict2.get(k, []) for k, v in dict1.iteritems()}
{'a': [1, 2, 3, 100, 101, 103], 'b': [4, 5, 6, 104, 105, 106]}

if not:
>>> from itertools import chain
>>> res = {}
>>> for k, v in chain(dict1.iteritems(), dict2.iteritems()):
...     res[k] = res.get(k, []) + v
...
>>> res
{'a': [1, 2, 3, 100, 101, 103], 'b': [4, 5, 6, 104, 105, 106]}

and you can use collections.defaultdict in this solution:
>>> from collections import defaultdict
>>> res = defaultdict(list)
>>> for k, v in chain(dict1.iteritems(), dict2.iteritems()):
...     res[k] += v
...
>>> dict(res)
{'a': [1, 2, 3, 100, 101, 103], 'b': [4, 5, 6, 104, 105, 106]}

A: dict1 = {'a':[1, 2, 3], 'b':[4, 5, 6]}
dict2 = {'a':[100, 101, 103], 'b':[104, 105, 106]}
def combine(D1, D2):
    D = collections.defaultdict(list)
    for k, v in D1.items():
        D[k] += v
        D[k] += D2[k]
    return D

A: If the dictionaries have the same keys, I think this is the simplest solution:
res = {k : dict1[k]+dict2[k] for k in dict1}

If the dictionaries have different keys, but you only care about the keys which are the same:
res = {k : dict1[k]+dict2[k] for k in set(dict1) & set(dict2)}

Otherwise, another answer will do!

A: this assumes dict1 and dict2 has the same keys
res = {}
for i in dict1.keys()
    res[i] = dict1[i] + dict2[i]

something like that should work, i didn't run the code so it might be wrong but the idea should be correct.

redpajama_set_name: RedPajamaStackExchange


text:
Q: KMLViewer won't display tracks due to Style Map I've been using Apple's KMLViewer code to show tracks on my MKMapView. I create the KML files by saving a place from Google Earth as a KML file, but the tracks won't display in the map unless I change the style map in the KML file.
At the beginning of the KML file is the style map:
<Style id="lineStyle0000">
    <LineStyle>
        <color>ff0600ff</color>
        <width>4</width>
    </LineStyle>
</Style>
<StyleMap id="lineStyle11000">
    <Pair>
        <key>normal</key>
        <styleUrl>#lineStyle0000</styleUrl>
    </Pair>
    <Pair>
        <key>highlight</key>
        <styleUrl>#lineStyle01</styleUrl>
    </Pair>
</StyleMap>
<Style id="lineStyle01">
    <LineStyle>
        <color>ff0600ff</color>
        <width>4</width>
    </LineStyle>
</Style>

And the track within the KML file starts with
<Placemark>
    <name>Track01</name>
    <visibility>0</visibility>
    <styleUrl>#lineStyle11000</styleUrl>
    <LineString>
        <tessellate>1</tessellate>
        <coordinates>...

When I run the app, the track doesn't show up at all. If I change the styleUrl tag in the beginning of the track from #lineStyle11000 to #lineStyle0000, it shows up fine. This is easy enough to do when I have one or two tracks to display, but it's an annoyance. When I have ten or fifteen tracks to display in one KML file, it really eats up some time.
Is there any way to avoid this problem? I keep all of my tracks in Google Earth so that I can manage them easily, but I'd like to not have to manually change the text of the file every time I need to put it in an app.
Thanks

A: The solution I've been using doesn't really fix the problem, but gets around it okay. Google Earth exports the kml file with the style maps, but if you send the kml file through GPSVisualizer with an output format of Google Earth KML, it just converts the entire file into the simpler format that Apple's KMLViewer can read, while keeping all the colors and line sizes.
Kind of a cop out, but it works.

A: You could automatically edit the file to remove all styleUrls lines
grep -v styleUrl old.kml > new.kml

or run a find and replace within your app.


text:
Q: Android which intent flag required for start activity after android device home button press In my Bluetooth  application I have used fragments.when i am  in a fragment i pressed home button of android device .After that activity in foreground I want to first open the fragment from its previous state.I have used this code but it not working
note-I want to start same activity from its previous state
activityManager = (ActivityManager) getApplicationContext()
            .getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningAppProcessInfo> procInfos = activityManager
            .getRunningAppProcesses();

    for (int i = 0; i < procInfos.size(); i++) {

        if (!procInfos.get(i).processName.equalsIgnoreCase("com.example.democamera")) {

            Log.e("Service", "in service");

            Intent intent1 = new Intent(getBaseContext(),MainActivity.class);
            intent1.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
            getApplicationContext().startActivity(intent1);

        }
    }

A: Intent intent = new Intent(getApplicationContext(), MainActivity.class);
           intent.setAction("android.intent.action.MAIN");
           intent.addCategory("android.intent.category.LAUNCHER");
           intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
           intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
           getApplicationContext().startActivity(intent);


text:
Q: Ubuntu 14.04 / Unity- onboard utility (on-screen keyboard) - desktop icon I would like to have some easier way to launch "onboard" (on-screen keyboard utility).
Once onboard is launched it conveniently sits on a service bar (would be nice to have some improvements there too) but before it is activated one needs to search for it in installed applications every time ubuntu is started.
I would like to place onboard launcher on the desktop (as it never appears in launcher bar so onboard cannot be locked to it)
I have tried various recipes (including making symbolic links) but none is working for me.
Is it somehow possible to create a desktop icon to start onboard when it is not started?

A: You can Find "On Board" Desktop file form following location:
/usr/share/applications/:
$ cat /usr/share/applications/onboard.desktop
[Desktop Entry]
Name=Onboard
GenericName=Onboard onscreen keyboard
Comment=Flexible onscreen keyboard for GNOME
Exec=onboard
Terminal=false
Type=Application
Categories=Utility;Accessibility;
#NotShowIn=GNOME;
#NotShowIn=GNOME;Unity;
NoDisplay=false
MimeType=application/x-onboard;
Icon=onboard
X-Ubuntu-Gettext-Domain=onboard

Drag It to Launcher!


text:
Q: Comparing an array index to a String? I'm trying to compare an index from my array of char's to a string, I'm using the .equals method but I'm running into errors. Any help?
if (j[1].equals("A"))
{j[1] = 10;}

I keep getting this error:
int cannot be dereferenced
else if (j[1].equals("A"))

A: Try this instead:
if (j[1] == 'A')

If the j array contains chars, then you must compare its values with another char, not a String (even if the string has length 1) - they're different data types. And because a char is a primitive type, == is used for equality comparisons.

A: In order to compare single characters, you need to use the == operator because char is a primitive type and Java does not allow to call methods on primitive types. Also, you can't directly compare with a string, you need to compare to a char. Constants of type char are written with single quotes as opposed to double quotes which denote String constants.
Thus your code would be:
if (j[1] == 'A')

You should then use another variable for storing the value 10. Although you could theoretically store it in the array (characters are just numbers, too), this would be very confusing code. Thus use an additional int variable.
Also note that in Java, you should speak of chars, not of Chars. The reason is that there is also a class name Character which also represents a single character, but as an object instead of a primitive type. Thus when you say Char, it is not clear if you mean char of Character.

A: If j[1] is an array of char (the primitive, not the object Character) then you cannot not call the equals method on it, just like you cannot call 1.equals("A").
So, this would work instead (using objects)
    char[] array = new char[] { 'a', 'b', 'c' };
    boolean equals = array[0].equals('a'); // Cannot invoke equals(char) on
                                            // the primitive type char
    Character.valueOf('a').equals(Character.valueOf(array[0])); //This works

Or this, using primitives:
    char[] array = new char[] { 'a', 'b', 'c' };
    boolean anotherEquals = array[0] == 'a'; // This works


text:
Q: ZF Set Theory and Law of the Excluded Middle I know that the law of the excluded middle is implied in ZFC set theory, since it is implied by the axiom of choice. Taking away the axiom of choice, does ZF set theory (with axioms as stated in the corresponding Wikipedia article), imply the law of the excluded middle [for infinite sets]?
If you know of a proof to the answer to my question, could you please point me to it? If LEM does follow from ZF and you don't know the proof, do you know which axioms of ZF it follows from?
Thanks very much.

A: Thanks for the responses GME, Andres, and Andreas. I think my question is answered. (GME I do indeed mean $\phi \vee \neg \phi $).
Let me make sure I understand your answers...
We have logic axioms and set theory axioms. ZF is set theory axioms consistent with the axioms for first-order logic, which is already not intuitionistic since LEM is included in those axioms. So, ZF is not intuitionistic.
If we want a "version" of ZF that is intuitionistic, we have to adjust the logic axioms by removing LEM, and then we will have to adjust the set theory axioms to be consistent with the new logic we are building it on. We will still try to make these new axioms resemble ZF as much as possible. So, take first-order logic, remove LEM, then adjust ZF, and we can get something like IZF or CZF.
What if we want to add the axiom of choice to IZF or CZF? My guess would be that this is exactly equivalent to adding AC to ZF (unless adjusting the set theory axioms as described in the previous paragraph results in some unforeseen consequences) - since AC implies LEM, by adding AC to IZF or CZF we "complete" our weakened first-order logic to once again have LEM, so that IZF/CZF is now ZF again, but with AC it is actually ZFC. (So, by adding AC to IZF/CZF, we lose the entire point of originally constructing IZF/CZF, since we end up at a non-intuitionistic theory again).
Basically, in my question I was assuming that ZF was built on a logic that didn't include LEM. This assumption was false, so my question is moot.
Does this all seem correct?
Thanks again.


text:
Q: Classic asp paging and session state Working on a classic asp page that uses paging.  The error I am having a problem with is this:  Lets say that you have 5 pages returned in your record set and you are on page 2.  You leave and come back, you then press the link for page 3, the trouble is your session has timed out.  I don't know why this happens but the page is reloaded, but the session check is bypassed and of course when the page attempts to retrieve the record set the session variables are now empty so I am getting a message stating: error near ',' line 1, because now the query is defunct.  How do I get around this?
Thanks, Ron.

A: You can just check if any session variable is empty and redirect user to the first page or login page (if you have it).


text:
Q: C++ Templates: Why does not this work?
Possible Duplicate:
C++ method only visible when object cast to base class?!

I've the follow code:
class String {
    char* _Text;
public:
    String( const char* s ) {
        int iLen = strlen(s);
        _Text = new char [iLen+1];
        strcpy( _Text, s );
    }
};

template<typename T>
class Vector {
public:
    int Add( T* pItem ) { return 0; }
    int Add( const T* pItem ) { return 0; }
    int Add( T& pItem ) { return 0; }
};

class StrVector : public Vector<String> {
public:
    int Add( char* pItem ) { return 0; }
    int Add( const char* pItem ) { return 0; }
};

void main()
{
    String s;
    StrVector v;
    v.Add( s ); <-------------
}

The line v.Add( s ); should call Vector::Add(T& pItem), right?

A: The Add methods in the derived class hide the methods defined in the base class.
If you want the base class's Add to not be hidden, you can add a using directive to the derived class:
class StrVector : public Vector<String> {
public:
   using Vector<String>::Add;
   ...
}

A: Nope. You are hiding all the Add functions ov Vector by declaring Add functions in class StrVector. The compiler is issuing an error, and it is right: int Add(String&) is not accessible.

A: I guess what you mean by "not working" is that the call to Add doesn't compile (no appropriate candidate, or something similar).
The Add methods declared in StrVector hide the ones from its base class. See Namespaces and the Interface Principle for a complete explanation.

A: You never gave Vector an actual template argument, just said that it was a template. You need to have template<typename T>. Next, StrVector needs to inherit from Vector<char*>, although why you're inheriting from it I don't actually know.
Of cousre, in actual code, you'd use a std::vector<std:string>.


text:
Q: Ubuntu 16.4 public Samba share suddenly not public anymore New, completely "vanilla" Ubuntu 16.4 server installation. I modified the original smb.conf file to include a public share. It worked, until I rebooted the Windows 10 client. Now, I get asked for the credentials when trying to access the public share. They work, but the share is supposed to be public, so something is obviously wrong. What I cannot fathom is how it could have worked, and then suddenly not anymore after a Windows reboot. There's nothing in the Windows Credential Manager, and it shouldn't be either.
Here's the smb.conf file (which has NOT been altered after it worked the first time):
[global]
workgroup = WORKGROUP

Server string = %h server (Samba, Ubuntu)

dns proxy = no[global]

log file = /var/log/samba/log.%m

max log size = 1000

syslog = 0

panic action = /usr/share/samba/panic-action %d

server role = standalone server

obey pam restrictions = yes

unix password sync = yes

passwd program = /usr/bin/passwd %u
passwd chat = *Enter\snew\s*\spassword:* %n\n *Retype\snew\s*\spassword:* %n\n *password\supdated\ssuccessfully* .

pam password change = yes

map to guest = bad user

usershare allow guests = yes

[printers]
   comment = All Printers
   browseable = no
   path = /var/spool/samba
   printable = yes
   guest ok = no
   read only = yes
   create mask = 0700

[print$]
   comment = Printer Drivers
   path = /var/lib/samba/printers
   browseable = yes
   read only = yes
   guest ok = no

[public]
   comment = Public share
   path = /home/public
   browsable = yes
   read only = no
   guest ok = yes
   force user = nobody

Anyone got any ideas? The workgroup "WORKGROUP" is the same. The permissions and ownership of the public folder on the server are correct. Etc. Etc.


text:
Q: Tables not creating? Syntax issue? I am currently doing a lab for school and cannot for the life of me figure out why I am getting these errors (2 in particular). The first error thrown to me is that in the table "invoice" the PRIMARY KEY constraint is asking for a second right parentheses. The second error I'm receiving is in the creation of table "invprod" where it is arguing to me that "invno" doesn't actually exist.
I don't know if this is an error in my syntax or otherwise but any help is greatly appreciated.
CREATE TABLE invoice
(invno CHAR(5) NOT NULL
,invdate DATE
,orderno CHAR(5) NOT NULL
,CONSTRAINT invorder FOREIGN KEY (orderno)
          REFERENCES salesorder(orderno)
,CONSRAINT pkinvoice PRIMARY KEY (invno)
);

CREATE TABLE invprod
(invno CHAR(5) NOT NULL
,partno CHAR(4) NOT NULL
,shipqty INTEGER CHECK (shipqty>0)
,CONSTRAINT fk1invprod FOREIGN KEY(invno)
        REFERENCES invoice(invno)
,CONSTRAINT fk2invprod FOREIGN KEY(partno)
        REFERENCES part(partno)
);

A: You have typo CONSRAINT should be CONSTRAINT:
CREATE TABLE invoice
(
  invno CHAR(5) NOT NULL
,invdate DATE
,orderno CHAR(5) NOT NULL
,CONSTRAINT invorder FOREIGN KEY (orderno)
          REFERENCES salesorder(orderno)
,CONSTRAINT pkinvoice PRIMARY KEY (invno)
);

SqlFiddleDemo


text:
Q: Why my own authentication doesn't work with my own model in Laravel? I am using Laravel 4.2 and I'm trying to auth my own model (I don't use User model).
The problem appears when pass the mail and password, then I use the method Auth::attempt and enters to else (that it corresponds to the error)
Usuario Controller
class UsuarioController extends BaseController{

function doLogin(){
    $userdata = array(
        'Correo' => Input::get('correo'),
        'Contrasena' => Input::get('contrasena')
        );
    if(Auth::attempt($userdata)){
        echo 'SUCCESS!';

    }else{
        echo 'Error!';

    }
} ...

Usuario Model
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class Usuario extends Eloquent implements UserInterface, RemindableInterface {
protected $table = 'Usuario';
protected $primaryKey = 'idUsuario';
protected $fillable = array(
                        'Nombre',
                        'Apellido',
                        'Rol',
                        'Correo',
                        'Contarsena',
                        'Cumpleanos',
                        'Foto',
                        'Pais',
                        'Comuna',
                        'Profesion_idProfesion',
                        'Institucion_idInstitucion',
                        'remember_token'
                    );

function profesion(){
    return $this->belongsTo('Profesion', 'idProfesion');
}

public function getPasswordAttribute()
{
    return $this->Contrasena;
}

public function setPasswordAttribute($Contrasena)
{
    $this->Contrasena= $Contrasena;
}

public function getReminderEmail()
{
    return $this->Correo;
}

public function getRememberToken()
{
    return $this->remember_token;
}

public function setRememberToken($value)
{
    $this->remember_token = $value;
}

public function getRememberTokenName()
{
    return 'remember_token';
}
public function getAuthIdentifier()
{
    return $this->getKey();
}
public function getAuthPassword() {
    return $this->Contrasena;
}

}

Auth.php
return array(

'driver' => 'eloquent', //database or eloquent

'model' => 'Usuario',

'table' => 'Usuario',

'username' => 'Correo',
'password' => 'Contrasena',

'reminder' => array(

    'email' => 'emails.auth.reminder',

    'table' => 'password_reminders',

    'expire' => 60,

),

);

Usuario Table

The application never crash but in the If Condition always enter to the ''else'' returns Error!

A: try
dd(DB::getQueryLog());

to get the the SQL executed. That makes troubleshooting easier.
My guess is that there's no 'password' field, which the attempt method will automatically hash

A: You have a typo in your fillable array:
protected $fillable = array(
                    'Nombre',
                    'Apellido',
                    'Rol',
                    'Correo',
                    'Contarsena',
                    'Cumpleanos',
                    'Foto',
                    'Pais',
                    'Comuna',
                    'Profesion_idProfesion',
                    'Institucion_idInstitucion',
                    'remember_token'
                );

Contarsena should be Contrasena
And your auth array should contain a email and password key:
$userdata = array(
    'correo' => Input::get('correo'),
    'password' => Input::get('contrasena')
);


text:
Q: Integrating simple Bluetooth functionality without microcontrollers I have recently bought a Bluetooth HC-05 Module, and have followed many tutorials on integrating it with an Arduino, or a microcontroller. However I got interested in whether it is possible without one. And the task I need to achieve is pretty simple, just switching an LED on/off. The official bluetooth documentation is impossible to read, so I'm asking the question here, since I know many of you are experts in the subject.

A: Think of all the interfacing that needs to be done. The module can't put a pin high when you send something to it, or low when you send something else. It's much more advanced, and involves communication standards that use timing. So if you would do this with 'simple components' (logic ports and the like) it would get extremely advanced, and you would simply have a little microcontroller.


text:
Q: R: run time issue, loop, two large dataframes, efficiency I am working on some mass transportation analysis. I have two large dataframes, df:"links" and df:"incl_1stop". The first contains the raw data, 100000 obs - all existing one directional station-station (A to B) links/edges incl. arrival and departure times. The second contains all possible "one stop-transfer" combinations (meaning A via B to C), which I created with a loop.
I would now like to create all possible "two-stop-combinations" by linking A-B-C of df:"incl_1stop" with all "suitable" obs in df:"link" conditionally on C in df:"incl_1stop" == A in df:"link" and some other constraints (see below).
I tried the following loop:
two_stop <- data.frame(stringsAsFactors = FALSE)
mtt <-5
total_travel_time <- 240

for(i in 1:length(incl_1stop$ID)){#all one stop paths
  for(j in 1:length(links$ID)){#all existing direct links
   if(incl_1stop$dest[i]==links$orig[j] & !is.na(incl_1stop$dest[i]) &!is.na(links$orig[j])){#destination one-stop path = origin link
    if((links$dep_minute[j] - incl_1stop$arr_minute[i]) >= mtt & !is.na(links$dep_minute[j]) &!is.na(incl_1stop$arr_minute[i])){#minimum transit time
     if((links$arr_minute[j] - incl_1stop$dep_minute[i]) <= total_travel_time & !is.na(links$arr_minute[j]) &!is.na(incl_1stop$dep_minute[i])){#max travel time
      if(links$dest[j]!=incl_1stop$orig[i]& !is.na(links$dest[j])& !is.na(incl_1stop$orig[i])){#loop first origin
       if(links$dest[j]!=incl_1stop$dest[i]& !is.na(links$dest[j])& !is.na(incl_1stop$dest[i])){#loop second origin

          two_stop[k,1]<-incl_1stop$orig[i]#first node/origin
          two_stop[k,2]<-incl_1stop$dest[i]#second node
          two_stop[k,3]<-incl_1stop$dest2[i]#thrird node
          two_stop[k,4]<-incl_1stop$dep_minute[i]#depature time first node
          two_stop[k,5]<-incl_1stop$arr_minute2[i]#arrival time endpoint third node
          two_stop[k,6]<-incl_1stop_$prov2[i]#provider last path element

          two_stop[k,7]<-incl_1stop$ID1[i]#ID first edge
          two_stop[k,8]<-incl_1stop$ID2[i]#ID second edge

          two_stop[k,9]<-links$ID3[j]#ID additional/third edge
          two_stop[k,10]<-links$dep_minute[j]#depature time third element
          two_stop[k,11]<-links$dest[j]#destination third element/fourth node
          two_stop[k,12]<-paste0(incl_1stop$path[i],"_",links$dest[j]) #travel path
          two_stop[k,13]<-(links$arr_minute[j]-incl_1stop$dep_minute[i])#total travel time first node-fourth node
          k <- k+1
        }
      }
    }
  }
}
}
}

This loop however needs literally days to go through the frames and generate results. I assume that the code is not very efficient.
Do you have recommendations of how to significantly speed up the procedure?


text: Q: Is there any way to perform click actions on tableau Dashboard I am trying to perform click, drag and drop actions on tableau dashboard. I am using selenium for navigation. I did not find anything on the web for this. Tableau UI contains the graph and charts which are populated using html5 canvas, so XPath is not available for these components.


text:
Q: HtmlUnit click event on submit button doesn't work this week I starded a homework and reading on this forum I found the "solution" of my problem.
My programm parses a HTML page of a website and get some data. Well this is not difficult. My problem is how to get data on the website.
Using HtmlUnit I know that's possible, and reading their tutorials and some code on the web I wrote my simple test:
import org.junit.Test;

import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;

public class MyTest {

  @Test
  public void myClient() throws Exception {

    final WebClient webClient = new WebClient();

    HtmlPage page = webClient.getPage("http://www.atb.bergamo.it/ITA/Default.aspx?SEZ=2&PAG=38&MOD=LINTRV");

    final HtmlForm form = page.getFormByName("form1");

    final HtmlSubmitInput filtra = form.getInputByName("ctl13$btnFilter");

    page = filtra.click();

    final String pageAsXml = page.asXml();

    System.out.println(pageAsXml);

    webClient.closeAllWindows();
  }
}

This code gets the remote page, clicks a submit button in a form of the page and after that prints the submit result on the console.
The problem is when I use the click event, because nothing changes in the web page.
Infact it must appear a new table with some data which I want to collect, but it doesn't.
Can you tell me where I get wrong, please?
Do you know another way to do what I'd like to do?

A: It seems as if this code throws an exception loading the initial page (specifically executing the JavaScript).
From my experience this isn't uncommon and can be attributed to HtmlUnit's JavaScript engine(Rhino).
I would suggest trying Selenium WebDriver instead.
This code should get the source of the page:
package javaapplication1;

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Selenium  {
    public static void main(String[] args) throws InterruptedException {
        WebDriver driver = new FirefoxDriver();

        driver.get("http://www.atb.bergamo.it/ITA/Default.aspx?SEZ=2&PAG=38&MOD=LINTRV");
        WebElement filtra = driver.findElement(By.name("ctl13$btnFilter"));
        filtra.click();
        //make sure to wait till the results div is loaded
        //waits 10 seconds or then throws an exception
        (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver d) {
                List<WebElement> divTags = d.findElements(By.tagName("div"));
                for(WebElement tag: divTags){
                    if(tag.getAttribute("id").equalsIgnoreCase("ctl13_divRisultati")){
                        return true;
                    }
                }
                return false;
            }
        });
        String pageSource = driver.getPageSource();
        System.out.println(pageSource);
        driver.quit();
    }
}


text:
Q: sudo minikube returns "command not found" I need to run minikube as sudo on Centos 7.5. minikube is in /usr/local/bin
For my user echo $PATH is:
/usr/local/maven/bin:/usr/lib64/qt-3.3/bin:/usr/local/maven/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin

For user root echo $PATH is:
/usr/local/bin/:/usr/lib64/qt-3.3/bin:/usr/local/maven/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

I even added the following to visudo
Defaults    secure_path = /sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin

But still...
sudo minikube start --cpus 4 --memory 24000 --disk-size=50g --kubernetes-version=v1.7.4 --vm-driver=none

returns sudo: minikube: command not found
What is wrong, or whatelse is missing?

A: See this issue for the answer: https://github.com/kubernetes/minikube/issues/1932
The problem is because your minikube is installed to /usr/bin/local and sudo does not see the binary. A simple fix is to do:
sudo mv /usr/bin/local/minikube /usr/bin/

A: In my case, the Minikube was installed in /usr/bin/local/minikube
so I typed:
sudo mv /usr/bin/local/minikube /usr/bin/

You need to check where the Minikube is installed first (whereis minikube) and then move it to /usr/bin/.
Good luck!

A: Binaries installed in /usr/bin/local, PATH contains /usr/local/bin (traditional place for local/experimental/non-official stuff, check). PATH for root (!!!) has local stuff before the system locations (basic sanity is to have root with a minimal PATH, never including '.' nor unofficial stuff). Fix that first.


text:
Q: OpenCV applying filters to specific place in image Hello I am using OpenCV for Java and want to blur faces from image, but I keep failing to apply it only for face. How can I do it?

A: Your question is too general. What basically needs to be done is to run a face detection algorithm (google for face detection opencv), extract the rectangle of pixels depicting the face using cv::rect, blur them and replace the original pixels. I suggest you read about face detection (try to understand the main ideas regardless of openCV), read some tutorials on implementation and then, if you need assistance, write a more specific question here and people are sure to answer you.


text:
Q: Renumbering auto-increment values in rows in MySQL I have a table with an auto-incrementing primary key. Because I allow my data to be deleted, there are now numerous gaps in the primary keys. For example, if I have row 1, 2 and 3, and 2 gets deleted, I only have rows 1 and 3 left (meaning the number 2 is vacant and empty).
This has proven to give me problems now that I am attempted to conduct a full data migration. So I'm wondering if it's possible at all to simply re-index everything - i.e. run some kind of MySQL UPDATE query such that I update all the rows' primary keys into a smooth, running order.
How do I go about doing this?

A: I think the easiest way is to create an empty clone of the table and copy all rows from your original one. That way all AUTO_INCREMENT fields are re-assigned.
1) Copy the table:
CREATE TABLE clone_table LIKE original_table;

2) Copy all rows, manually specifying all fields except your AUTO_INCREMENT one (id?) using the INSERT INTO ... SELECT ... syntax:
INSERT INTO clone_table (field1, field2, fieldN)
SELECT field1, field2, fieldN FROM original_table ORDER BY id;

3) Optionally, you can now delete old table and rename the clone:
DROP TABLE original_table;
RENAME TABLE clone_table TO original_table;


text:
Q: Python Fibonacci series - different while loops I am relatively new to Python, so pardon my ignorance.
These two implementation of while loop for generating a Fib series is resulting in very different outputs.
The first one is returning the power series of 2, though I feel it is should be doing exactly what the latter is; which is returning the expected series.
The second while loop is obviously doing something right. I am guessing it has to do with the way the variables as being assigned while swapping values.
What is driving this difference?
Appreciate your inputs and help,
First while loop:
def fib(n):
x=0
y=1
while y < n:
    print(y)
    x = y
    y = x + y

The second while loop:
x,y=0,1
while y < 100:
    print(y)
    x,y = y,x+y

A: Parallel assignments
x,y = y,x+y

This is a parallel assignment. The x on the right side is still the old x, it hasn't been set to y yet. This is the desired behaviour, for example in order to swap two variables without needing a 3rd one:
>>> a = 1
>>> b = 2
>>> a, b = b, a
>>> a
2
>>> b
1

As explained by @Alfe, x, y = y, x + y is actually one single tuple assignment:
(x, y) = (y, x + y)

The tuple on the right is completely defined before the assignment happens.
Successive assignments
x = y
y = x + y

The x on the right side of the second line has been set to y on the previous line, so the second line is actually y = y + y.
If you try to swap two variables this way you'll get the same value twice:
>>> a = 1
>>> b = 2
>>> a = b
>>> b = a
>>> a
2
>>> b
2

You need a third variable:
>>> a = 1
>>> b = 2
>>> temp = b
>>> b = a
>>> a = temp
>>> a
2
>>> b
1

A: Edited Answer:
No prob. Following the sequence of your first loop, so x=0, y=1. The first line in your loop makes x = y = 1.
So now y=1.
Then, your next line creates y=x+y.
Which means y=1+1=2. Now x=1 and y=2.
For the next iteration:
x = y = 2

so x = 2
then:
y= 2 + 2 = 4

As was explained, your second loop is a parallel assignment. So following the logic starting with x=0 and y=1:
x,y=y,x+y

causes:
x=1 and y= 0+1 = 1 simultaneously

So now x=1 and y=1. Then for the next iteration:
x=1 and y= 1+1=2 simultaneously

So now x=1 and y=2. My professor for my computer science class taught me that following code line by line on paper helps understand the process the computer follows. I also found it was good to help build an ability to read code. Hope this helped.


text:
Q: Creating a regular weak-reference in Javascript using WeakMaps I am trying to do the obvious thing with WeakMaps: I want to create a weak reference.  In particular, I want to have a list of event-listeners without that list influencing the life of the listener.
So I was very excited to find WeakMaps, until I saw they were only built to satisfy one (fairly rare) use-case, extending objects that were otherwise sealed.  I can't think when I ever wanted to do that, but I need lists of listeners all the time.
Is this possible to use WeakMaps in some clever way I haven't thought of to do this?

A: No, it is impossible to use WeakMaps to create a weak reference. WeakMaps are not iterable, to use them you always need the key. This was a deliberate decision (also here), so that garbage collection does not influence the semantics of your program - which is exactly what you want.
Real weak references might come with ES8, see here and there for drafts.


text:
Q: How to make first array value to uppercase I am trying to make first array value to uppercase.
Code:
$data = $this->positions_model->array_from_post(array('position', 'label'));
$this->positions_model->save($data, $id);

So before save($data, $id) to database I want to convert position value to uppercase. I have tried by this
$data['position'] = strtoupper($data['position']);

but than it is not storing the value in db with uppercase but as it is what user inputs.
Current output of $data:
Array ( [position] => it [label] => Information Technology )

And I want it in uppercase as IT
Added Model Method
public function get_positions_array($id = NULL, $single = FALSE)
{

    $this->db->get($this->_table_name);
    $positions = parent::get($id, $single);

    $array = array();
    foreach($positions as $pos){
    $array[] = get_object_vars($pos);
    }

    return $array;
}

Main MY_Model method
public function array_from_post($fields)
{
    $data = array();

    foreach ($fields as $field) {
    $data[$field] = $this->input->post($field);
    }
    return $data;
}

A: This should work:
$data = $this->positions_model->array_from_post(array('position', 'label'));
$data['position'] = strtoupper($data['position']);
$this->positions_model->save($data, $id);

If Its not, then $data array have only read attribute.

A: The array_from_post() method returns an array with the format below:
$data = array(
  'position' => 'it',
  'label'    => 'Information Technology'
);

So, you could make first value of the array to uppercase, by using array_map or array_walk functions as follows:
$data = array_map(function($a) {
  static $i = 0;
  if ($i === 0) { $i++; return strtoupper($a); }
  else return $a;
}, $array);

Note: This only works on PHP 5.3+, for previous versions, use the function name instead.
Here is the array_walk example, which modifies the $data:
array_walk($data, function(&$value, $key) {
    static $i = 0;
    if ($i == 0) { $i++; $value = strtoupper($value); }
});

Again, if you're using PHP 5.2.x or lower, you could pass the function name instead.


text:
Q: Why can the hyperplanes in $\mathbb{R}^{n+1}$ be represented by means of affine functions $\mathbb{R}^{n+1} \to \mathbb{R}$? Why can the hyperplanes in $\mathbb{R}^{n+1}$ can be represented by affine functions $\mathbb{R}^{n} \to \mathbb{R}$?
Intuitively, it is true. But still, it is not clear for me.
An $n$-dimensional hyperplane in $\mathbb{R}^{n+1}$ defined by $(b,\beta)\in \mathbb{R}^{n+1}$ can be represented as
$$\{x\in \mathbb{R}^n | \langle x, b \rangle = \beta \}.$$
I also know that the hyperplane can also be represented as an affine function
$$\mathbb{R}^n \ni x \mapsto f(x)= \langle b, x\rangle - \beta.$$
Can someone help me deduce the first expression from the second?
Thank you in advance

A: We can represent a hyperplane $\Pi \in \mathbb{R}^{n + 1}$ via a pair $(b, \beta) \in (\mathbb{R}^{n + 1} - \{0\}) \times \mathbb{R}$. Explicitly, $\Pi$ is the set
$$\{ x \in \mathbb{R}^{n + 1} : \langle b, x \rangle = \beta\}.$$
On the other hand, this is precisely the zero set of the affine function $f: \mathbb{R}^{n + 1} \to \mathbb{R}$ defined by
$$x \mapsto \langle b, x \rangle - \beta.$$
Conversely, any affine function $f: \mathbb{R}^{n + 1} \to \mathbb{R}$ can be written as
$$x \mapsto b_1 x_1 + \cdots b_{n + 1} x_{n + 1} - \beta$$ for (unique) coefficients $b_1, \ldots, b_{n + 1}, \beta$. If $f$ is nonconstant, then $b := (b_1, \ldots b_n)$ is nonzero, and
$$x \mapsto \langle b, x\rangle - \beta$$
defines a hyperplane.


text:
Q: How to parse feedburner xml and display on site using google feed API I have a feed coming from Wordpress and flowing through Feedburner. I would like to take the feed from Feedburner and display node values on my website like such:
Title
Description
Audio Link
Comment Count ()
Will the google feed API allow me to grab the media encosure url??? or is it limited to what you can grab?

A: If it's part of the XML feed, then you can grab it and show it on your website.
Can you paste a sample of the xml source from the feed here? That will tell all. (One way of doing this is to open the feed url in ie... it usually shows the source)

A: You'll need to first create a custom feed and feed template from WordPress since this is the source of any feed burned by Feedburner.
To get it done please see the following article that walks you through the whole process, "How to Create a Custom RSS Feed in WordPress in 12 Lines of Code".
Once you've followed the article simply burn a new feed and you're done.


text:
Q: Install Visual Studio 2012 (and SQL Server 2012) on SD card I have a tablet/netbook (Acer W511) which I use for work when I'm not at home. It's great computer overall, but it have only 32GB on a hard drive so I get a 64GB SD card to increase allowed space.
But I've found that Visual Studio 2012 couldn't be installed on SD card as well as SQL Server 2012.
Is there some workaround?

A: If you use NTFS you can not just mount a volume with a drive letter; you can also mount it in a directory.  (Similar to the way unices mount their filesystem).
To do this go to [start] [run] and type diskmgmt.msc.
Select the disk you want to modify and right click on it.
Choose "Change drive letters or paths..."

If you have a previously assigned drive letter then use the [remove] button to get rid of it. Then use [add] and select "mount in the following NTFS folder"

A:
Visual Studio 2012 indeed refuses to install on removable drives, but it can be installed on certified Windows To Go devices. A list of such devices can be found here and here.
If you don't have such a device then one possible workaround (which I haven't personally tried) might be to create a VHD on the card and install the programs in that. The performance might be terrible, but that's for you to deal with.
Open Disk Management (Run / diskmgmt.msc) and create a VHD on the card from the Action menu. Initialise the new disk, create a new simple volume on it, format as NTFS and specify a drive letter.
To auto-mount the VHD/VHDX you can create a shortcut in your startup folder or use the Task Scheduler/Group Policy Editor to schedule a startup/logon script that runs the following command:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe Mount-DiskImage "VHD_Drive:\path to\VHD.vhd"


text:
Q: Not able to access embedded nlog config file? system.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
            System.IO.Stream inputStream = assembly.GetManifestResourceStream(assembly.GetType().Namespace + "Manager.NLog.config");
            using (StreamReader reader = new StreamReader(inputStream))
            {
                string result = reader.ReadToEnd();

            }

getting null error as input stream ? I added the config file under the project folder.

A: If you added the Manager.NLog.config file to the project root folder and your project is called Foo then the correct key under which the file will be embedded is: Foo.Manager.NLog.config.
In your example you seem to be using the Assembly.GetExecutingAssembly method but have you verified that the assembly returned by this method is actually the assembly containing the Manager.NLog.config file?
Also note that assembly.GetType().Namespace will always return System.Reflection so your code looks like this:
var inputStream = assembly.GetManifestResourceStream("System.ReflectionManager.NLog.config");

and I very highly doubt that this key is correct.
So you may try something along the lines of:
var assembly = Assembly.GetExecutingAssembly();
var key = assembly.GetName().Name + ".Manager.NLog.config";
using (var inputStream = assembly.GetManifestResourceStream(key))
using (var reader = new StreamReader(inputStream))
{
    var result = reader.ReadToEnd();
}

A: This code will work no matter where you put the config file in your project structure. Make sure you set Build Action to "Embedded Resource" as I'm sure you've already done.
using System;
using System.IO;
using System.Linq;
using System.Reflection;

var exe = Assembly.GetExecutingAssembly();
string resourceName = exe.GetManifestResourceNames()
                         .FirstOrDefault(s => s.IndexOf("NLog.config", StringComparison.OrdinalIgnoreCase) > -1);
if (!string.IsNullOrEmpty(resourceName))
{
  using (var xml = new StreamReader(exe.GetManifestResourceStream(resourceName)))
  {
    string xmlConfig = xml.ReadToEnd();
    if (!File.Exists("NLog.config"))
    {
      // Do something with the log file, like write it out to the root directory.
      File.WriteAllText("NLog.config", xmlConfig);
    }
  }
}


text:
Q: Should C++11 Move and Copy Assignment Operators return const? Should C++11 Move and Copy Assignment Operators return const?
Example code:
const my_class& operator=(const my_class& other)
{
    // Copy the data
    my_class tmp(other);
    *this = std::move(tmp);

    return *this;
}

const my_class& operator=(my_class&& other)
{
    // Steal the data
    std::swap(my_data_length, other.my_data_length);
    std::swap(my_data, other.my_data);

    return *this;
}

For clarity:
class my_class
{

    protected:

    double *my_data;
    uint64_t my_data_length;
}

Notice the const on the return type. I usually put this without thinking, but is it really necessary? What does returning const prevent you from doing? (An example would be helpful here.)
Note one example was given but then it was removed. Can anyone comment on the following? (a = b).non_const_member_function();

A: No, they definitely should not return a reference to const. A typical declaration is:
my_class& operator=(const my_class& other)
my_class& operator=(my_class&& other)

According to cpprefernce:
CopyAssignable
MoveAssignable
Returning T& for copy and move assignment is requirement to satisfy CopyAssignable and MoveAssignable concept

A: Short answer: No.
Assignment operators and operators like += e.t.c. should always return a reference to the class so that it can be assigned to again:
If it returns const, you cannot do the following do the fact the return object is immutable.
std::string str = "Hello";

(str = "Hello World") += "!";//assign value to hello world then append !

Returning const& still allows you to do functions that are const declared, but nothing that would modify the container, such as =, +=, swap, e.t.c.

A: Well the return value can be used for chain assignment. So a const return would prevent a system like this: (a = b) = c. As a=b returns a const object.


text:
Q: Gnuplot: How to make a 3d palette using the given cordinates and then colour it with a parameter The question which i have asked may seem too obvious but it is not. I have a file containing X Y Z and a parameter (for example lets say pressure). Now i want to plot the 3d body (just use the command splot "file.dat" u 1:2:3 ) but then here comes the tricky part. I want to color the body using the fourth column, that is pressure. That is where the pressure is maximum u get a red color over the body and where the pressure is minimum u get a blue color over the body. Hope am clear to u all

A: Use something like
set palette defined (0 'blue', 1 'red')
set autoscale cbfix
splot 'file.dat' using 1:2:3:4 palette

to color the points depending on the fourth column.


text:
Q: Get an infinite loop using method_added and initialize together I want to hook some actions in all methods in the object, but my attempt is seems to be getting in an infinite loop.
Once I comment out the initialize the problem is fixed.
How can I fix this?
I call the object TaskRecord.new in this way, and then raise the message like stack overflow
class TaskRecord
  @@cnt = 0
  #To add log when calls a method
  def self.method_added(name)
    if /hook/.match(name.to_s) or method_defined?("#{name}_without_hook")
      return
    end
    class_eval do
      alias_method "#{name}_without_hook" , "#{name}"
      define_method name do
        p "#{name} called"
        send "#{name}_without_hook"
      end
    end
  end

  def initialize
    ...
  end

  def somemethods
    ...
  end

A: Because initialize is a private method, try this:
class Test
   def initialize
   end
   alias_method :old_initialize, :intialize
end

Test.method_defined? 'initialize'     # returns false
Test.method_defined? 'old_initialize' # returns false too

You can fix your code with private_method_defined?
if /hook/.match(name.to_s) or
  method_defined?("#{name}_without_hook") or
  private_method_defined?("#{name}_without_hook")


text:
Q: Undefined is not an object (_this.state) I am still quite new to react native and am trying to render a view only if the state is set to true. However, as much as I keep trying I always end up with the following error:
Undefined is not an object (evaluating '_this.state')

The code:
"use strict"
import React, { Component } from 'react'
import * as Animatable from './animations'
import Icon from 'react-native-vector-icons/FontAwesome'
import renderIf from './libs/renderif'
import { Text, TouchableOpacity, View, StyleSheet, Navigator } from 'react-native'
var MyCustomComponent = Animatable.createAnimatableComponent(MyCustomComponent);

const Ic = ({ name, style, onPress }) => (
    <TouchableOpacity onPress={onPress}>
        <Icon name={name} style={style} />
    </TouchableOpacity>
)

const Btn = ({label, onPress}) => (
  <TouchableOpacity style={styles.btn} onPress={onPress}>
    <Text style={styles.btnText}>
      {label}
    </Text>
  </TouchableOpacity>
)

const Dashboard = ({ navigator }) => (
    <View style={styles.container}>
        <Text style={styles.text}>
          In Dashboard
        </Text>
        <Btn label="Let's go back" onPress={() => navigator.pop()} />
    </View>
)

const Home = () => (    // this is where I am trying to access the state
    <View>
        <View style={styles.navbarContainer}>
            <View style={styles.navbar}>
                <View style={styles.flexes}>
                    <Ic
                      name="bars"
                      style={styles.iconLeft}
                      onPress={() => this.setState({isOpen: true})}
                    />
                </View>
                <View style={styles.flexes}>
                    <Text style={styles.navbarTitle}>
                        title
                    </Text>
                </View>
                <View style={styles.rightBtn}>
                    <Ic
                      name="envelope"
                      style={styles.iconRight}
                      onPress={() => alert("envelope pressed")}
                     />
                </View>
            </View>
        </View>
        {renderIf(this.state.isOpen)(
            <View style={{marginTop: 40}}>
                <Text>hi</Text>
            </View>
        )}
    </View>
)

export default class App extends Component {
    constructor(props){
        super(props)
        this.state = {
            isOpen: false
        }
    }

    renderScene(route, navigator) {
        return(
            <route.component
                navigator={navigator}
            />
        )
    }

    render() {
        return (
            <Navigator
                renderScene={this.renderScene.bind(this)}
                initialRoute={{
                    component: Home
                }}
            />
        )
    }
}

The renderIf function:
'use strict';
import React, { Component } from 'react';
const isFunction = input => typeof input === 'function';
export default predicate => elemOrThunk =>
  predicate ? (isFunction(elemOrThunk) ? elemOrThunk() : elemOrThunk) : null;

And the main index.android.js:
import { AppRegistry } from 'react-native'
import App from './app';

AppRegistry.registerComponent('NavRoute', () => App);

I tried to find a relevant question that was answered before but sadly I did not find the one that I need. If this question was answered before, please do point me to that thread and my deepest apologies for the inconvenience.
Thank you in advance!

A: You are trying to use state in a functional / stateless component. That is not possible. To use state, use the class version of React component. The state must explicitly defined in the constructor to use this.state in render function.
export default class Home extends React.Component {
  constructor() {
    super();
    this.state = {
      someState: ''
    }
  }

  // rest of the code below
  // move Home to a separate file - home.jsx and import it
}


text:
Q: SQL Procedure: Selecting Highest DATE within INNER JOIN I currently have the following procedure:
        CREATE TABLE #Appointments (
    [aptUniqueID] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    [aptTime] datetime,
    [aptWorkToDo] [varchar] (512) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    [aptStateDispChar] [varchar] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    [aptStateTextColor] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    [aptStateBgcolor] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    [aptPatientID] [varchar] (8) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    [aptPatientFullName] [varchar] (130) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    [aptEntryTime] datetime,
) ON [PRIMARY]

-- Insert appointments data into temp table
INSERT INTO #Appointments  ( aptUniqueID, aptTime, aptWorkToDo, aptStateDispChar, aptStateTextColor, aptStateBgcolor, aptPatientID, aptPatientFullName, aptEntryTime )
SELECT  CONVERT(varchar(36), apt.UniqueID),
        apt.atime,
        RTRIM(apt.apwork) + ' ' + RTRIM(apt.apwrk2),
        aps.apsdispchar,
        RTRIM(LTRIM(aps.apstextcolor)),
        RTRIM(LTRIM(aps.apsbgcolor)),
        apT.apid,
        dbo.MakeCaseString(pat.pfname, pat.pfnamcase) + ' ' + dbo.MakeCaseString(pat.plname, pat.plnamcase),
        apn.apnentrytime
        FROM apt INNER JOIN pat ON pat.pid = apt.apid INNER JOIN aps on ((apt.aconfstat IS NOT NULL AND apt.aconfstat = aps.apsid) OR (apt.aconfstat IS NULL AND aps.apsid = ' ')) INNER JOIN apn ON (apn.apnpid = apt.apid AND apn.apndate = apt.adate AND apn.apntime = apt.atime)
WHERE apt.adid = @ProviderIDParam   AND apt.adate = @DateParam
ORDER BY apt.atime ASC

Inside my Inner Join how can I return the MAX() date from apn.apnentrytime (DATETIME Field)?
At the moment, it's returning the two rows of data when I only want it to return the row with the highest (most recent) apnentrytime.

A: Something like:
WHERE apn.apnentrytime = MAX(apn.apnentrytime)

A: select  convert(varchar(36), apt.uniqueid),
        apt.atime,
        rtrim(apt.apwork) + ' ' + rtrim(apt.apwrk2),
        aps.apsdispchar,
        rtrim(ltrim(aps.apstextcolor)),
        rtrim(ltrim(aps.apsbgcolor)),
        apt.apid,
        dbo.makecasestring(pat.pfname, pat.pfnamcase) + ' ' + dbo.makecasestring(pat.plname, pat.plnamcase),
        apn.apnentrytime
from apt
inner join pat on pat.pid = apt.apid
inner join aps on
    (apt.aconfstat is not null and apt.aconfstat = aps.apsid)
    or
    (apt.aconfstat is null and aps.apsid = ' ')
inner join (
    select apnpid, apndate, apntime, max(apnentrytime) as apnentrytime
    from apn
    group by apnpid, apndate, apntime
    ) apn on (apn.apnpid = apt.apid and apn.apndate = apt.adate and apn.apntime = apt.atime)
where apt.adid = @provideridparam and apt.adate = @dateparam
order by apt.atime asc


text:
Q: Beginner C++ input behviour This program is a very simple code in my practice to learn C++. The problem is at some point it does not accept input from cin and behaves strangely.
The code and the output of the program are below.
Why does the program not consider cin at "Enter your first name please"?

# include "cmath"
# include <iostream>
using namespace std;

int main()
{
    string FirstName, MiddleName, LastName;
    string WelcomeMessage = "Welcome to Visual C++";
    int Number_of_Steps = 5;
    int LoopStart = 1, LoopEnd = 5;
    int AgeYears, AgeMonths;
    double Pi = 3.14;
    float k = 5.366;
    double Age;
    char* Symbol = "k";
    bool TestResult = true;

    MiddleName = "Milton";

    cout << "Input Your First Name and Last Name" << endl;
    cin >> FirstName >> LastName;
    cout << "Input your Age in Years" << endl;
    cin >> AgeYears;
    cout << "Imput your Age in Months " << endl;
    cin >> AgeMonths;
    Age = AgeYears + AgeMonths / 12;
    cout << endl << "Your Name is " << FirstName << ' ' << LastName << endl;
    cout << "Your Age is " << Age << endl;
    cout << "The Character is " << Symbol << endl;

    // Testing operators
    cout << "Please Enter a floating point number \n";
    int n;
    cin >> n;
    cout << "n==" << n
        << "\n n+1==" << n + 1
        << "\n n three times==" << 3 * n
        << "\n n twice ==" << n + n
        << "\n nsquared ==" << n*n
        << "\n half of n ==" << n / 2
        << "\n square root of n ==" << sqrt(n)
        << "\n";

    // Testing string addition
    cout << "Eneter your first name please" << endl;
    string String1, String2, String3;
    cin >> String1;
    cout << "Enter your family name please" << endl;
    cin >> String2;
    String3 = String1 + " " + String2;
    cout << "Welcome" << " " << String3 << endl;

    // testing inequalities to strings
    string FirstString, SecondString;
    cout << "Input First String "
        << endl;
    cin >> FirstString;
    cout << "Input Second String "
        << endl;
    cin >> SecondString;
    if (FirstString == SecondString)
        cout << "The two words are identical \n";
    if (FirstString >= SecondString)
        cout << "First word is bigger than second word \n";
    if (FirstString <= SecondString)
        cout << "Second word is bigger than first word \n";
}

A: You get a hint from the output displaying .2 as the first name (String1).  The cin operation before asking for first name had 64.2 on the buffer but because you read the value into an int n it only read the integer portion 64 and left the .2 on the buffer.  Changing the declaration n to float n or doing some input validation if you did want an integer should leave the buffer empty when you get to the request for first name.


text:
Q: Max number of tables (objects) in SQL Server editions (compact, express) What are the maximum number of tables that you can have in:

*

*SQL CE4

*SQL 2008 R2 Express

Numbers here http://msdn.microsoft.com/en-us/library/ms143432.aspx I guess is for SQL Server 2008, but are they valid for Express and what about SQL CE4?

The sum of the number of all objects in a database cannot exceed 2,147,483,647

BTW. Sorry for duplicating questions, but it seems to me Stackoverflow is providing answers more quickly.

A: No word about CE, but Express is normal SQL Server + database size and memory / processr limitations.... If you can fit yoru tables into the size, the normal SQL Server limity apply.

A: SQL Server Compact 3.5 limitations here:
http://msdn.microsoft.com/en-us/library/ms172451%28v=SQL.105%29.aspx but that only points out 1024 columns per table and no specific table limitation.
SQL Server Express is the same as normal SQL Server as TomTom points out, it's just limited by memory, processor and database size, the limits of SQL Server Express edition are:

*

*Constrained to a single CPU

*1GB RAM

*10GB database size (4GB in versions before SQL 2008 R2 Express)

Otherwise express edition is standard, this is to allow databases to be moved to and from SQL Server Standard to SQL Server Express, which helps in system development. So for SQL Express it's still The sum of the number of all objects in a database cannot exceed 2,147,483,647
As I said in a comment, if you're doing anything that gets close to hitting these numbers you should really look at your DB design process, if they're being automatically generated then consider not partitioning into so many tables.
By this I mean that you should be selecting your SQL Server version based on other requirements, if suppose SQL CE is limited to 256 tables (not saying that it does since I can find no such thing, and it's much more likely to be at least past 1024), and say you need 500 tables. Then either look at denormalizing some of your tables, or at that point you really need to upgrade to including SQL Express with your program (this just complicates your software deployment process, and not a lot more).
I don't have SQL CE avail atm, but the easiest way would be to just have a test go run off and generate 10k create table statements, with each table having 20+ columns. If your requirements are greater than that then just use numbers that you know.
Lastly, there's SQLite which you haven't asked about, again there's no documentation on this but I suspect it's likely 64k+ you're limited to only 64 tables in a join though.

A: For SQLCe4, I got the response:

There is no limit on number of tables, but we do have a limit of 4GB
  file size.


text:
Q: Como criar uma interface em Python que receba dados, calcule eles e "print" o resultado? A ideia é o usuário digitar dois valores dentro da interface, apertar um botão para a execução do código e o resultado aparecer na tela. Segue o código abaixo:
import requests

from tkinter import *

#Orçamento 3D com Python - Básico

#Dados

MinutosdoProjeto = float(input("Digite os Minutos do Projeto:"))
GramasdoProjeto = int(input("Digite o numero de Gramas do Projeto:"))
ConstanteLuz = float(0.21)
ConstanteLucro = float(4.32)
MaterialGramas = int(1000)
MaterialReais = float(150.00)

#Variaveis

Valor1 = MinutosdoProjeto * ConstanteLuz
Valor2 = MinutosdoProjeto * ConstanteLucro
Valor3 = GramasdoProjeto * MaterialReais / MaterialGramas +0.013
Valor4 = Valor1+Valor2+Valor3

print(" O valor de sua luz é:",Valor1)
print(" O valor de seu lucro é:",Valor2)
print(" O valor de seu Material é:",Valor3)
print(" O valor em Reais é R$:",Valor4)

janela = Tk()
janela.title("Orçamento Impressão 3D")
Entry().grid(row=0, column=0, Text="Minutos do Projeto")
Entry().grid(row=1, column=2, Text="Gramas do Projeto")

Button(text="Fazer o Calculo").grid(row=2, column=0)
janela.mainloop()

A: from tkinter import *

janela = Tk()
janela.title("Orçamento Impressão 3D")

def calcular():
    MinutosdoProjeto = float(valor_minutos.get())
    GramasdoProjeto = int(valor_gramas.get())
    ConstanteLuz = float(0.21)
    ConstanteLucro = float(4.32)
    MaterialGramas = int(1000)
    MaterialReais = float(150.00)

    #Cálculos
    Valor1 = MinutosdoProjeto * ConstanteLuz
    Valor2 = MinutosdoProjeto * ConstanteLucro
    Valor3 = GramasdoProjeto * MaterialReais / MaterialGramas + 0.013
    Valor4 = Valor1 + Valor2 + Valor3

    #Imprimir resultado
    resultado.config(text=" O valor de sua luz é: {:.2f}\n O valor de seu lucro é: {:.2f}\n O valor de seu Material é: {:.2f}\n O valor em Reais é R$:{:.2f}".format(Valor1, Valor2, Valor3, Valor4))

# Adicionar as caixas de entrada e o botão
Label(janela, text="Minutos do Projeto").grid(row=0, column=0)
valor_minutos = Entry(janela)
valor_minutos.grid(row=0, column=1)

Label(janela, text="Gramas do Projeto").grid(row=1, column=0)
valor_gramas = Entry(janela)
valor_gramas.grid(row=1, column=1)

Button(janela, text="Fazer o Cálculo", command=calcular).grid(row=2, column=0)

# Adicionar o resultado
resultado = Label(janela)
resultado.grid(row=3, column=0)

janela.mainloop()

Sobre o código:
'valor_minutos' e 'valor_gramas' são variáveis que armazenam os valores digitados nas caixas de entrada.
A função 'calcular()' é chamada quando o botão "Fazer o Cálculo" é pressionado. Ela utiliza os valores digitados para fazer os cálculos e imprime o resultado na label 'resultado'.
A label 'resultado' é criada vazia e só será preenchida quando o botão for pressionado.


text:
Q: Most concise way to describe people of multiple nationalities, not family origins A problem I'm having is finding a concise way to differentiate between when people are a citizen of one country but have family origins in another, and dual citizens. For example, is there an easy way to distinguish between an American citizen who has French origins, and someone who is a dual citizen of both countries?
Obviously 'French-American' comes to mind, but Wikipedia, for example, says it means both:

French Americans or Franco-Americans (French: Franco-Américains) are citizens or nationals of the United States who identify themselves with having full or partial French or French Canadian heritage, ethnicity, and/or ancestral ties. Members of this group are also those who have declared allegiance either informally or formally to France or French Canada and the United States of America. People with dual citizenship of both France and the United States are commonly referred to as French-Americans.

This could happen with any two nationalities (i.e. British-Italian, Irish-American, etc.)
What is the most concise way to describe someone as having two nationalities while avoiding the possible confusion of it being misinterpreted as speaking of family origins?

A: A person of two nationalities has—exactly as stated in the quotation in the question itself—dual citizenship:

[Merriam-Webster]
  : the status of an individual who is a citizen of two or more nations
  // If that's the case, then her baby will be eligible for dual citizenship.
  — Amy Mackelden, Harper's BAZAAR, "Will Meghan Markle and Prince Harry's Baby Be an American Citizen?," 27 Apr. 2019
  // Mujica has dual citizenship in the U.S. and Mexico, and has homes in Phoenix and Sonoyta.
  — Rafael Carranza, azcentral, "Phoenix-based activist and migrant caravan organizer arrested in Mexico," 9 Nov. 2018

Although dual citizen would be understood, it's not common enough to have its own dictionary definition—and it might be considered unusual by some people.

A single word is multinational, used as both an adjective and a noun, but it may not be acceptable if it's thought to imply family origin as opposed to citizenship. If citizenship needs to be explicitly conveyed, then that word needs to be used.


text:
Q: RadControl DateTimePicker Selecting new time doesn't remove highlight from previous selection This is not browser specific - the behavior exists in Firefox and IE. The RadControl is being used within a User Control in a SiteFinity site.
Very little customization has been done to the control.
<telerik:RadDateTimePicker ID="RadDateTimePicker1" runat="server"
     MinDate="2010/1/1" Width="250px">
      <ClientEvents></ClientEvents>
      <TimeView starttime="08:00:00" endtime="20:00:00"
           interval="02:00:00"></TimeView>
      <DateInput runat="server" ID="DateInput"></DateInput>
</telerik:RadDateTimePicker>

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        RadDateTimePicker1.MinDate = DateTime.Now;
    }
}

A: [Disclaimer, I work for Telerik]
I don't specifically know what the issue is, however here are some general troubleshooting steps that might help unearth the issue:

*

*Check for Javacript errors - (Firefox's Error Console would do it)

*Isolate the RadDateTimePicker control from Sitefinity - (Create a normal ASPX page and place the RadDateTimePicker control on this page.  Does it work in this environment?)

*Check for stylesheet issues using Firebug and/or remove stylesheets (backup first).

In general, keep simplifying until it starts working then re-add complexity until it breaks again.  This normally tells me where the problem is.
Alternately, you could send your project/code to Telerik support.  Best of luck.

A: Can you try changing MinDate to use:
RadDateTimePicker1.MinDate = System.DateTime.Parse(String.Format("{0}/{1}/{2}", System.DateTime.Now.Month, System.DateTime.Now.Day, System.DateTime.Now.Year - 1))

And tell me if the behavior changes.
Also, is the new highlight being shown as well, or is it stuck on the old highlighting completely?


text:
Q: TFS Command-line Crashing I'm trying to set up a build script involving code checked into TFS 2010.  Everything works fine from the IDE, but the command-line functions crash every time I try to access it.  Specifically, "tf workspace" and "tf workspaces" work just fine, but "tf history," "tf get," and anything else that might be useful create an unhandled exception.  No matter how I format these commands, the program still crashes.  I have looked everywhere on the Internet for a key to this problem, to no avail.  This is driving me nuts.  Here is a sample, run from a "Visual Studio Command Prompt:"
tf history * /version:T
Unhandled Exception: System.NullReferenceException: Object reference not set to
an instance of an object.
at Microsoft.TeamFoundation.VersionControl.Controls.DialogHistory.set_Workspace(Workspace value)
at Microsoft.TeamFoundation.VersionControl.CommandLine.CommandHistory.Run()
at Microsoft.TeamFoundation.VersionControl.CommandLine.VersionControlCommandLine.RunCommand(String commandName, String[] args, Boolean& showExitCode)
at Microsoft.TeamFoundation.Client.CommandLine.RunCommand(String[] args)
at Microsoft.TeamFoundation.Client.CommandLine.Run(String[]& args)
at Microsoft.TeamFoundation.VersionControl.CommandLine.VersionControlCommandLine.Main(String[] args)

I apologize if the use of the command is totally wrong, but given that everything I put in makes it crash, I have no frame of reference.
UPDATE:
[I originally posted this comment, but it was deleted as the moderator felt it was more of an "update" than an answer.]
Thank you all for the tips. The day I posted this our TFS server crashed and had to be re-created. I didn't change any of the code or workspaces. When our IT guy recreated it, everything worked perfectly. I have tried to find some difference between the old and new server for the sake of posterity, but I have not found anything.


text:
Q: Facebook OAuth Issue with CakePHP 2.9 Hi Guys first of all let me tell you guys that I am a newbie with CakePHP and MVC also but one of my old client requested me some favor which I took as a challenge. So If anyone can help me I will appreciate a lot.
I have a CakePHP 2.9 application where OAuth is not working properly following is the code for app/Controller/UsersController.php
 public function facebookLogin(){

    $this->layout = false;

    App::import('Vendor', 'Facebook/facebook');
    /*$facebook = new Facebook(array(
                                  'appId'  => '1867587306812489',   // Facebook App ID
                                  'secret' => '9fb41a07d3da3406dbab5861c3498764',  // Facebook App Secret
                                  'cookie' => false,
                                  )
                            );   */
    $facebook = new Facebook(array(
                                  'appId'  => '1887387108164606',   // Facebook App ID
                                  'secret' => '8d733aa6a4501ce27fde9626429baab9',  // Facebook App Secret
                                  'cookie' => false,
                                  )
                            );
    $user = $facebook->getUser();
    if ($user) {
         try {
                $user_profile = $facebook->api('/me?fields=first_name,last_name,email');

        $usersArr = $this->User->find('first',array('conditions'=>array('User.email'=>$user_profile['email'],'User.social_id'=>$user_profile['id'],'User.role_id'=>0)));

                                      $user_count = $this->User->find('first',array('conditions'=>array(),'order'=>'User.id DESC','limit'=>1));

                if(empty($usersArr)){

                        $saveUserArr['User']['username'] =  trim($user_profile['first_name']).' '.trim($user_profile['last_name']);
                        $saveUserArr['User']['firstname'] =  $user_profile['first_name'];

                        $saveUserArr['User']['lastname'] =   $user_profile['last_name'];

                                                   /* $user_n = $saveUserArr['User']['first_name'].'.'.$saveUserArr['User']['last_name'];
                        $user_cnt = $user_count['User']['id'] + 1;
                        $user_n = str_replace(' ','_',$user_n).'.'.$user_cnt;
                        $saveUserArr['User']['user_unique_id'] = $user_n;  */

                        $saveUserArr['User']['email'] =      $user_profile['email'];

                        $saveUserArr['User']['password'] =   '123456';

                        $saveUserArr['User']['social_id'] =  $user_profile['id'];

                        $saveUserArr['User']['login_from'] =  'facebook';

                        $saveUserArr['User']['role_id'] =  0;

                        $this->User->save($saveUserArr['User'],false);

                }else{

                    $this->User->id = $usersArr['User']['id'];

                    $this->User->saveField('social_id', $user_profile['id']);

                    $this->User->saveField('login_from', 'facebook');

                }

            $this->request->data['User']['email'] =  $user_profile['email'];

            $this->request->data['User']['login_from'] =  'facebook';

          } catch (FacebookApiException $e) {

             error_log($e);

             $user = null;

          }

    } else {

     $loginUrl = $facebook->getLoginUrl(array(

            'scope'     => 'email', // Permissions to request from the user

            ));

     return $this->redirect($loginUrl);
    }
}

private function deleteFacebookSession(){

    Configure::write('debug', 0);

    if(!$this->Session->check('Auth.User')){

        foreach( $this->Session->read() as $key => $value ) {

            if( strpos( $key, 'fb_' ) === 0 ) {

                $this->Session->delete($key);

            }
        }
    }
}

It throws following error:

A: The oauth script url is not properly configured in your fb app.
You may go to your fb app settings and look for APP DOMAIN.
Include your domain there:

If you are developing in your localhost, you may want to create a server.local rec in your hosts file so you can access your localserver as server.local.
Also, you can create test versions of the main fb app, and allows you to have a copy of your fb app that works in other environments, it is called "create test app"


text:
Q: How to bind Grid RowDefinition's Height in X.F? I have this binding in my XAML
<RowDefinition Height="{Binding HasValue, Converter={StaticResource BoolToIntConverter}, ConverterParameter=33}" />

but it doesn't seem to work as straight-forward as I assumed. When rendering the page the height of the row is evaluated to a star value actually as opposed to 33.
Any trick I am missing?

A: The binding works if the converter returns a value of type GridLength explicitly...


text:
Q: create a pfx file from a .cer and a .pem file I have used openssl to create a .key and .cer file in pem format (you can read them). Now I want to create .pfx file from them. I have read openssl doumentation it says something like following command I can use
openssl pkcs12 -export -in certificate.cer -inkey privateKey.key -out certificate.pfx -certfile CACert.cer

but I don't know which one is my .cer file (certificate.cer or CACert.cer) what is differences between these two files?

A: The certificate.cer is your public key and the CACert.cer file (as it names suggest) is the public key of a CA (maybe the one who has signed your certificate).
The -in switch specifies input certificate to embed in output file
The -inkey switch specifies the key file you've generated using OpenSSL
The -out switch tells the openssl your desired name for output file
The -certfile is used to specify additional certificates to add to the output pfx file (it could be ignored)


text:
Q: KQL Remove from array if array item contains equals condition I have a log source which has the following format:
//file1.png is the filename, the parenthesis hold the filesize in bytes.
// Each item is separated by a semicolon.
file1.png (445b); file2.pdf (2345b); file3.jpg (343b); file4.docx (3243b);

I have this regex to split the items into a list of lists, with 0 being the filename, 1 the extension and 2 the size in bytes. This can be copied as a test:
datatable (item:string ) [
'file1.png (445b); file2.pdf (2345b); file3.jpg (343b); file4.docx (3243b);',
'file1.src (3243b); file2.ps2 (24b); file3.jpg (300b); file4.jpg (326b);'
]
| extend list = extract_all(@'([^<>:"\/\\\|\?\*;]+)\.([a-zA-z0-9]+) \((\d+)b\);', item)

This outputs as the following:
[["file1", ".png", "343"], ["file2", ".pdf", "232"],...]
I want to remove items from the list if the sublist contains certain filetypes (such as .png). How would I go about doing this? KQL has no iteration features as far as I know.
I have tried using regex to exclude the queries I do not want to match. It was the following: (?:^|; =?)([^<>:"\/\\\|\?\*;]+\.(?!jpg\b|png\b)\w+ \(\d+b\))(?=;|$). Unfortunately, KQL does not support negative lookaheads.

A: mv-apply operator
datatable (item:string ) [
'file1.png (445b); file2.pdf (2345b); file3.jpg (343b); file4.docx (3243b);',
'file1.src (3243b); file2.ps2 (24b); file3.jpg (300b); file4.jpg (326b);'
]
| mv-apply f = extract_all(@'([^<>:"\/\\\|\?\*;]+)\.([a-zA-z0-9]+) \((\d+)b\);', item) on
  (
    where f[1] !in~ ("png", "jpg")
    | summarize make_list(pack_array(f))
  )

item
list_

file1.png (445b); file2.pdf (2345b); file3.jpg (343b); file4.docx (3243b);
[["file2","pdf","2345","b"],["file4","docx","3243","b"]]

file1.src (3243b); file2.ps2 (24b); file3.jpg (300b); file4.jpg (326b);
[["file1","src","3243","b"],["file2","ps2","24","b"]]

Fiddle

A: replace_regex()
datatable (item:string ) [
'file1.png (445b); file2.pdf (2345b); file3.jpg (343b); file4.docx (3243b);',
'file1.src (3243b); file2.ps2 (24b); file3.jpg (300b); file4.jpg (326b);'
]
| extend clean_item = replace_regex(item, @'([^<>:"\/\\\|\?\*;]+)\.(?i:png|jpg) \((\d+)b\);', "")
| extend extract_all(@'([^<>:"\/\\\|\?\*;]+)\.([a-zA-z0-9]+) \((\d+)b\);', clean_item)

item
clean_item
Column1

file1.png (445b); file2.pdf (2345b); file3.jpg (343b); file4.docx (3243b);
file2.pdf (2345b); file4.docx (3243b);
[[" file2","pdf","2345"],[" file4","docx","3243"]]

file1.src (3243b); file2.ps2 (24b); file3.jpg (300b); file4.jpg (326b);
file1.src (3243b); file2.ps2 (24b);
[["file1","src","3243"],[" file2","ps2","24"]]

Fiddle

A: And another option that doesn't rely on (arguably) hard to read regular expressions:
datatable (item:string ) [
'file1.png (445b); file2.pdf (2345b); file3.jpg (343b); file4.docx (3243b);',
'file1.src (3243b); file2.ps2 (24b); file3.jpg (300b); file4.jpg (326b);'
]
| extend s=split(item, "; ")
| mv-expand s
| parse s with fileName "." extension " (" fileSize "b)" rest
| where extension !in ("png", "jpg")
| extend image = bag_pack("fileName", fileName, "extension", extension, "fileSizeBytes", fileSize)
| summarize make_list(image) by item

item
list_image

file1.png (445b); file2.pdf (2345b); file3.jpg (343b); file4.docx (3243b);
[ { "fileName": "file2", "extension": "pdf", "fileSizeBytes": "2345" }, { "fileName": "file4", "extension": "docx", "fileSizeBytes": "3243" } ]

file1.src (3243b); file2.ps2 (24b); file3.jpg (300b); file4.jpg (326b);
[ { "fileName": "file1", "extension": "src", "fileSizeBytes": "3243" }, { "fileName": "file2", "extension": "ps2", "fileSizeBytes": "24" } ]

According to the original regular expression ; isn't part of the filename which means simply splitting on ; should be safe.


text:
Q: Strategy to label stock prices Suppose I have the prices of an action XXXX at the second for three years. I want to use the data to train my Deep Neural Network model for standard day trading purposes (i.e. High Frequency Trading). However, I have to label each second of the data file with "-1", "0", "1" for sale order, do nothing or a buy order. I don't want to label each row manually because it will take a year to do this task. How could I parse the data with python to label each row by "-1" if it is a good time to sell, "0" for doing nothing or "1" for a buy order? For a time X, we know precisely the past prices and the future prices, so it could be doable to label all of them I figure.
Be aware that for a standard trading, we have to take into account the transaction fees. In my case, I pay \$4.95 for a buy and \$4.95 for a sell. For instance, if I buy 100 shares at $1, then in order not to lose money, I must at least cover the loss related transaction costs. Hence, the selling price much be at least \$1 + (\$9.90/100) = \$1.099 ~ \$1.1
Another important aspect is that my market making strategy is order flow. So I don't want to trade on low price changes. In fact, I want the machine assists me to trade at the beginning. So I need the machine to trade as a trader normal would do on a normal day trading.
                        ...
2018-04-02 17:59:33.643    0.8400
2018-04-02 18:08:58.808    0.8420
2018-04-02 18:09:50.003    0.8400
2018-04-02 18:09:50.003    0.8400
2018-04-02 18:12:27.183    0.8400
2018-04-02 18:16:04.064    0.8400
2018-04-02 18:25:07.933    0.8450
2018-04-02 18:25:41.331    0.8450
2018-04-02 18:26:54.375    0.8400
2018-04-02 18:26:54.376    0.8300
2018-04-02 18:37:39.056    0.8250
2018-04-02 18:38:23.336    0.8250
2018-04-02 18:38:23.339    0.8250
2018-04-02 18:51:15.689    0.8449
2018-04-02 19:04:41.140    0.8449
2018-04-02 19:17:38.169    0.8450
2018-04-02 19:26:59.634    0.8450
2018-04-02 19:27:47.407    0.8450
2018-04-02 19:37:19.775    0.8449
2018-04-02 19:37:29.165    0.8449
2018-04-02 19:41:05.906    0.8449
2018-04-02 19:54:18.236    0.8400
2018-04-02 19:54:20.944    0.8449
2018-04-02 19:54:20.946    0.8449
2018-04-02 19:56:32.848    0.8412
2018-04-02 19:56:32.851    0.8412
2018-04-02 19:57:04.354    0.8400
2018-04-02 19:57:04.355    0.8400
2018-04-02 19:58:02.221    0.8400
2018-04-02 19:59:31.622    0.8400

UPDATE

The mid-price at time $t$ is denoted by $$p_t = \frac{s_t^{a,1} +
 s_t^{b,1}}{2}.$$
This mid-price can evolve in minimum increments of half a tick but is
  almost always observed to move at increments of a tick over time
  intervals of a millisecond or less. In our feature set, each limit
  order book update is recorded as an observation. Each observation is
  labelled bases on whether the mid-price will increase, decrease or
  remain over a horizon $h$: $$Y_t = \Delta p^t_{t+h},$$ where $\Delta
 p^t_{t+h}$ is the forecast the discrete mid-price changes from time
  $t$ to $t+h$, given measurement of the predictors up to time $t$. The
  forecasting horizon $h$ can be chosen to represent a fixed number of
  events or can be a fixed time interval.

This definition is from A High Frequency Trade Execution Model for Supervised Learning (https://arxiv.org/pdf/1710.03870.pdf).

A: You haven't stated what the criteria are for assigning labels of -1, 0, or 1.  Also, if you are trading on the second time scale, then the price change per bar will be quite low.   If the price change is +0.01 for a bar, and the asset price is \$1 per share (\$100 per trade for 100 shares), then then your profit will be \$1 from that trade, which won't cover the \$4.95 commission.  If you are trading 100 shares per second, where on Earth are you going to find a brokerage that will process your Sell trade alerts/signals for a given second and settle the trade in milliseconds, so that if the next bar (second) is a Buy, the proceeds will be available to make the purchase?
Overall, for very low price changes on short time scales (seconds, ticks) you have trade thousands of shares for each alert in order to be profitable.  But trading so many shares on a short time scale can result in a lack of sufficient funds very quickly since sell and cover trades won't get filled as quickly as the unit of time scale you are on.
Next, if you are training a deep learning ANN with several hidden layers, which will require hundreds of iterations to determine whether to go long (Buy) or short for each second's bar, how are you going to be able to run your input through the ANNs architecture and trained connection weights to make the prediction before the next bar?
Overall, there are some trading issues which could be disastrous based on what you want to do, such that trade settlements will become clogged up and insufficient funds will occur for future trades (selling shares can take many seconds).


text:
Q: pyusb assertion error - no usb out endpoint? I'm trying to program (upload new messages to) a scrolling LED badge via python on Linux instead of via the windows exe. I've got a capture of a successful upload via the windows app that I'll use as a template, but at the moment I'm having trouble writing anything at all to the device.
When I run my script, I get an assertion error, which I assume means that no OUT endpoints have been found. lsusb seems to corroborate this, but I could be mistaken. This is basically straight from the pyusb tutorial with alternate_setting removed from intf because it was causing a pipe error and is apparently not necessary.
intf = usb.util.find_descriptor(cfg, bInterfaceNumber = interface_number,)

ep = usb.util.find_descriptor(
    intf,
    # match the first OUT endpoint
    custom_match = \
    lambda e: \
        usb.util.endpoint_direction(e.bEndpointAddress) == \
        usb.util.ENDPOINT_OUT
)

assert ep is not None # < assertion error

In case it helps, lsusb -vv for the LED badge: http://bpaste.net/show/biixy6e38A71WlCw7euU/
Any guidance would be much appreciated - I'm entirely new to USB protocol, and not great at python either.


text:
Q: How do I correctly send a request in a loop? After sending a response to me comes with a link to the next page with the products, how do I send requests to it while this link is in the response?
function get_data() {
  $array = [];
  $curl = curl_init();
  curl_setopt($curl, CURLOPT_URL, $url);
  $headers = array(
    "accept: application/json;charset=utf-8",
    "Authorization: Bearer $token",
    "Content-Type: application/json-patch+json",
  );
  curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
  curl_setopt($curl, CURLOPT_HEADER, 0);

  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

  $resp = curl_exec($curl);
  curl_close($curl);
  $res = json_decode($resp, true);

  while(isset($res['meta']['nextHref'])) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $res['meta']['nextHref']);
    $headers = array(
      "accept: application/json;charset=utf-8",
      "Authorization: Bearer $token",
      "Content-Type: application/json-patch+json",
    );
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_HEADER, 0);

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $resp = curl_exec($curl);
    curl_close($curl);
    $res = json_decode($resp, true);
    $array[] = $res;
  }
  return $array;
}

A: You do not need the while cycle there. Change your function so that it excepts an input parameter, and make it recursive by itself, like this:
function get_data($url) {
  $array = [];
  $curl = curl_init();
  curl_setopt($curl, CURLOPT_URL, $url);
  $headers = array(
    "accept: application/json;charset=utf-8",
    "Authorization: Bearer $token",
    "Content-Type: application/json-patch+json",
  );
  curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
  curl_setopt($curl, CURLOPT_HEADER, 0);

  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

  $resp = curl_exec($curl);
  curl_close($curl);
  $res = json_decode($resp, true);
  $array[] = $res;

  if (isset($res['meta']['nextHref'])) $array = array_merge($array, get_data($res['meta']['nextHref']));

  return $array;
}


text:
Q: CSS (Grid), auto resize unknown number of items, row and columns, 100% height and width I'm trying to render a dynamic (css) grid with unknown number of items (javascript generated).
What I need is to have all items (obviously resized) in width 100% and height 100%.
Examples:

*

*1 item: big square

*2 items: 2 big squares (2 horizontal columns)

*3 items: screen in 4 squares, 1, 2, 3 divs, 4 (latest one) empty

*4 items: screen in 4 squares

*and so on...

*1920 items (on 1920x1080 display): every item resized very very small (maybe just one pixel or less considering gap between) (with no text inside) in the same number of columns and rows (but this is just an extreme example, just for meaning!)

What I have done alone: https://jsfiddle.net/fredhors/s4k3z9t2/8/
CSS:
.grid-wrapper {
  display: grid;
  grid-template-columns: repeat(auto-fit, 10vmax);
  grid-gap: 0.5rem;
  height: 100vh;
}

.grid-item {
  background: red;
}

A: The error was in the grid-template-columns: repeat();: I used a minmax column width of 9% to allow for all ten columns to appear across the page with 1fr to distribute the remaining space to the gutters.

.grid-wrapper {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(9%, 1fr));
  grid-gap: 0.5rem;
  height: 100vh;
}

.grid-item {
  background: red;
}

Content D

Content E

Content J

Content K

Content D

Content E

Content J

Content K

Content L

Content D

Content E

Content J

Content K

Content L

Big or small, it does it all! ;)


text:
Q: Indecomposable finite-dimensional representations of the nonabelian two-dimensional Lie algebra Let $\mathfrak{g}$ be the nonabelian $2$-dimensional complex Lie algebra. It can be generated by two independent vectors $e_1,e_2$ such that $[e_1,e_2]=e_1$. Thus, $\mathfrak{g}$ is solvable and it follows that its irreducible representations are $1$-dimensional (I guess this is Lie's theorem). Also we may look at the adjoint representation: it is $2$-dimensional but it can be easily shown that it is indecomposable, however. So, is it true that for each $n\in \mathbb{N}$ there is a indecomposable representation of $\mathfrak{g}$ of dimension $n$? I will be grateful if you share the examples.

A: Start with the $n$ dimensional irrep of $\mathfrak{sl}_2$ and restrict it to its Borel subalgebra of upper triangular matrices (a non-abelian $2$ dimensional Lie algebra). It is indecomposable because any proper submodule does not contain the highest weight vector. This produces one indecomposable in every dimension.

A: Supplementing Stephen's excellent answer (+1) with concrete matrices to cater for the possibility that this exercise was encountered prior to the theory of representations of $\mathfrak{sl}_2$. Let us fix a dimension $n$. Let $A$ be the diagonal matrix with entries
$-(n-1)/2$, $-(n-3)/2$, $\ldots$, $(n-3)/2$,$(n-1)/2$ in an arithmetic progression from $-(n-1)/2$ to $(n-1)/2$ (so step $=1$). Let $B=(b_{ij})$ be the $n\times n$-matrix with $b_{i,i+1}=1$ for all $i=1,2,\ldots,n-1$, and zeros elsewhere. Then it is not too hard to check that $BA-AB=B$, so by mapping $e_1\mapsto B$ and $e_2\mapsto A$ we get an $n$-dimensional representation $V$ of your Lie algebra. This is indecomposable, because no proper submodule contains the vector $v=(0,0,0,\ldots,0,1)^T$. For if a submodule does contain $v$, then it also contains
$Bv=(0,0,\ldots,0,1,0)^T$, $B^2v$ and all the way down to $B^{n-1}v=(1,0,0,\ldots,0)$.
These vectors span all of $V$, so the submodule wasn't a proper one. In light of Stephen's answer the reason for this is immediate. The element $e_1$ (or the matrix $B$) acts as a ladder operator, and this is just the ladder in action - $n$ rungs to it this time.
As an example consider the case $n=5$. Then the matrices are
$$
e_1\mapsto\left(\begin{array}{ccccc}0&1&0&0&0\\0&0&1&0&0\\0&0&0&1&0\\0&0&0&0&1\\
0&0&0&0&0\end{array}\right)\quad\text{and}\quad
e_2\mapsto\left(\begin{array}{rrccc}-2&0&0&0&0\\0&-1&0&0&0\\0&0&0&0&0\\0&0&0&1&0\\
0&0&0&0&2\end{array}\right).
$$

A: Here is an answer derived from the answer of Stephen.
First, write the equivalent relation $[ - e_2, e_1]= e_1$ and denote $e = - e_2$, $f=  e_1$ to get $[e,f] = f$.
For $\lambda$ a parameter ( take it $\text{mod}\  \mathbb{Z}$) consider the infinite dimensional vector space $V_\lambda$ spanned by $v_i$, $i \in \mathbb{Z}$. It is easy to check that the formulas below give an action  of our Lie algebra on $V_{\lambda}$:
\begin{eqnarray}
 e (v_i) &=& (\lambda + i ) \cdot v_i \\
f( v_i) &=& v_{i+1}
\end{eqnarray}
For $n$ in $\mathbb{Z}$ the subspace $V_{\lambda,N}$ spanned by $v_i$, $i \ge N$ is subrepresentation of $V_{\lambda}$. Let's show that there are no other subrepresentations. Indeed,  let $W\ne 0$ an invariant subspace of  $V_{\lambda}$. Let $v \in W$, $v = \sum_{i \ge i_0} a_i v_i$, $a_{i_0} \ne 0$.  Since all the $v_i$ are eigenvectors of $e$ for distinct eigenvalues and $W$ is invariant under $e$ it follows that $v_{i_0} \in W$. Now raise the indexes to conclude $W \supset V_{\lambda, i_0}$.
The quotient representations $V_{\lambda, N} / V_{\lambda, N + n}$  ( a subquotient of $V_{\lambda}$ ) has dimension $n$ and all its subrepresentations are $V_{\lambda, N+m} / V_{\lambda, N + n}$ for $0\le m \le n$. Hence the subrepresentations of  $V_{\lambda, N} / V_{\lambda, N + n}$ form a complete flag and hence no two can decompose the space $V_{\lambda, N} / V_{\lambda, N + n}$ in a nontrivial way.
These $V_{\lambda, N} / V_{\lambda, N + n}$, let's denote them by $W_{\lambda+n-1,n}$ should give you all the finite dimensional representations of your algebra. The dimension is of $W_{\mu, n}$ is $n$ and the highest weight of $e$ is $\mu$.


text:
Q: XPath Getting child elements from html I am trying to find the xpath for only the child of a navigation bar. The path which I am trying at the moment is //div[@class='navCol subMenus'] from this peace of HTML.

        Brands

         Shop by Brand

      blah

I have tried a number of Xpath syntax but none seem to work to bring up just the sub categories. Thank you for any help which you can provide.


text:
Q: non-default argument follows default argument but all arguments other than self are defined? I'm trying to learn how to properly nest classes in python (I'm used to having structs within other structs in C++). The following is my attempt:
class Patient(object):
    class FutureMirceraRegimen(object):
        def __init__ (self, dose = None, frequency = None):
            self.dose = dose
            self.frequency = frequency

    class CurrentMirceraRegimen(object):
        def __init__(self, dose = None, frequency = None, lastdose = None):
            if dose is None:
                self.dose = input("What is the current dose (in mcg)?")
            if frequency is None:
                self.frequency = input("What is the current frequency (in weeks)?")
            if lastdose is None:
                self.lastdose = input("How many days have elapsed since the patient's last dose of Mircera?")

    class Hgb(object):
        def __init__(self, level = None, increasing = None, decreasing = None):
            if level is None:
                self.level = input("What is the Hgb level?")
            if increasing is None:
                self.increasing = input("Is the Hgb increasing? (answer Y/N)")
            if decreasing is None:
                self.decreasing = input("Is the Hgb decreasing? (answer Y/N)")

    def __init__(self, identifier = None, age = None, gender = None, weight = None, currentminceraregimen, hgb, futureminceraregimen):
        self.identifier = input("Patient identifier?")
        self.identifier = int(self.identifier)

        self.age = input("Patient age?")
        self.age = int(self.age)

        self.gender = input("Input 1 if patient is female, input 2 if patient is male.")
        self.gender = int(self.gender)

        self.weight = input("Input rounded weight in KG.")
        self.weight = int(self.weight)

        self.futureminceraregimen = Patient.FutureMirceraRegimen

        self.currentminceraregimen = Patient.CurrentMirceraRegimen

        self.hgb = Patient.Hgb

Jeff = Patient

However, whenever I run the code I get an error saying that I have a non-default argument following a default argument. I don't understand why because my only non-default argument is self in all of the classes. Any help would be greatly appreciated!


text:
Q: How to recreate a .pub file I'm trying to replace a test cert in an old code base. However, I keep getting the below exception at the line X509EncodedKeySpec spec = new X509EncodedKeySpec(x509EncodedPublicKey);. I tried inspecting the old cert which is a .pub file and that is in unreadable format. I tried to generate self-signed certs myself and not matter what type of public I create, I still keep getting the same exception. How can I inspect the existing certificate and recreate another cert like that.
Exception
java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
    at sun.security.rsa.RSAKeyFactory.engineGeneratePublic(RSAKeyFactory.java:205)
    at java.security.KeyFactory.generatePublic(KeyFactory.java:334)

Caused by: java.security.InvalidKeyException: invalid key format
    at sun.security.x509.X509Key.decode(X509Key.java:387)
    at sun.security.x509.X509Key.decode(X509Key.java:402)

when I tried to read the cert I got the below exception
$ openssl x509 -in test.pub -text -noout
unable to load certificate
4420640428:error:09FFF06C:PEM routines:CRYPTO_internal:no start line:/m/pem_lib.c:684:Expecting: TRUSTED CERTIFICATE

A: It turns out that there is an option in the keystore explorer tool where the .pub file can be extracted in 2 formats. One is as .pem the other is without pem. When we disable the .pem option, the file is extracted with .pub and encoded as mentioned in the question.


text:
Q: How can i asyncronously download images from a list of urls in python? I have no real idea of how to do something like this. I'm using urllib2 to download the images, and as the image names are stored in the URL. I've already made one synchronously,

A: https://docs.python.org/3/library/concurrent.futures.html#threadpoolexecutor-example
Try this, just follow the example. Almost the same.