text:
Q: How to extend angular @input decorator? I'm trying to write custom property decorator for extending skills of angular @Input decorator.
My goal is to get Localizable property with existing property selector.
./decorators/my-decorators.ts
import {Input} from '@angular/core';
export interface InputDefinition {localizable: boolean; selector: string; }
export function MyInput(inputDefinition: InputDefinition) {
    const ngInput = Input(inputDefinition.selector);
    return function (target: any, key: string) {
        if (inputDefinition.localizable === true) {
            console.log(`loclizable input ${inputDefinition.selector}`);
            // implement localization for property.
        }
      ngInput(target, key);
    };
}

./my-component/mycomponent.ts
import { Component, Input } from '@angular/core';
import { MyInput } from '../decorators/my-decorators';

@Component({
  selector: 'my-component',
  template: `<h1>{{myInput}}</h1>`
})
export class MyComponent {
  //define input property with custom decorator
  @MyInput({selector: 'my-input', localizable: false})
  myInput = 'input default value';
}

./app.component.html
<div style="text-align:center">
  <my-component my-input="bound value"></my-component>
</div>

ng serve

seems to work great but when I run it in prod mode..
--ng serve --prod

has no any build error or runtime error but property binding not working in prod build.
All kinds of suggestions will help.
thanks in advance
ng -version

Angular CLI: 6.2.4
Node: 8.11.1
OS: win32 x64
Angular: 6.1.9
... animations, common, compiler, compiler-cli, core, elements
... forms, http, language-service, platform-browser
... platform-browser-dynamic, router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.8.4
@angular-devkit/build-angular     0.8.4
@angular-devkit/build-optimizer   0.8.4
@angular-devkit/build-webpack     0.8.4
@angular-devkit/core              0.8.4
@angular-devkit/schematics        0.8.4
@angular/cli                      6.2.4
@ngtools/webpack                  6.2.4
@schematics/angular               0.8.4
@schematics/update                0.8.4
rxjs                              6.2.2
typescript                        2.9.2
webpack                           4.20.2


text:
Q: Vertically centering nav items in Bootstrap 3 So, I've set my navbar to a custom height of 80px, but now that makes my nav items not centered vertically. I've been searching for an answer to center them vertically in relation to their parent item for awhile now so I figured I'd give StackOverflow a shot.
Screenshot: http://screencast.com/t/zfUuX9SSQK
HTML:

                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#nav-collapse">
                        Toggle Navigation

                    </button>
                    Tickets

Link 1

Link 2

Link 3

CSS:
.navbar.isModified {
height: 80px;
border-radius: 0;
background-color: #cccccc;

}

.icon-bar.isModified {
background-color: #fff;

}

A: Vertical alignment can be done in a number of ways, as shown in this Stack Overflow question. However, they're fairly situational, meaning there isn't a single approach that can be applied to every case.
For the issue you're facing, I'd suggest the line-height approach, since all of your navigation content is on a single line. Just remove any vertical padding on the elements in questions, and set them to have the same line-height as the desired container height (80px):
.navbar-nav li a {
    padding:0 15px;
    line-height:80px;
}
.navbar-header a {
    padding:0 15px;
    line-height:80px;
}

Here's a Bootply to demonstrate. Hope this helps! Let me know if you have any questions.
Alternatively, you can use:
.navbar.isModified a {
    padding:0 15px;
    line-height:80px;
}

Though you may find this too broad of a CSS selector if you plan on styling other links in your navbar differently.
Note: If you want the mobile version of the menu to look alright, you may need to use media queries to override these styles with more of your own.

A: You can do this several ways depending on how your nav links need to behave. You probably want to apply line-height to you links so on hover they are still the full height of the navbar above 768px (or not, depends). You can then use another media and add padding to the navbar-header class to have a taller navbar. Don't use a fixed height though because on mobile your toggle nav will have no background color since the navbar has a default value of min-height: 50px.
Working Example:

.navbar.isModified {
  background-color: #cccccc;
}
.navbar.isModified .icon-bar {
  background-color: #fff;
}
@media (min-width: 768px) {
  .navbar.isModified .navbar-brand {
    line-height: 50px;
  }
  .navbar.isModified .navbar-nav > li > a {
    line-height: 50px;
  }
}
@media (max-width: 767px) {
  .navbar.isModified .navbar-header {
    padding: 15px 0;
  }
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#nav-collapse">
            Toggle Navigation

          </button>
          Tickets

Link 1

Link 2

Link 3

redpajama_set_name: RedPajamaStackExchange


text:
Q: gremlin intersection with `select` and `as` I'm following up with these 2 questions --
gremlin intersection operation
JanusGraph Gremlin graph traversal with `as` and `select` provides unexpected result
I'm viewing StackOverflow intensively(wanted to thank the community!) but unfortunately I didn't post/write a lot, so I don't even have enough reputation for posting a comment on the posts above...therefore I'm asking my questions here..
In 2nd post above, Hieu and I work together, and I want to provide a bit more background on the question.
As Stephen asked in the comment(for 2nd post), the reason that I want to chain V() in the middle is simply because I want to start the traversal from the beginning, i.e. each and every node of the whole graph just like what g.V() does, which appears at the beginning of most of the queries in gremlin documentation.
A bit more illustration: suppose I need 2 conditional filters on the results. Basically I want to write
g.V().(Condition-A).as('setA')
 .V().(Condition-B).as('setB')
 select('setA').
 where('setA',eq('setB'))

which borrows the last answer from Stephen's answer in the 1st post.  Here Condition-A and Condition-B is just a chaining of different filter steps like has or hasLabel etc.
What should I write at the place of .V() in the middle? Or is there some other way to write the query so that Condition-B is completely independent of Condition-A?
Finally, I've read the section for chaining V() in the middle of a query at https://tinkerpop.apache.org/docs/3.5.0/reference/#graph-step. I still cannot fully understand the weird consequences for 2nd post, maybe I should read more about how traversers work?
Thanks Kelvin and Stephen again. Glad and excited to connect with you who wrote a book/wrote the source code for gremlin.

A: In the middle of a traversal, a V() is applied to every traverser that has been created by the prior steps. Consider this example using the air-routes data set:
g.V(1,2,3)

This will yield three results:
v[1]
v[2]
v[3]

and if we count all vertices in the graph:
gremlin> g.V().count()
==>3747

we get 3,747 results. If we now do:
gremlin> g.V(1,2,3).V().count()
==>11241

we get 11,241 results (exactly 3 times 3747). This is because for each result from g.V(1,2,3) we counted every vertex in the graph.
EDITED to add:
If you need to aggregate some results and then explore the graph again using those results as a filter, one way is to introduce a fold step. This will collapse all of the traversers back into one again. This ensures that the second V step will not be repeated multiple times by any prior fan out.
gremlin> g.V(1,2,3).fold().as('a').V().where(within('a'))
==>v[1]
==>v[2]
==>v[3]

gremlin> g.V(1,2,3).fold().as('a').V().where(without('a')).limit(5)
==>v[0]
==>v[4]
==>v[5]
==>v[6]
==>v[7]

EDITED again to add:
The key part I think people sometimes struggle with is how Gremlin traversals flow. You can think of a query as containing/spawning one or more parallel streams (it may not be executed that way but conceptually it helps me to think of it that way). So g.V('1') creates one stream (we often refer to them as traversers). However g.V('1').out() might create multiple traversers if there is more than one outgoing edge originating from V('1'). When a fold is encountered the traversers are all collapsed back down to one again.


text:
Q: Excel if function I've made this large excel sheet and at the time i didn't know i'd need to sort this table through categories.
I have in a column (J here ) the description of the line and the category joint. (example: "Shipment of tires for usin'ss")
The only way i was able to sort the table the way i wanted was to build a category column using this :
=IF(COUNTIF(J3;"*usi*");"Usins";IF(COUNTIF(J3;"*remis*");"Remise";IF(COUNTIF(J3;"*oe*");"Oenols";IF(COUNTIF(J3;"*KDB*");"KDB";IF(COUNTIF(J3;"*vis*");"cvis";IF(COUNTIF(J3;"*amc*");"AMC";0))))))
usi for instance is a segment of a category name, that i sometimes wrote as

*

*usin'ss

*usin

*usin's

*usins
'cause you know smart.
Anyway, how do i translate =If(If(If...))) into something readable in VBA like:
If...then
If... then

A: Example of "IF ... ELSE" in EVBA
IF condition_1 THEN
  'Instructions inside First IF Block
ELSEIF condition_2 Then
  'Instructions inside ELSEIF Block
...
ELSEIF condition_n Then
  'Instructions inside nth ELSEIF Block
ELSE
  'Instructions inside Else Block
END IF

Example of Case Switch in EVBA
Select Case score
    Case Is >= 90
        result = "A"
    Case Is >= 80
        result = "B"
    Case Is >= 70
        result = "C"
    Case Else
        result = "Fail"
End Select

Both cases work off a waterfall type logic where if the first condition is met, then it does not continue, but if condition 1 is not met then it checks the next, etc.
Example usage:
Function makeASelectAction(vI_Score As Integer) As String

    Select Case vI_Score
        Case Is >= 90
            makeASelectAction = "A, fantastic!"
        Case Is >= 80
            makeASelectAction = "B, not to shabby."
        Case Is >= 70
            makeASelectAction = "C... least your average"
        Case Else
            makeASelectAction = "Fail, nuff said."
    End Select

End Function

Function makeAnIfAction(vS_Destination As String, vS_WhatToSay As String, Optional ovR_WhereToStick As Range, Optional ovI_TheScore As Integer)

    If vS_Destination = "popup" Then
      MsgBox (vS_WhatToSay)

    ElseIf vS_Destination = "cell" Then
      ovR_WhereToStick.value = vS_WhatToSay

    ElseIf vS_Destination = "select" Then
        MsgBox makeASelectAction(ovI_TheScore)

    End If

End Function

Sub PopMeUp()
    Call makeAnIfAction("popup", "Heyo!")
End Sub

Sub PopMeIn()
    Call makeAnIfAction("cell", "Heyo!", Range("A4"))
End Sub

Sub MakeADescision()

    Call makeAnIfAction(vS_Destination:="select" _
                        , vS_WhatToSay:="Heyo!" _
                        , ovI_TheScore:=80 _
    )

End Sub

It will show you how to send variables to functions and how to call said function, it will show you how use optional parameters, how a function and interact with another function or sub, how do write a value to a sheet or spit out a messagebox.  The possabilities are endless.  Let me know if you need anything else cleared up or coded out.

A: You seem to be using CountIf just to see if the contents of the cell matches a certain pattern and, if so, give a replacement string. In VBA you can use the Like operator for pattern matching. In any event -- here is a function I wrote which, when passed a string and a series of pattern/substitution strings, loops through the patterns until it finds a match and then returns the corresponding substitution. If no match is found, it returns an optional default value (the last argument supplied). If no default is supplied, it returns #N/A.
The code illustrates that sometimes complicated nested ifs can be replaced by a loop which iterates through the various cases. This is helpful when you don't know the number of cases before hand.
Function ReplacePattern(s As String, ParamArray patterns()) As Variant
    Dim i As Long, n As Long
    n = UBound(patterns)
    If n Mod 2 = 0 Then n = n - 1
    For i = 0 To n Step 2
        If s Like patterns(i) Then
            ReplacePattern = patterns(i + 1)
            Exit Function
        End If
    Next i
    If UBound(patterns) Mod 2 = 0 Then
        ReplacePattern = patterns(n + 1)
    Else
        ReplacePattern = CVErr(xlErrNA)
    End If
End Function

Your spreadsheet formula is equivalent to
=ReplacePattern(J3,"*usi*","Usins","*remis*","Remise","*oe*","Oenols","*KDB*","KDB","*vis*","cvis","*amc*","AMC",0)


text:
Q: PDO select from where in array() I am listing data from database using "where in" statement, and I don't have problem when my array is short, but I am not able to run this request with long array.
This is my code:
$dbc= new PDO(...);
$numbers="1,2,3,4,5,6,7,8";
$run=$dbc->prepare("SELECT * FROM users WHERE id IN ($numbers)");
$run=execute();

How can I run this code when my numbers is like:
$numbers="1,2,3,4,5,6,7,...3997,3998,3999,4000";


text:
Q: Parse Server User Table Security I am fairly new at using Parse Server (hosted in back4app) and would like to get some clarification on the pre-created 'users' table.
I am currently trying to develop a Web Application (Javascript) using Parse and I am using REST API calls to signup and login users. One thing I have noticed is that anyone can get a hold of my REST API key (through html source), but most importantly anyone can make a GET 'users' request to get all the users in the DB. These results include the username, email, and ObjectID. As a result of this anyone can make another REST call to the 'sessions' table with the ObjectID and retrieve the sessionToken (which I was planning to use as an authorization token for protected REST API calls)
I am not quite sure how this can be safely accomplish. I have search online but without much success. Any help or articles will be greatly appreciated.
Thank you

A: The security access is made throuh the
CLP (Class-Level-Permission) and/or ACL (on each each row).
you should have a look here :
https://parseplatform.github.io/docs/js/guide/#security
Note that : "Session objects can only be accessed by the user specified in the user field. All Session objects have an ACL that is read and write by that user only. You cannot change this ACL. This means querying for sessions will only return objects that match the current logged-in user."
REM : for a web application you should use the Parse "Javascript Key" which can be "public". Try to keep the REST API key more "private" by using it for i.e. only on "third party custom and private server" that could make REST request on your database.


text:
Q: PC does not boot into Windows, but Ubuntu still works well; how to recover? I installed 7 operating systems in my PC. All worked very well. (Ubuntu 11, Ubuntu 14, EduBoss, Redhat6, Nodezero, Windows 8, Win 7). I frequently used Windows 8 and Ubuntu 14 last 6-7 months, I enjoy all operating system but one day after CHKDSK perform by Win7 my PC was unable to start with windows boot. If I try to start windows PC restarts very fast and shows nothing to any options just restart.
All other Linux O.S.  work but no any other Win boot is working.
As per my knowledge I guesses that problem occurred by file corruption or by CHKDSK operation by Windows.
Can I repair Windows boot option by Linux? (without win bootable disk)

*

*Architect i386

*2 Gb ram

*Intel quad core

*OS. First I installed windows and then Linux.

A: One of the methods using Linux is to use fsck.msdos command which is found majorly in most of the Linux Distributions. While you've not mentioned that is there any error shown by Windows and, it is not mentioned too whether it is possible to boot into Safe Mode by pressing and holding Shift and tapping F8 repeatedly. Based on the dearth of information here, I advise booting into Linux, open the Terminal, and type:

*

*sudo fsck.msdos /dev/XYZ where XYZ is the partition where Windows is installed(say sda1).

There are many parameters available which can be accessed by typing fsck.msdos -h but the basic command should be able to correct your Windows.

If that went well, you will want to check whether Linux is able to detect Windows loader now or not. Besides, you need to generate a new GRUB configuration file too. I'm assuming the Linux you're booted into is running Grub 2.0. To Probe the Boot Loader, type the command:

*

*sudo os-probe, it shall give you an output like this:

/dev/sda1:Windows 7 (loader):Windows:chain

If you receive any such output, you can go ahead for building new Grub configuration file. In Terminal, type:

*

*sudo grub-mkconfig -o /boot/grub/grub.cfg, if your grub.cfg is at some other location then replace the path in the command with your file location.

*Type sudo grub-install /dev/sda where sda is my primary HDD having Windows and Linux installed.

Reboot, and choose Windows in Grub Menu. it should boot. If it doesn't we can try other methods but your question demands only Linux-specific solution.

A: Have you try Boot-Repair tool? It seems that your boot files were messed up by CHKDSK.

A: 1> use win7 disk
2> start up repair
3> chkdsk >>>> restart
after restart win boot louder start but GRUB not.
to fix that USE "BOOT-repair" disk and "fsck.msdos" commands. both answers are very helpful together.


text:
Q: Celery beat - different time zone per task I am using celery beat to schedule some tasks. I'm able to use the CELERY_TIMEZONE setting to schedule the tasks using the crontab schedule and it runs at the scheduled time in the mentioned time zone.
But I want to be able to setup multiple such tasks for different timezones in the same application (single django settings.py). I know which task needs to run in what timezone when the task is being scheduled.
Is it possible to specify a different timezone for each of the tasks?
I'm using django (1.4) with celery (3.0.11) and django celery (3.0.11).
I've looked at the djcelery.schedulers.DatabaseScheduler class and it's base class, but I can't figure out how and where the timezone is getting used. Can I write a custom scheduler that can make each job run in a different timezone?
Thanks,

A: You can achieve a timezone-aware scheduling of individual tasks in a celery schedule. This way you can run a task according to the local time in a specific timezone (also adjusting to e.g. daylight saving time) by specifying a separate now function for each celery schedule
crontab supports the nowfun argument to specify the datetime function to be used to check if it should run
import datetime
import pytz
nowfun = lambda: datetime.datetime.now(pytz.timezone('Europe/Berlin'))

In your schedule, set this function as the datetime function via
'periodic_task': {
    'task': 'api.tasks.periodic',
    'schedule': crontab(hour=6, minute=30, nowfun=nowfun)
}

This runs every day at 6.30am CET adjusted to daylight savings.
In case you use the function more than once, consider creating a helper
from functools import partial
cet_crontab = partial(crontab, nowfun=nowfun)
'periodic_task': {
    'task': 'api.tasks.periodic',
    'schedule': cet_crontab(hour=6, minute=30)
}

Make sure you have CELERY_ENABLE_UTC = False set, otherwise celery converts your schedules to UTC.

A: I think the easiest way to do it is to use decorator with mock
from mock import patch

@task
@patch.multiple(settings, CELERY_TIMEZONE='time_zone')
def my_task(*args):
    #do your staff

I'm not tested it yet but it seems right. I hope i helped you :)

A: In my case, I needed a function that will run every time and get a timezone for a specific value from db.
I created a new function that will accept a variable and will get me the timezone needed.

def get_time(db_query: str) -> datetime.datetime:
    """Extract timezone from DB"""

    # get location from db
    timezone = 'get timezone for location'
    # return calculated datetime using timezone
    return datetime.datetime.now(pytz.timezone(timezone))

def custom_crontab(*args, **kwargs):
    """Create a custom crontab that will call get_time function and assign value to nowfun"""

    db_query = kwargs.pop("db_query")
    nowfun = get_time(db_query)
    kwargs['nowfun'] = nowfun
    # return the call to crontab
    return crontab(*args, **kwargs)

beat_schedule = {
    'periodic_task': {
        'task': 'main_job',
        'schedule': custom_crontab(minute=0, db_query='some_value'),
    }
}

A: Maybe I'm misunderstanding the problem, but if you want to run tasks at a certain time in different time zones, could you not just offset the scheduled time by the hour difference between the time zones? For example, if I wanted a task to run at 5 PM in two different TZs:
# settings.py
CELERY_TIMEZONE = "US/Eastern"

CELERYBEAT_SCHEDULE = {
    # Task to run in EST
    'schedule-my-est-task': {
        'task': 'path.to.my.est.task',
        'schedule': crontab(minute=0, hour=17),
    },
    # Task to run in UTC - hour time is offset
    'schedule-my-utc-task': {
        'task': 'path.to.my.utc.task',
        'schedule': crontab(minute=0, hour=10),
    },
}


text:
Q: Error in com.sun.speech.freetts.* this is my code
import com.sun.speech.freetts.Voice;
import com.sun.speech.freetts.VoiceManager;

public class FreeTTS {

 private static final String VOICENAME_kevin = "kevin";
 private String text; // string to speech

 public FreeTTS(String text) {
  this.text = text;
 }

 public void speak() {
  Voice voice;
  VoiceManager voiceManager = VoiceManager.getInstance();
  voice = voiceManager.getVoice(VOICENAME_kevin);
  voice.allocate();
  voice.speak(text);
 }

 public static void main(String[] args) {
  String text = "FreeTTS was written by the Sun Microsystems Laboratories "
    + "Speech Team and is based on CMU's Flite engine.";
  FreeTTS freeTTS = new FreeTTS(text);
  freeTTS.speak();
 }
}

it is givivng an error on "com.sun.speech" in imports,although i include lib folder from freetts into this project.
Any kind of help would be appreciated.

A: I gone through your code it require freetts-1.0.jar
 just download it and then
add this jar to your project classpath
or create a newfolder in name it lib and then paste freetts-1.0.jar in that folder( i.e lib) and then add that jar.


text:
Q: python "hide" a big literal at the end of the source code/forward reference? I have this source file set up to run tests if it is run as __main__.
if __name__ == '__main__':
    import sys

    expected_output = '''
         (60-line literal that represents the correct output)'''

    [run the tests collecting output in a variable named output]

    [compare output to expected_output]

I would love to put that huge literal down at the bottom of the file, but I can't think of a way to create a forward reference to it.
Am I just basically out of luck?

A: Yup, in python everything should be defined before you use it. I'd recommend to put the literal into a different file.
If you must, technically, you can put your literal into the same file, at the very end of the code and then read it with introspection or just as a file.
with open(__file__) as f: expected_output = f.read().rsplit("'''")[-2]

though I find storing large literals in separate file(s) is easier to maintain and read.

A: You have to assign the data before you can use it. The trick is to put the stuff you currently have in if __name__==__main__ into a function at the top of the code. Then you can put all the good code in that function, add the big blob of ugliness and put a very simple if at the bottom. By the time main() is called, the variable as been assigned and you are good to go.
import sys # aren't saving anything by putting it in the `if`

def main():
    [run the tests collecting output in a variable named output]
    [compare output to expected_output]

expected_output = '''
    (60-line literal that represents the correct output)'''

if __name__ == '__main__':
    main()

@tdelaney Here is a slight embellishment on your suggestion.
def main(expected_output):
    [run the tests collecting output in a variable named output]
    [compare output to expected_output]

if __name__ == '__main__':
    main(
'''
(60-line literal that represents the correct output)
'''
)


text:
Q: How to view dicom images in android? I want to view .dcm file in my project so can please suggest me any library or way to view dicom files in android.
thanks.

A: You can download Droid Dicom Viewer from the below url
https://code.google.com/p/droid-dicom-viewer/
It is Free and Open Source Software (FOSS) licensed under the terms of the GNU General Public License as published by the Free Software Foundation.


text:
Q: cakephp global variable for controllers I'm trying to change my database connection depending on who is trying to log in to my page.
What I need is a way to save the correct db name so its accessible by all my controllers.
Using a session would work, but I doubt its safe and/or good practice.
If I could set a variable in the AppController from my AccountsController that would be perfect. but basically any way that enables me to share a variable between all controllers.
In my AccountsController I query a standard database for the correct name. then I use configure::write('CompanyDB', $myDbVar). this work fine for this controller, but I cant use configure::read('CompanyDB') in any other controllers.
In my AppModel i have a construct fucntion that sets the db connection depending on the value inside configure::read('campanyDB') as mentioned before, I need to use configure::write('CompanyDB',$myDbVar) in all my controllers for this to work.
In my Account Model I set the $specific=true. this tells the AppModel that it should use the construct and change the db connection.
class AccountsController extends AppController {

    public $helpers = array('Html', 'Form','Js');
    public $components = array('RequestHandler');
    var $uses = array('User', 'Company');
    public $name = 'Accounts';
    public $myDbVar='coolbeans';

    public function beforeFilter() {
        parent::beforeFilter();
        Configure::write( 'companyDB',$this->myDbVar);
    }
}

class AppModel extends Model {
    var $specific = false;
    function __construct($id = false, $table = null, $ds = null) {
        if ($this->specific) {
            // Get saved company/database name
            $dbName = Configure::read('companyDB');
            // Get common company-specific config (default settings in database.php)
            $config = ConnectionManager::getDataSource('companySpecific')->config;
            // Set correct database name
            $config['database'] = $dbName;
            // Add new config to registry
            ConnectionManager::drop('companySpecific');
            ConnectionManager::create('companySpecific', $config);
            // Point model to new config
            $this->useDbConfig = 'companySpecific';
        }
        parent::__construct($id, $table, $ds);
    }
}

class Account extends AppModel {

    public $primaryKey = '_id';
    //var $useDbConfig = 'mongo';
    var $specific = true;
    .....
}

A: Probably best bet would be to go with a Configuration file:
Reading and Writing Configuration Files:
http://book.cakephp.org/2.0/en/development/configuration.html#reading-and-writing-configuration-files
The basic idea is, you create a file in your Config/ directory with settings for your app, then, in the bootstrap, you load that config file, which makes any of those variables available anywhere in the app.
Example file:  Config/dbconnections.php
<?php
$config = array(
    'MyAppDBs' => array(
        'company1' => 'connectionName',
        'company2' => 'differentConnectionName
    )
);

In your bootstrap file:
Configure::load('dbconnections');

Anywhere in your App:
$whatever = Configure::read('MyAppDBs.companyDB');

A: I think if you do this
configure::write('CompanyDB', $myDbVar);

in your appController then you can access it in any controller using
configure::write('CompanyDB',$myDbVar);

since all controller inherits appController.


text:
Q: VBA code from 32 bit to 64 bit - Ms Access I've built an application on a 64bit machine (windows 7) running 32bit Microsoft Office.  The client machine is 64bit windows and 64bit office.
I initially had problems with comdlg32.dll but included the PtrSafe keyword.  The next problem was a missing IPCONFIG.dll which I installed into the client machine.
I now have it compiling okay but I am trying to use the file save dialog (code by Ken Getz).  It seems to be skipping over opening the actual dialog and runs straight to runtime error 2522 (file name required).  Any help appreciated.  This is the code I'm using (that refers back to Ken Getz's functions):
Function exportData_Click()

Dim strFilter As String
Dim strSaveFileName As String
Dim The_Year As Variant

Dim ctlCurrentControl As Control
Dim queryName As String

'Get the name of the control button clicked (corresponds to query name to be run)
Set ctlCurrentControl = Screen.ActiveControl
queryName = ctlCurrentControl.Name

'Get combobox value and assign relavent values to The_Year
The_Year = Forms![Extract Data]!Extract_Year.value

'Change the year from a variant to what we need in the SQL

If The_Year Like "20*" Then
    The_Year = CInt(The_Year)
    'MsgBox The_Year & "Data Type = " & VarType(The_Year)
Else: The_Year = "*"
'MsgBox The_Year & "Data Type = " & VarType(The_Year)
End If

'Set queryYear variable
setYear (The_Year)

'Check the variable is correct
'MsgBox getYear()

'Open the Save as Dialog to choose location of query save

strFilter = ahtAddFilterItem("Excel Files (*.xlsx)", "*.xlsx")

strSaveFileName = ahtCommonFileOpenSave( _
                                openFile:=False, _
                                Filter:=strFilter, _
                Flags:=ahtOFN_OVERWRITEPROMPT Or ahtOFN_READONLY)

DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, queryName, strSaveFileName

End Function

Debugging points to this line:
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, queryName, strSaveFileName

A: I found that this code will work with MS Access 64:
Function GetFile(strStartIn As String, strFilter As String) As String
Dim f As Object

   Set f = Application.FileDialog(3)
   f.AllowMultiSelect = False
   f.InitialFileName = strStartIn & strFilter
   f.Show

   GetFile = f.SelectedItems(1)
End Function

It is not as neat as Ken Getz' code, but should be suitable to choose a file to save or open. You can reference the Microsoft Office library to use built-in constants such as :
msoFileDialogOpen (1)
msoFileDialogSaveAs (2)
msoFileDialogFilePicker (3)
msoFileDialogFolderPicker (4)

( http://msdn.microsoft.com/en-us/library/office/aa190813(v=office.10).aspx#ofobjFileDialogFilters )

A: An alternative method that worked well for my application was to check the version of VBA:
#if Vba7 then
'  Code is running in the new VBA7 editor
     #if Win64 then
     '  Code is running in 64-bit version of Microsoft Office
     #else
     '  Code is running in 32-bit version of Microsoft Office
     #end if
#else
' Code is running in VBA version 6 or earlier
#end if

#If Vba7 Then
Declare PtrSafe Sub...
#Else
Declare Sub...
#EndIf

http://msdn.microsoft.com/en-us/library/office/gg264421.aspx


text:
Q: Asynchronous Controllers in Web Api I have very basic fundamental doubt regarding asynchronous Web API programming. I want to make  call to SaveCaseSearch in my controller asynchronously. But the call passes through various layers of DAL and eventually calls DB.
Should those consecutive calls also be made asynchronous ?
I am very new to the world of async so I might already have made some mistakes. Just correct me if anything seems wrong.
So for the controller , I am doing something like the below :
/*Create API for Case*/
[HttpPost]
[Route("createcase")]
public IHttpActionResult PostCreateCase([FromBody]  ARC.Donor.Business.Case.CreateCaseInput CreateCaseInput)
{
    ARC.Donor.Service.Case.CaseServices cs = new ARC.Donor.Service.Case.CaseServices();
    var searchResults = cs.createCase(CreateCaseInput);
    List<CreateCaseOutput> searchOutputResults = (List<CreateCaseOutput>)searchResults;
    if (!string.IsNullOrEmpty(searchOutputResults.ElementAt(0).o_case_seq.ToString()))
       SaveCaseSearchDetails(SaveSearchInput); /*This should be called asynchronously*/
    return Ok(searchResults);
}

This
SaveCaseSearchDetails
now needs to be called in async mode . So I have written :
[HttpPost]
public async Task<IHttpActionResult> SaveCaseSearchDetails([FromBody]  ARC.Donor.Business.SaveSearchInput SaveSearchInput)
{
    ARC.Donor.Service.Case.CaseServices cs = new ARC.Donor.Service.Case.CaseServices();
    var searchResults = await cs.saveCaseSearchDetails(SaveSearchInput);
}

Then if that is correct
should the consecutive calls be async too ?
For now they are
public IList<Entities.Case.SaveCaseSearchOutput> saveCaseSearch(ARC.Donor.Data.Entities.Case.SaveCaseSearchInput SaveCaseSearchInput)
{
    Repository rep = new Repository();
    string strSPQuery = string.Empty;
    List<object> listParam = new List<object>();
    SQL.CaseSQL.getCreateCaseParameters(SaveCaseSearchInput, out strSPQuery, out listParam);
    var AcctLst = rep.ExecuteStoredProcedure<Entities.Case.SaveCaseSearchOutput>(strSPQuery, listParam).ToList();
    return AcctLst;
}

Is
SQL.CaseSQL.getCreateCaseParameters
method needs to be called in async manner ?
But in that case the immediate next line
rep.ExecuteStoredProcedure
can't execute successfully right ? Because strSPQuery comes from the previous line itself ?
I am thinking in a wrong way ? Please correct me .

A:
Should those consecutive calls also be made asynchronous?

Yes.

SaveCaseSearchDetails now needs to be called in async mode

That's the hard way of doing it.
A much more natural approach is to start at the other end. Whatever part of your code is actually executing the database query should be made asynchronous first. Then you call it using await, which makes those methods async, so they should be called with await, etc., until you finally reach your controller action which is the last thing to be made asynchronous.

actually the problem I am facing is SaveCaseSearchDetails(SaveSearchInput) in PostCaseCreate method needs to be called somewhat async because we don't want to wait for return Ok(searchResults)

Ah, that's a totally different question. You want to return early. Async will not help you do this; as I explain on my blog (and in an MSDN article on async ASP.NET), async does not change the HTTP protocol.
There are a few approaches to returning early or "fire and forget" on ASP.NET that I describe on my blog. However, ASP.NET was not designed for this scenario, so you need to tread carefully. The only fully reliable solution is a properly distributed architecture.

A: You cannot call SQL.CaseSQL.getCreateCaseParameters in an async manner (with await) since it uses the out keyword which isn't available for async metods.
If you want your DB call to happen async you'll have to find a DB method that you can await. Then you can change the saveCaseSearch method to also be async and await it from your controller method.


text:
Q: The value of $x^2+y^2+z^2+w^2$ Let$x,y,z,w$ satisfy
$$\frac{x^2}{2^2 - 1^2} +\frac{y^2}{2^2 - 3^2} +\frac{z^2}{2^2 - 5^2} +\frac{w^2}{2^2 - 7^2} =1$$
$$\frac{x^2}{4^2 - 1^2} +\frac{y^2}{4^2 - 3^2} +\frac{z^2}{4^2 - 5^2} +\frac{w^2}{4^2 - 7^2} =1$$
$$\frac{x^2}{6^2 - 1^2} +\frac{y^2}{6^2 - 3^2} +\frac{z^2}{6^2 - 5^2} +\frac{w^2}{6^2 - 7^2} =1$$
$$\frac{x^2}{8^2 - 1^2} +\frac{y^2}{8^2 - 3^2} +\frac{z^2}{8^2 - 5^2} +\frac{w^2}{8^2 - 7^2} =1$$
My work
$$\frac{x^2}{t - 1^2} +\frac{y^2}{t - 3^2} +\frac{z^2}{t - 5^2} +\frac{w^2}{t - 7^2} =1$$
where $t $ satisfy $4,16,36,64$
$$f(t)=0$$
$$f(t) = (t – 1)(t – 9)(t – 25)(t – 49)–x^2(t – 9)(t – 25)(t – 49) –y^2(t – 1)(t – 25)(t – 49) – z^2(t–1)(t–9)(t–49) – w^2(t–1)(t–9)(t–25)$$
then I compared the coefficient with different value of $t$ .
I want to know that is there any easier alternative methods for this .

A: Expanding
\begin{equation*}
\frac{x^2}{t - 1^2} +\frac{y^2}{t - 3^2} +\frac{z^2}{t - 5^2} +\frac{w^2}{t - 7^2} =1
\end{equation*}
we get
\begin{equation*}
(t-1^2)(t-3^2)(t-5^2)(t-7^2) - (t-3^2)(t-5^2)(t-7^2)x^2 - \text{ similar terms } = 0
\end{equation*}
This biquadratic in $t$ has four roots $2^2, 4^2, 6^2, 8^2$ and coefficient of $t^3$ is $-(2^2+4^2+6^2+8^2)$. The coefficient of $t^3$ is also given by
\begin{equation*}
-(1^2+3^2+5^2+7^2) - (x^2+y^2+z^2+w^2)
\end{equation*}
and hence
\begin{equation*}
-(1^2+3^2+5^2+7^2) - (x^2+y^2+z^2+w^2) = -(2^2+4^2+6^2+8^2)
\end{equation*}
Hence we have
\begin{equation*}
x^2+y^2+z^2+w^2 = (2^2+4^2+6^2+8^2)-(1^2+3^2+5^2+7^2)=36
\end{equation*}

A: Set up a matrix equation
$$\begin{bmatrix} a_{11} & a_{12} & a_{13} & a_{14}\\ a_{21} & a_{22} & a_{23} & a_{24}\\ a_{31} & a_{32} & a_{33} & a_{34}\\ a_{41} & a_{42} & a_{43} & a_{44} \end{bmatrix} \begin{bmatrix} x^{2}\\y^{2}\\z^{2}\\w^{2}\end{bmatrix} = \begin{bmatrix} 1\\1\\1\\1\end{bmatrix}$$
and then solve. You can essentially ignore the fact that your variables are squared, and just assume that means they must all be nonnegative.

A: I multiplied the equations out to get:
$$\begin{pmatrix} -4725 & 2835 & 675 & 315 \\
2079 & 4455 & -3465 & -945 \\
-3861 & -5005 & -12285 & 10395 \\
32175 & 36855 & 51975 & 135135 \\
\end{pmatrix}
\begin{pmatrix} x^{2}\\y^{2}\\z^{2}\\w^{2}\end{pmatrix} =
\begin{pmatrix} -14175 \\
31185 \\
-135135 \\
2027025 \\
\end{pmatrix}$$
Then  inverted the matrix and solved to get:
$$\begin{pmatrix} x^{2}\\y^{2}\\z^{2}\\w^{2}\end{pmatrix} =
\begin{pmatrix} 10.76660156 \\
10.15136719 \\
8.797851563 \\
6.284179688
\end{pmatrix}
$$
giving
$$x^2+y^2+z^2+w^2=36$$
 - so there probably is an algebraic short cut to that.


text:
Q: CSS Global Class Issue with Child i have a global class for an html

and the CSS is
.div { width:auto; display:block }

.content {  width:100px;  height:50px; }

On the .content div, i do not need "display:block" class. But Its applying on Runtime.
i Have given dispay:inherit; but it doesn't work. Is there any Other Way for Removing the Display Style ?

A: .content {  width:100px;  height:50px; display: inline; }

or another display property

A: You can just do:
.content {  width:100px;  height:50px; display:inline }
//or display:none or whatever your standard default is

inline is what the value is by default, see MDN Ref.

A: .div { width:auto; display:block }

this might not be working....for the above provided html cos there is not div named class
what you can do is
.content {  width:100px;  height:50px; display:inline}


text:
Q: Get syncfusion Schedule data on a specific cell in Blazor I am new in SynFusion and Blazor. I read The Synfusion Document and I find myself in situation that I want to get the synfusion cell data and pass data in a Radzen dialogservice. First I have to get the Synfusion Scheduler cell Data . Which Event may I have get that?
For example ScheduleEvents OnCellClick I get Start Date and End Date.But I have to click the empty cell. Now if I click on a cell that have data and showing someone appointment I want to edit so I have to get the data for example I show in a picture of my sfschedule in below to explain:

If I click "Kevin sick 2 hours off" I could not get data and
<ScheduleEvents TValue="AppointmentData" OnPopupOpen="@OnPopupOpen" OnCellClick="OnCellClickAsync" >

I am talking about the OnCellClick .
<SfSchedule TValue="AppointmentData"   SelectedDateChanged="CommandDateChanged" Width="100%" Height="600px" EnableAutoRowHeight="true" SelectedDate="@DateTime.Now" DateFormat="yyyy/MM/dd" @bind-CurrentView="@CurrentView">

        <ScheduleResources>
            <ScheduleResource TItem="ResourceData" TValue="int" DataSource="@ProjectData" Field="Id" TextField="Text" ColorField="Color">

            </ScheduleResource>
        </ScheduleResources>
        <ScheduleEvents TValue="AppointmentData" OnPopupOpen="@OnPopupOpen" OnCellClick="OnCellClickAsync" > </SfSchedule>

And here is my OnCellClick of C#
 public async Task OnCellClickAsync(CellClickEventArgs args)
    {

        var parameters2 = new Dictionary<string, object>();
        parameters2.Add("StartDate", args.StartTime.Date.ToString());
        parameters2.Add("EndDate", args.StartTime.Date.ToString());
        var notificationMessage = new Radzen.NotificationMessage();
        notificationMessage.Severity = Radzen.NotificationSeverity.Success;
        notificationMessage.Duration = 4000;
    }

You can see on CellClickEventArgs I can get start date and end date of current cell. But that is only where there is no data. I want to update and that's why I want to get cell data. How can I get current cell data as per the picture I have shown?

A: You can get the event details on OnEventClick event, please refer to the following UG. You can access your event details on Event.
https://blazor.syncfusion.com/documentation/scheduler/events/#oneventclick
If you want to get the event details on OnCellClick event, you can use GetEvents method using which can can get all the events available in that cell.
    public async Task OnCellClick(CellClickEventArgs args)
    {
        args.Cancel = true;
        List<AppointmentData> events = await
            ScheduleRef.GetEvents(args.StartTime, args.EndTime);
    }


text:
Q: value-of select="document($path)/ns0:element1/ns0:element2" returns NULL with SAXON-B XSLT 2.0 (saxon9) The getdetails.xslt code (XSLT 2.0) below reads the contents of user-config.xml via a document().
The code successfully works against Saxon 9.4.0.6 and the value of ns0:project_abs_path is visible in the xml output as shown below
<?xml version = "1.0" encoding = "UTF-8"?>
<xmlString><?xml version="1.0" encoding="UTF-8"?> C:\myProject</xmlString>

However, the below xml output (NOTE:no value for ns0:project_abs_path) is returned when the same XSLT code is run against SAXON-B XSLT 2.0 (saxon9) in TIBCO Transform Activity.
<?xml version = "1.0" encoding = "UTF-8"?>
<xmlString><?xml version="1.0" encoding="UTF-8"?></xmlString>

*There is no error returned.
user-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<ns0:userRules xmlns:ns0="http://www.tibco.com/schemas/-bw/SharedResources/Schema.xsd">
    <ns0:project_abs_path>C:\myProject1</ns0:project_abs_path>
</ns0:userRules>

getdetails.xslt
<?xml version='1.0'?>
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ns0="http://www.tibco.com/schemas/bw/SharedResources/Schema.xsd"
xmlns:ns1="http://www.tibco.com/schemas/bw/SharedResources/rule-db.xsd">
<xsl:output method="xml" encoding="UTF-8"/>
<xsl:param name="invar_ruleid"/>
<xsl:variable name="var_installation_path">C:\FOLDER</xsl:variable>
<xsl:variable name="var_user_config_path" select="concat($var_installation_path,'\bin\user-config.xml')"/>
<xsl:variable name="var_project_abs_path" select="document($var_user_config_path)/ns0:userRules/ns0:project_abs_path"/>
<xsl:variable name="file">file:///</xsl:variable>
<xsl:variable name="var_out_file_path" select="concat($file,$var_project_abs_path)"/>
<xsl:template match="/">
<xsl:value-of select="document(concat($var_installation_path,'\bin\user-config.xml'))/ns0:userRules/ns0:project_abs_path"/>
</xsl:template>
</xsl:stylesheet>

A: Saying "A NULL is returned" is a very vague. Could you be more explicit? Are you seeing an exception, or a Saxon error message, or incorrect transformation results? If you see an exception, could you show the stack trace? If you see a Saxon error message, could you tell us what it is?
The only thing obviously wrong with your code is that you are constructing a Windows filename (in the form "c:\a\b\c") and passing this to the document() function, which expects a URI. In theory this is always wrong, but some applications tolerate it. You should be passing a URI of the form "file:///c:/a/b/c". I have no idea whether this is the cause of the problem.


text:
Q: Read any JSON into list of key-value pairs (EAV format) in SQL Server Looking for a way to read any JSON without knowing the internals with SQL Server's JSON methods, I came up with an approach I'd like to share.
Here is the question bringing up this issue.
The question is: How can I transform an unknown JSON into a structured EAV format while keeping all the information about sort order and nest levels.
The ideal output should carry the original row's id as the entity, the Json's key and value as the attribute and value together with the JsonPath for the specific object in a sorted list.
Find the MCVE (sample data from the linked question) embedded into my self-answer.

A: First we create a declared table variable and fill it with some sample JSONs to simulate the issue (I added some arrays to the samples to reflect JSON paths for arrays):
DECLARE @table TABLE(ID INT IDENTITY, AnyJSON NVARCHAR(MAX));
INSERT INTO @table VALUES
(N' {
    "correlationId": "c3xOeEEQQCCA9sEx7-u6FA",
    "eventCreateTime": "2020-05-12T15:38:23.717Z",
    "time": 1589297903717,
    "owner": {
        "ownergeography": {
            "city": "abc",
            "country": "abc"
        },
        "ownername": {
            "firstname": "abc",
            "lastname": "def"
        },
        "clientApiKey": "xxxxx",
        "businessProfileApiKey": null,
        "userId": null
    },
    "campaignType": "Mobile push"
}')
,(N'[{
    "correlationIds": [
        {
            "campaignId": [1,2,3],
            "correlationId": [{"a":"b"},{"c":"d"},{"e":"f"}]
        }
    ],
    "variantId": 1278915,
    "utmCampaign": "",
    "ua.os.major": "8"
    }
    ,{
    "correlationIds": [
        {
            "campaignId": [1,2,3],
            "correlationId": [{"a":"b"},{"c":"d"},{"e":"f"}]
        }
    ],
    "variantId": 1278915,
    "utmCampaign": "",
    "ua.os.major": "8"
    }]')
,(N'{
    "correlationId": "ls7XmuuiThWzktUeewqgWg",
    "eventCreateTime": "2020-05-12T12:40:20.786Z",
    "time": 1589287220786,
    "modifiedBy": {
        "clientId": null,
        "clientApiKey": "xxx",
        "businessProfileApiKey": null,
        "userId": null
    },
    "campaignType": "Mobile push"
}');

--The query
WITH recCTE AS
(
    SELECT ID
          ,NestLevel   = 0
          ,ObjectIndex = CAST(1 AS bigint)
          ,SortString  = CAST(N'sort'                       COLLATE DATABASE_DEFAULT AS NVARCHAR(MAX))

          ,JsonPath    = CAST(N'$'                          COLLATE DATABASE_DEFAULT AS NVARCHAR(MAX))
          ,JsonKey     = CAST(N'$'                          COLLATE DATABASE_DEFAULT AS NVARCHAR(MAX))
          ,JsonValue   = CAST(AnyJSON                       COLLATE DATABASE_DEFAULT AS NVARCHAR(MAX))
          ,JsonType    = CAST(CASE WHEN LEFT(TRIM(AnyJSON),1)=N'[' THEN 4 ELSE 0 END AS TINYINT)
          ,NestedJSON  = CAST(CASE WHEN ISJSON(AnyJSON)=1
                                   THEN AnyJSON
                                   ELSE NULL END            COLLATE DATABASE_DEFAULT AS NVARCHAR(MAX))
    FROM @table t

    UNION ALL

    SELECT r.ID
          ,r.NestLevel+1
          ,ROW_NUMBER() OVER(ORDER BY (SELECT NULL))
          ,CAST(CONCAT(r.SortString,REPLACE(STR(ROW_NUMBER() OVER(ORDER BY (SELECT NULL)),5),' ','0')) COLLATE DATABASE_DEFAULT AS NVARCHAR(MAX))

          ,CAST(CONCAT(r.JsonPath, CASE WHEN r.JsonType=4 --<-- see the docs for OPENJSON()
                                        THEN CONCAT('[',A.[key],']')
                                        ELSE '.' + A.[key] END)                       COLLATE DATABASE_DEFAULT AS NVARCHAR(MAX))
          ,CAST(A.[key]                                                               COLLATE DATABASE_DEFAULT AS NVARCHAR(MAX))
          ,CAST(r.JsonValue                                                           COLLATE DATABASE_DEFAULT AS NVARCHAR(MAX))
          ,A.[type]
          ,CAST(A.[value]                                                             COLLATE DATABASE_DEFAULT AS NVARCHAR(MAX))
    FROM recCTE r
    CROSS APPLY OPENJSON(r.NestedJSON) A
    WHERE ISJSON(r.NestedJSON)=1
)
SELECT ID
      ,NestLevel
      ,ObjectIndex
      ,JsonPath
      ,JsonKey
      ,NestedJSON AS JsonValue
      ,SortString --<-- just to illustrate the sorting, not needed in the output
FROM recCTE
WHERE ISJSON(NestedJSON)=0
ORDER BY ID,SortString;

The result
+----+-------------------------------------------+-----------------+--------------------------+---------------------------------+
| ID | JsonPath                                  | JsonKey         | JsonValue                | SortString                      |
+----+-------------------------------------------+-----------------+--------------------------+---------------------------------+
| 1  | $.correlationId                           | correlationId   | c3xOeEEQQCCA9sEx7-u6FA   | 0    1                          |
+----+-------------------------------------------+-----------------+--------------------------+---------------------------------+
| 1  | $.eventCreateTime                         | eventCreateTime | 2020-05-12T15:38:23.717Z | 0    2                          |
+----+-------------------------------------------+-----------------+--------------------------+---------------------------------+
| 1  | $.time                                    | time            | 1589297903717            | 0    3                          |
+----+-------------------------------------------+-----------------+--------------------------+---------------------------------+
| 1  | $.owner.ownergeography.city               | city            | abc                      | 0    4    1    1                |
+----+-------------------------------------------+-----------------+--------------------------+---------------------------------+
| 1  | $.owner.ownergeography.country            | country         | abc                      | 0    4    1    2                |
+----+-------------------------------------------+-----------------+--------------------------+---------------------------------+
| 1  | $.owner.ownername.firstname               | firstname       | abc                      | 0    4    2    1                |
+----+-------------------------------------------+-----------------+--------------------------+---------------------------------+
| 1  | $.owner.ownername.lastname                | lastname        | def                      | 0    4    2    2                |
+----+-------------------------------------------+-----------------+--------------------------+---------------------------------+
| 1  | $.owner.clientApiKey                      | clientApiKey    | xxxxx                    | 0    4    3                     |
+----+-------------------------------------------+-----------------+--------------------------+---------------------------------+
| 1  | $.campaignType                            | campaignType    | Mobile push              | 0    5                          |
+----+-------------------------------------------+-----------------+--------------------------+---------------------------------+
| 2  | $[0].correlationIds[0].campaignId[0]      | 0               | 1                        | 0    1    1    1    1    1      |
+----+-------------------------------------------+-----------------+--------------------------+---------------------------------+
| 2  | $[0].correlationIds[0].campaignId[1]      | 1               | 2                        | 0    1    1    1    1    2      |
+----+-------------------------------------------+-----------------+--------------------------+---------------------------------+
| 2  | $[0].correlationIds[0].campaignId[2]      | 2               | 3                        | 0    1    1    1    1    3      |
+----+-------------------------------------------+-----------------+--------------------------+---------------------------------+
| 2  | $[0].correlationIds[0].correlationId[0].a | a               | b                        | 0    1    1    1    2    1    1 |
+----+-------------------------------------------+-----------------+--------------------------+---------------------------------+
| 2  | $[0].correlationIds[0].correlationId[1].c | c               | d                        | 0    1    1    1    2    2    1 |
+----+-------------------------------------------+-----------------+--------------------------+---------------------------------+
| 2  | $[0].correlationIds[0].correlationId[2].e | e               | f                        | 0    1    1    1    2    3    1 |
+----+-------------------------------------------+-----------------+--------------------------+---------------------------------+
| 2  | $[0].variantId                            | variantId       | 1278915                  | 0    1    2                     |
+----+-------------------------------------------+-----------------+--------------------------+---------------------------------+
| 2  | $[0].utmCampaign                          | utmCampaign     |                          | 0    1    3                     |
+----+-------------------------------------------+-----------------+--------------------------+---------------------------------+
| 2  | $[0].ua.os.major                          | ua.os.major     | 8                        | 0    1    4                     |
+----+-------------------------------------------+-----------------+--------------------------+---------------------------------+
| 2  | $[1].correlationIds[0].campaignId[0]      | 0               | 1                        | 0    2    1    1    1    1      |
+----+-------------------------------------------+-----------------+--------------------------+---------------------------------+
| 2  | $[1].correlationIds[0].campaignId[1]      | 1               | 2                        | 0    2    1    1    1    2      |
+----+-------------------------------------------+-----------------+--------------------------+---------------------------------+
| 2  | $[1].correlationIds[0].campaignId[2]      | 2               | 3                        | 0    2    1    1    1    3      |
+----+-------------------------------------------+-----------------+--------------------------+---------------------------------+
| 2  | $[1].correlationIds[0].correlationId[0].a | a               | b                        | 0    2    1    1    2    1    1 |
+----+-------------------------------------------+-----------------+--------------------------+---------------------------------+
| 2  | $[1].correlationIds[0].correlationId[1].c | c               | d                        | 0    2    1    1    2    2    1 |
+----+-------------------------------------------+-----------------+--------------------------+---------------------------------+
| 2  | $[1].correlationIds[0].correlationId[2].e | e               | f                        | 0    2    1    1    2    3    1 |
+----+-------------------------------------------+-----------------+--------------------------+---------------------------------+
| 2  | $[1].variantId                            | variantId       | 1278915                  | 0    2    2                     |
+----+-------------------------------------------+-----------------+--------------------------+---------------------------------+
| 2  | $[1].utmCampaign                          | utmCampaign     |                          | 0    2    3                     |
+----+-------------------------------------------+-----------------+--------------------------+---------------------------------+
| 2  | $[1].ua.os.major                          | ua.os.major     | 8                        | 0    2    4                     |
+----+-------------------------------------------+-----------------+--------------------------+---------------------------------+
| 3  | $.correlationId                           | correlationId   | ls7XmuuiThWzktUeewqgWg   | 0    1                          |
+----+-------------------------------------------+-----------------+--------------------------+---------------------------------+
| 3  | $.eventCreateTime                         | eventCreateTime | 2020-05-12T12:40:20.786Z | 0    2                          |
+----+-------------------------------------------+-----------------+--------------------------+---------------------------------+
| 3  | $.time                                    | time            | 1589287220786            | 0    3                          |
+----+-------------------------------------------+-----------------+--------------------------+---------------------------------+
| 3  | $.modifiedBy.clientApiKey                 | clientApiKey    | xxx                      | 0    4    2                     |
+----+-------------------------------------------+-----------------+--------------------------+---------------------------------+
| 3  | $.campaignType                            | campaignType    | Mobile push              | 0    5                          |
+----+-------------------------------------------+-----------------+--------------------------+---------------------------------+

The idea in short:

*

*we use a recursive CTE to walk this down.

*The query will test any fragment ([value] coming from OPENJSON) for being valid JSON.

*If the fragment is valid, this walks deeper and deeper.

*The column SortString is needed to get a final sort order.

*The CAST() and COLLATE helps to avoid data type mismatch. Recursive CTEs are very picky with this...

Hint: If you deal with bigger JSONs you might need to set OPTION (MAXRECURSION 0) at the end of your query.
Enjoy :-)
Something similar for XML
Here is a similar answer about how to read an unknown XML.


text:
Q: Good way to count unique anonymous visitors of articles I'm building a website with articles, and I'd like to count unique-per-day visits for each article.
The idea to use cookies suggests itself, but I simply can't set a cookie for each and every article visited - ofc the user typically won't go through everything, but better to be safe. If I put all into one cookie, I'll run out of per-cookie space soon, too.
What'd be the best (most practical and lightweight) solution to this?
I have an sqlite database, so maybe some kind of persistent "session" data? That'll put extra load on the server and db, though. Ideas?

A: This is how you are tracked without cookies via the browser fingerprint.
https://panopticlick.eff.org/index.php?action=log&js=yes
Idea: Each browser has a unique fingerprint if you get enough features

*

*ip address

*installed fonts

*javascript yes/no

*adblock yes/no

*accepted headers

*is some stuff cached?

*java

*screen size

If you get 20 bits out of the browser you can distinct approximately 1,000,000 users. If you only have 100 users and some features change then they are still identifiable with a high probability.
Also you can add knowledge about the

*

*interests of people viewing a site

*how long they visit

*how many links they click (make links traceable)

to add more information.

A: If you are concerned about load you could use redis or in-memory storage, and them periodically offload the results, see:
Python example, could be adapted to php
Uses Redis bitmaps to store the counts


text:
Q: Implementing a weighted average on the fly in Python I have a stream of coming data and I want to implement the moving average on the fly. If all the elements in the moving average have the same weight it is fairly easy to implement using a 'Queue' but I want the most recent elements to have higher weights and the distribution of this weights are linear (not exponential).
For example, if the moving average is of length 5, the current value should have weight '1', the previous one should have weight '0.8' and so on until the fifth element in the queue which should have weight '0.2'; so the weight vector is: [0.2, 0.4, 0.6, 0.8, 1.0].
I was wondering if anybody knows how to implement it is Python. If there is any faster way to do this please recommend that to me; efficiency is important for my specific job.

A: If you want to keep a weighting vector such as described (linearly decreasing weights), you will need to keep all the information about your past stream. I quickly tried to sketch a mathematical function that would avoid keeping your past scalars in your memory without success. This is where the exponential weighting has a powerful advantage:
average_(t) = x_(t) + aa*average_(t-1)

You only need to keep two variables in your memory.
Anyway, if the memory is not an efficiency parameter, your problem goes down as a vector multiplication. Therefore, I would suggest using the numpy library. [1] [2]. See a solution example below (perhaps you may found a more efficient one):
import numpy as np

stream = np.array((20, 40))
n = len(stream)

latest_scalar = 60
stream = np.append(stream, latest_scalar)

n += 1
# n represent the length of the stream
# I assumed that is more efficient to handle n without calling len() function
# may raise safety issue
weights = np.arange(1, n+1)
# [1, 2, 3]
average = np.dot(stream, weights).sum() / (n*(n+1)/2)
# (n*(n+1)/2): total of the weights
# output: 46.666... ok!


text:
Q: NSPredicate predicateWithFormat not evaluating format specifier I have a (to me) curious case with NSPredicate's predicateWithFormat: method.
Using the following I log the description of two NSPredicate instances to the console:
NSNumber *myNumber = [NSNumber numberWithInt:1];

NSString *predicateFormatByHand = [NSString stringWithFormat:@"self MATCHES 'chp%@_img[0-9]+\\.png'", myNumber];
NSPredicate *firstPredicate = [NSPredicate predicateWithFormat:predicateFormatByHand];

NSLog(@"firstPredicate description: %@", firstPredicate);

NSPredicate *secondPredicate = [NSPredicate predicateWithFormat:@"self MATCHES 'chp%@_img[0-9]+\\.png'", myNumber];

NSLog(@"secondPredicate description: %@", secondPredicate);

This outputs:
 firstPredicate description: SELF MATCHES "chp1_img[0-9]+.png"
secondPredicate description: SELF MATCHES "chp%@_img[0-9]+.png"

I would expect these descriptions to be the same.
Can someone explain why they are not?
(Following this question I've played with various escape sequences for the embedded single-quotes but when doing so keep having NSPredicate complain that it cannot then parse the format string. I'd be grateful to know what's going on.)
UPDATE: one answer suggested it's an issue with using NSNumber rather than an int, so:
NSPredicate *thirdPredicate = [NSPredicate predicateWithFormat:@"self MATCHES 'chp%d_img[0-9]+\\.png'", [myNumber intValue]];

NSLog(@"thirdPredicate description: %@", thirdPredicate);

I began with this originally, but alas the output is the same:
thirdPredicate description: SELF MATCHES "chp%d_img[0-9]+.png"

(Something means the format specifier is not evaluated.)

A: The answer is simple: the parser used by NSPredicate assumes that anything inside the quote marks is a string literal, and does not attempt to do any substitutions on its contents. It you need to have a dynamic string value, you will have to build the string before substituting it into the predicate format string, as in your first example.

A: ...because the predicate is not such thing than string.
for any of the predicates you should use two format specifier 100% safety only:

*

*one for the key (%K); and

*one for the value (%@);

you cannot format neither the key nor the value when you add them to the predicate. this is why your second (and third) predicates are not formatted inside the value.
you can format the value before you add it to the predicate like:
NSNumber *myNumber = [NSNumber numberWithInt:1];
NSString *string = [NSString stringWithFormat:@"chp%@_img[0-9]+\\.png", myNumber];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", string];
NSLog(@"%@", predicate);

the result is:
SELF MATCHES "chp1_img[0-9]+\\.png"

...and never forget my first sentence: the predicates and the strings are not the same thing.

A: My interpretation of

%@ is a var arg substitution for an object value

in the "Predicate Programming Guide" is that %@ can only be used for substituting a value that a Core Data object can be compared against. For example
NSNumber *myNumber = [NSNumber numberWithInt:1];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"count = %@", myNumber];

is perfectly valid if "count" is a Number attribute of the entity. It is similar to binding values to SQLite prepared statements.
If %@ could be used for general string formatting in predicates, then there would be no need to have two different format specifiers %K  and %@ for key paths and values.


text:
Q: matplotlib.pyplot.scatter() loses color when importing seaborn package? I am working on generating some scatter plot with matplotlib.pyplot.scatter() in jupyter notebook, and I found that if I import seaborn package, the scatter plot will lose its color.  I am wondering if anyone has a similar issue?
Here is an example code
import matplotlib.pyplot as plt
import seaborn as sb

plt.scatter(range(4),range(4), c=range(4))

The output is

The scatter plot without seaborn is:

A: That seems to be the way it behaves. In seaborn 0.3 the default color scale was changed to greyscale. If you change your code to:
plt.scatter(range(4),range(4), c=sb.color_palette())
You will get an image with colors similar to your original.
See the Seaborn docs on choosing color palettes for more info.

A: Another way to fix this is to specify cmap option for plt.scatter() so that it would not be affected by seaborn:
ax = plt.scatter(range(4),range(4), c=range(4), cmap='gist_rainbow')
plt.colorbar(ax)

The result is:

There are many options for cmap here:
http://matplotlib.org/examples/color/colormaps_reference.html


text:
Q: C++/CLI circular reference issue with CLI Classes I am having an issue with two classes that reference each other. I have attempted to use an interface to resolve the issue, but run into other problems such as class re-definition. I am just not sure how to do this properly.
here is an example of what I have going on. Note: I have taken out all the extra properties and methods that are not actually affecting this issue.  How can I redo these without causing class re-definitions and without the circular reference. If you can, please use this example as a template for a correct layout of the statements.
// componentClass.h
//#include "controlClass.h" - Would cause a circular reference
namespace test
{
    //component class
    public ref class componentClass sealed : Component
    {
    internal:
        componentClass(controlClass ^control);
    private:
        controlClass ^_control;
    };
}

// controlClass.h
#include "componentClass.h";
namespace test
{
    //control class
    public ref class controlClass: Control
    {
    public:
        controlClass();
    private:
        componentClass ^_componentClass;
    };
}

// controlClass.cpp
#include "controlClass.h"
controlClass::controlClass()
{
    _componentClass = gcnew componentClass(this);
}

// componentClass.cpp
#include "componentClass.h"
componentClass::componentClass(controlClass ^control)
{
    _control = control;
}

A: Generally the easiest way to resolve this issue is to put both class declarations inside of one header file, and forward-declare the second one.  For example:
namespace test
{
    // Forward declaration of controlClass
    ref class controlClass;

    //component class
    public ref class componentClass sealed : Component
    {
    internal:
        componentClass(controlClass ^control);
    private:
        controlClass ^_control;
    };

    //control class
    public ref class controlClass: Control
    {
    public:
        controlClass();
    private:
        componentClass ^_componentClass;
    };
}

It's possible to accomplish this with multiple header files, but there are caveats and complexities that are eliminated by using a single header file.
You can continue to provide the implementation of each class in a different source file without problems.


text:
Q: Properly validate UTF-8 characters for insertion in a table with utf8_general_ci colocation While the real problem is the colocation of the field on the database, i can't change it. I need to drop invalid characters instead.
Using @iconv('utf-8', 'utf-8//IGNORE'); won't work, because the characters are valid UTF8 characters, but invalid when inserted in a field with that colocation.
$broken_example = '↺ﺆী▜Ꮛ︷ሚ◶ヲɸʩ𝑸ᚙ𐤄🃟ʳ⸘ᥦฆⵞ䷿ꘚꕛ𝆖𝇑𝆺𝅥𝅮↺ﺆী▜Ꮛ︷ሚ◶ヲɸʩ𝑸ᚙ𐤄🃟ʳ⸘ᥦฆⵞ䷿ꘚꕛ𝆖𝇑𝆺𝅥𝅮';
$utf8 = html_entity_decode($broken_example, ENT_QUOTES, 'UTF-8');

I've tried to use some workaround like preg_replace('/&#([0-9]{6,});/', '');, but with no success.
The error mysql is reporting is Incorrect string value: '\xF0\x90\xA4\x84\xCA\xB3...'

A: A regex for validating all utf-8 chars is:
function removeInvalidChars ($text) {
    $regex = '/( [\x00-\x7F] | [\xC0-\xDF][\x80-\xBF] | [\xE0-\xEF][\x80-\xBF]{2} | [\xF0-\xF7][\x80-\xBF]{3} ) | ./x';
    return preg_replace($regex, '$1', $text);
}

Removing the match for 4-byte chars will allow only the characters that can be stored in utf8_general.
function removeInvalidChars ($text) {
    $regex = '/( [\x00-\x7F] | [\xC0-\xDF][\x80-\xBF] | [\xE0-\xEF][\x80-\xBF]{2}) | ./x';
    return preg_replace($regex, '$1', $text);
}

btw it's the character set that matters not the collation. Also you would be much better off just switching to utf8mb4 with utf8mb4_unicode_ci rather than putting a hack like this in.


text:
Q: JavaFX Wait for a click wherever on a screen I have two buttons: buttonPoint1 and buttonPoint2. When I click one of the buttons it calls action method for this button. In this function I want program to wait for me to click wherever on a screen. Then I'll call MouseInfo.getPointerInfo().getLocation(). When I click outside my app window (e.g on other window), I lose focus on my app. How to make program to wait for click, don't hide, lose focus and give me response that I clicked?

A: One idea is using a transparent window like so
public class Main extends Application {
    @Override
    public void start(Stage primaryStage) {
        VBox vBox = new VBox(new Label("IMAGINE A BEAUTIFUL APPLICATION HERE"));
        vBox.setAlignment(Pos.CENTER);

        Button button = new Button("Im gonna steal your next click");
        button.setOnAction(event -> {
            System.out.println("Firing Button Action");
            openTransparentWindow();
            System.out.println("Button Action Finished Firing");
        });

        vBox.getChildren().add(button);

        Scene scene = new Scene(vBox, 300, 150);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void openTransparentWindow(){
        VBox vBox = new VBox();

        Stage stage = new Stage();
        stage.setScene(new Scene(vBox));
        //stage.setOpacity(0.5f); //Uncomment if you want to test and see the stage
        stage.setOpacity(0f);
        stage.setMaximized(true);

        vBox.setOnMouseClicked(event ->{
            System.out.println("event.getX() = " + event.getX());
            System.out.println("event.getY() = " + event.getY());
            System.out.println("event.getScreenX() = " + event.getScreenX());
            System.out.println("event.getScreenY() = " + event.getScreenY());
            stage.close();
        });

        stage.showAndWait();
    }
}


text:
Q: Enabling System.Net.Http within VS 2012 Project I'm fairly new to JSON development and just getting started is a major task with very little in the way of solutions via Google.
I can't get anywhere without adding system.net.http as part of my project
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Net.Http;

objects like var, HttpWebClient, KeyValuePair throw up an error during compile. Here's what I tried:

*

*Reinstalled .NET 4.0

*Reinstalled .NET 4.5

*Repackaged library via. NuGet

*Referenced system.net

No luck. I've even tried referencing the the class in web.config
<compilation targetFramework="4.5">
  <assemblies>
    <add assembly="System.Net.Http, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
  </assemblies>
</compilation>

and again in..
<runtime>
  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <dependentAssembly>
      <assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" />
      <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
    </dependentAssembly>
  </assemblyBinding>
</runtime>

An error is thrown on "assemblies"
I'm at my wits end. What am I not referencing or doing wrong where System.Net.Http cannot be used.

A: In .NET 4.5 System.Net.Http is in it's own assembly, you have to go to "Add References" (right click on the project) and select it.
See the MSDN page for HttpClient: http://msdn.microsoft.com/en-us/library/system.net.http.httpclient.aspx

Assembly:  System.Net.Http (in System.Net.Http.dll)

A: The help system reveals that the System.Net.Http namespace is defined in System.Net.Http.dll which as you say is not listed. A quick search of my own filesystem reveals copies

*

*In the GAC

*In the framework folders for both 32 and 64 bit

On my system those paths are
 C:\Windows\Microsoft.NET\Framework\v4.0.30319
 C:\Windows\Microsoft.NET\Framework64\v4.0.30319

System.Net.Http.WebRequest.dll is on the same paths.

A: Did you try
using System.Net.Http;

C# is a case-sensitive language.


text:
Q: SICStus Prolog 4.3.2: clpfd got no power? Some of my Prolog programs could profit quite a bit if I could replace all (is)/2-based integer arithmetics by their clpfd counterpart.
So I want the power ... with clpfd ... so I can replace X is 10^3 with something clpfd-y :)
Consider the following five Prolog processors supporting clpfd:

*

*GNU Prolog 1.4.4

?- X #= 10^3.
uncaught exception: error(type_error(fd_evaluable,(^)/2),(#=)/2)

?- X #= 10**3.
X = 1000.

*SWI-Prolog 7.3.14

?- use_module(library(clpfd)).  % autoload would be even more awesome
true.

?- X #= 10^3.
X = 1000.

?- X #= 10**3.
ERROR: Domain error: `clpfd_expression' expected, found `10**3'

*B-Prolog 8.1

?- X #= 10^3.
X #= 10^3.
*** error(illegal_array_access,10^3)

?- X #= 10**3.
X = 1000.

*SICStus Prolog 4.3.2

?- use_module(library(clpfd)).
true.

?- X #= 10^3.
! Existence error in (^)/2
! constraint user:wi(^)/2 does not exist
! goal:  10^3

?- X #= 10**3.
! Existence error in user:(**)/2
! constraint user:(**)/2 does not exist
! goal:  10**3

Ideas / hints / advice, please.
What can I do? Use some clpfd compatibility layer(s), perhaps?
Thank you in advance!

A: Quick hack to the rescue?
Warning: massive overkill ahead, but... does it even work? And is it portable?
Let's check it out!

*

*SWI-Prolog 7.3.14

*

*using clpq

?- use_module(library(clpq)).
true.

?- clpq:{X = 10^3}, integer(X).
X = 1000.                          % <== SUCCESS!

*using clpr

?- use_module(library(clpr)).
true.

?- clpr:{X = 10^3}, integer(X).
false.

*SICStus Prolog 4.3.2

*

*using clpq

?- use_module(library(clpq)).
true.

?- clpq:{X = 10^3}, integer(X).
false.

*using clpr

?- use_module(library(clpr)).
true.

?- clpr:{X = 10^3}, integer(X).
false.

1X success, 3X failure... Works, well, kind of... Then again, I guess it ain't it.

A: You can use for constant expressions:
?- X is 10^3.
X = 1000.

Which should work in a ISO compliant prolog thanks to corr2.
It will also propagate inside CLP(FD) as if it were X #= 10^3:
?- Y #= X+1, X is 10^3.
Y = 1001
X = 1000


text:
Q: How to set different localized string in different visual states in WP7 using Blend? How do I set different localized strings in different visual states in WP7 using Blend without any code behind?
I can set different non-localized strings in different visual states (although it flickers).  That works, but how about localized strings?
If I change the string using data binding in Blend, Blend just overrides the data binding in Base state and not the actual state where I'm recording.
EDIT:
This is how I localize my strings:
I have a resources file named AppPresources.resx. Then I would do this in code:
    // setting localized button title
    mainButton.Content = AppResources.MainButtonText;

Then I have a GlobalViewModelLocator from MVVM Light Toolkit with the following Property for Databinding.
    private static AppResources _localizedStrings;
    public AppResources LocalizedStrings
    {
        get
        {
            if (_localizedStrings == null)
            {
                _localizedStrings = new AppResources();
            }
            return _localizedStrings;
        }
    }

And in xaml file:
<Button x:Name="mainButton" Content="{Binding LocalizedStrings.MainButtonText, Mode=OneWay, Source={StaticResource Locator}}" ... />

A: What you need to do, is very close to what you're already doing. First, define a class named Resources.cs with following content
public class Resources
{
    private static AppResources resources = new AppResources();

    public AppResources LocalizedStrings
    {
        get
        {
            return resources;
        }
    }
}

This allows us to create a instance of your Resource File in XAML. To do this, open App.xaml and add following
<Application.Resources>
    <local:Resources x:Key="Resources" />
</Application.Resources>

Now when you need to do bindings in your XAML, you do it like this:
<Button Content="{Binding LocalizedStrings.MainButtonText,
                          Source={StaticResource Resources}}" />

What you'll notice is that it doesn't work in Blend, yet. To make it work in Expression Blend,
add the following file: DesignTimeResources.xaml in the Properties Folder, and add following content
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:YourNameSpace">
    <local:Resources x:Key="Resources" />
</ResourceDictionary>

Now, you press F6 in Visual Studio to recompile, and voila, your localized strings are available in Expression Blend!
A real-world example from one of my projects:

*

*AppResources.cs

*DesignTimeResources.xaml

*App.xaml


text:
Q: Is there a way to use weakly informative default prior distributions for multinominal regression models? Following Gelman et al. 2008, we can use e.g. in the case of complete separation, weakly informative prior distributions to estimate a bayesian logistic regression.
However I wonder, whether there is a way to do something similar for a multinominal regression (I have 3 outcomes). It would be awesome if there is something implemented for stata or r.
Thanks in advance.

A: So far, only efficient samplers with normal priors (with large variances in the case of weak information) have been developed.
The relevant reference is:

Polson, Nicholas G., James G. Scott, and Jesse Windle. "Bayesian inference for logistic models using Pólya–Gamma latent variables." Journal of the American statistical Association 108.504 (2013): 1339-1349.

This methodology is implemented in the R package BayesLogit.


text:
Q: How do I use a function to calculate an object's properties in JavaScript? I have an object with property values designating the hours and minutes of a time in military time. I'm trying to have another property that uses a function outside the object to calculate the the time to twelve hour time and hold those values as additional properties.
I have the following code:
$(function () {
    console.log( startTime.twelveHourTime );
});

var startTime = {
    militaryTime: {
        hours: 23,
        minutes: 30
    },
    twelveHourTime: convertToTwelveHourTime (this.militaryTime)
    /* I would like this to result in
    twelveHourTime: {
        hours: 11,
        minutes: 30,
        amOrpm: 'PM'
    }*/
};

function convertToTwelveHourTime (militaryTime) {

    var twelveHourTime = {
        hours: 0,
        minutes: 0,
        amOrpm: ''
    };

    if(militaryTime.hours > 12){
        twelveHourTime.hours = militaryTime.hours - 12;
    }else{
        twelveHourTime.hours = militaryTime.hours;
    }

    twelveHourTime.minutes = militaryTime.minutes;

    if(militaryTime.hours > 11){
        twelveHourTime.amOrpm = 'PM';
    }else{
        twelveHourTime.amOrpm = 'AM';
    }

    return twelveHourTime;
}

Running this code results in the following errors in the console:
Uncaught TypeError: Cannot read property 'hours' of undefined

referring to the line if(militaryTime.hours > 12).
and
Uncaught TypeError: Cannot read property 'twelveHourTime' of undefined

referring to the initial console.log.
Why is this occurring and how can I fix this code?


text:
Q: How to use errors codes stored in the separate module In the errors.py module I have defined several errors such as:
INCORRECT_USERNAME = -2417
INCORRECT_PASSWORD = -2426
PASSWORD_EXPIRED = -2430
ACCOUNT_DISABLED = -2431

Now, I import this module into another Python script and check if the error code matches:
import errors

def get_error_name():
    returned_code = some_function(some_argument)

    if returned_code == errors.INCORRECT_USERNAME:
        return "INCORRECT_USERNAME"
    elif returned_code == errors.INCORRECT_PASSWORD:
        return "INCORRECT_PASSWORD"
    elif returned_code == errors.PASSWORD_EXPIRED:
        return "PASSWORD_EXPIRED"
    elif returned_code == errors.ACCOUNT_DISABLED:
        return "ACCOUNT_DISABLED"

The resulting code appears to be too redundant or verbal.
Is there a cleaner way to return the string value of the error message?

A: This seems like a good use case for Enum:
# errors.py
import enum

class Error(enum.IntEnum):
    INCORRECT_USERNAME = -2417
    INCORRECT_PASSWORD = -2426
    PASSWORD_EXPIRED   = -2430
    ACCOUNT_DISABLED   = -2431

# another_script.py
import errors

def get_error_name():
    returned_code = some_function(some_argument)
    return errors.Error(returned_code).name

Alternatively, if you ever want to return something that isn't just the name of the error, you might consider using a namedtuple:
# errors.py
import collections

Error = collections.namedtuple('Error', ['name', 'msg'])
all_errors = {
    -2417: Error('INCORRECT_USERNAME', 'The provided username was incorrect'),
    -2426: Error('INCORRECT_PASSWORD', 'The provided password was incorrect'),
    -2430: Error('PASSWORD_EXPIRED',   'Your password has expired'),
    -2431: Error('ACCOUNT_DISABLED',   'Your account is disabled'),
}

# another_script.py
import errors

def get_error_name():
    returned_code = some_function(some_argument)
    return errors.all_errors[returned_code].name

def get_error_msg():
    returned_code = some_function(some_argument)
    return errors.all_errors[returned_code].msg

A: You can use a dictionary to do this:
errors.py
error_dict = {
    -2417: "INCORRECT_USERNAME",
    -2427: "INCORRECT_PASSWORD",
    -2430: "PASSWORD_EXPIRED",
    -2431: "ACCOUNT_DISABLED"
}

from errors import error_dict

def get_error_name():
    returned_code = some_function(some_argument)

    # use this syntax instead of errors.error_dict[returned_code] to handle
    # invalid return code. could use a try / except KeyError also
    return error_dict.get(returned_code, "INVALID_CODE")

A: Your best choice would be to use a dictionary, which is the best equivalent of a switch...case statement in other languages like C or C++:
def error_handler(error_code: int) -> str:
    return {
        -2417: 'INCORRECT_USERNAME',
        -2426: 'INCORRECT_PASSWORD',
        -2430: 'PASSWORD_EXPIRED',
        -2431: 'ACCOUNT_DISABLED',
    }.get(error_code, 'DEFAULT_ERROR_MESSAGE')


text:
Q: Case Insensitive search in containment filter I need to perform Case Insensitive search in containment filter instead of using the exact case sensitve matching.
def filter(request, fname, fvalue):

    list = HmsPatient.objects.filter(**{fname:fvalue})
    c = {'list' : list}
    return render_to_response('patient/list.html', c, context_instance=RequestContext(request))

def search(request):
    if request.method == 'POST':
        fname = request.POST.get('filter_name')
    fvalue = request.POST.get('filter_value')
        return filter(request, fname, fvalue);
    else:
        action = HmsPatient().get_search_url()
        form = HmsPatientForm()
        c = {'form': form, 'action' : action}
        c.update(csrf(request))
        return render_to_response('search.html', c, context_instance=RequestContext(request))

A: Django allows you to do a case insensitive match using iexact. For example:
Blog.objects.get(name__iexact="beatles blog")

In your case, because fname is a variable, you have to append __iexact to the key in your dictionary.
key = fname + '__iexact'
list = HmsPatient.objects.filter(**{key: fvalue})

Django also supports contains and icontains, which you can use in the same way.

A: use Double quotes n "icontains" for case insensitive search.
def filter(request, fname, fvalue):

    key = fname + '__icontains'
    list = HmsPatient.objects.filter(**{key: fvalue})
    c = {'list' : list}
    return render_to_response('patient/list.html', c, context_instance=RequestContext(request))

use Double quotes n "contains" for case Sensitive search.
def filter(request, fname, fvalue):
    key = fname + '__contains'
    list = HmsPatient.objects.filter(**{key: fvalue})
    c = {'list' : list}
    return render_to_response('patient/list.html', c, context_instance=RequestContext(request))

in MySQL chosing a collation makes the data values case sensitive, if u dont choose any collation your database will be case insensitive, i.e AbC =abc


text:
Q: How to type check component children with Preact and TypeScript? Is it possible to type check a components children with TypeScript (v3.0.1) and Preact (v8.3.1)? In React there is a ReactElement<T> for that. Is there something similar in Preact?
I have a menu component, which can only have menuItem child components. How can I enforce that in Preact with TypeScript? With React I could do something like:
interface Props {
    children?: React.ReactElement<MenuItem>[] | React.ReactElement<MenuItem>;
}

I know that that ReactElement is implemented in preact-compat, but I don't want to use it.
Thank you for any advice!

A: Now the simplest option is probably the ComponentChildren type (see this commit: https://github.com/preactjs/preact/commit/cd422d047f6d21607ff980c84b9c4ac1845ca798). For example:
import { h } from "preact";

import type { ComponentChildren } from "preact";

type Props = {
  children: ComponentChildren;
}

export function ComponentWithChildren(props: Props) {
  return (
    <div>
      {props.children}
    </div>
  );
}

A: Preact's equivalent of ReactElement is called VNode (Virtual DOM Node). I'm by no means a TypeScript expert, but I believe your example could work as follows:
interface Props {
    children?: VNode<MenuItem>[] | VNode<MenuItem>;
}

Prior to Preact 8.3.0 I think we relied on JSX.Element instead of VNode.


text:
Q: Searching Query in codeigniter with timestamp format how do i compare date and time in codeigniter query where the database cell format is timestamp. i need to search data between date and between time. but date and time in my database in timestamp format. i have 4 inputs with datepicker and timepicker. datepicker format like "2017-06-06", and timepicker format like "16:00:00".  my database timestamp format looks like "2017-06-06 16:35:00.256". how do i compare my date and times with timestamp? big thanks for your help. sorry for my bad english.

A:   $start_date = date('Y-m-d'); //lets date this was your date

    //it would be something like below
    $query = $this->db->query(
        "SELECT FROM tbl_event WHERE event_startdate <= '{$start_date}'
        AND event_enddate >= '{$end_date}'");


text:
Q: How can i show tabs on frontend on custom product list page? I want to show these tabs on front end in custom product list page. On the click of these tabs the related content will show.

A:
Try this code

        White

white content

        Gold

Gold content

        Silver

Silver Content

you can call multiple phtml files into this content of  like this

        Custom title

        <?php
            echo $this->getLayout()->createBlock("VendoreName\ModuleName\Block\CustomerBlockName")->setTemplate("VendoreName_ModuleName::customtab.phtml")->toHtml();
        ?>

you can add multiple tab and also add your class name to apply your custom css.

Tab Source link
Call phtml file link
I Hope This Helps You.

A: I add this tabs by adding this code

Tab01

Tab02

Tab03

Tab 01 Neque ipsum dolor.

Consectetur adipisicing elit. Neque, repellat facilis totam ab eos distinctio sint atque maiores! Dignissimos, molestiae, rem accusantium iure vitae voluptatum voluptas repudiandae deserunt dolore quis! Quisquam mollitia eius sed.

Tab02 Maiores, suscipit

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Maiores, suscipit, eaque asperiores neque numquam nam possimus dolorem ipsa aspernatur reiciendis?

Tab03

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quaerat, excepturi, minima, corporis deserunt quia quae sit officiis labore inventore autem a delectus consequuntur voluptatem modi eligendi similique sed nam vitae.

And for slide up/down content i added jquery
require(['jquery'], function($){
'use strict';

$(document).ready(function() {

    (function ($) {
      $('.tab ul.tabs').addClass('active').find('> li:eq(0)').addClass('current');

        $('.tab ul.tabs li a').click(function (g) {
          var tab = $(this).closest('.tab'),
            index = $(this).closest('li').index();

          tab.find('ul.tabs > li').removeClass('current');
          $(this).closest('li').addClass('current');

          tab.find('.tab_content').find('div.tabs_item').not('div.tabs_item:eq(' + index + ')').slideUp();
          tab.find('.tab_content').find('div.tabs_item:eq(' + index + ')').slideDown();

          g.preventDefault();
        } );
    })(jQuery);
});

});


text: Q: Git Bash Slow Over Network Drive I'm having issues with Git Bash running slowly over a network drive. Something as simple as cd takes several seconds, moving forwards or backwards in Vim has a few seconds of latency, etc. This does not happen when I'm using git bash on a local drive. I also do not have this issue when using Windows' built in Command Prompt on either local or network drives. Any ideas on how to fix the latency issues?


text:
Q: Big-Omega proof using L'Hopital's Rule? Prove or disprove: $15n^2$ is in $\Omega(3 \times 2^n)$
So we'd have to prove or disprove this statement:
$$
\exists c \in\mathbb{R}^+,\,\exists B\in\mathbb{N}, \forall n \in\mathbb{N}, n ≥ B \Rightarrow 15n^2 \geq c(3 \times 2^n)
$$
There are other approaches to this but I'm interested in knowing how to prove it using L'Hopital's Rule and what steps to take.

A: To prove $15n^{2} \in \Omega(3 * 2^{n})$, we consider $L = \lim_{n \to \infty} \frac{15n^{2}}{3 * 2^{n}}$.
If $L = 0$, then we conclude $15n^{2} \in \omega(3 * 2^{n})$. Little-omega is a strict inequality, and so it implies Big-Omega.
Applying L'Hospital's rule, we get:
$$L = \lim_{n \to \infty} \frac{30}{3 * (ln(2))^{2} * 2^{n}} = 0$$
I applied L'Hospital's rule twice, differentiating the numerator and the denominator twice.


text:
Q: object oriented PHP and database wrappers I'm writing a small class for a booking system in PHP.
By my own admission OOP is not my thing at all - but I'd like to use it for this project, assuming I can glean enough of an understanding to use it properly.
Here's some of what I have so far (mostly pseudo):
class bookingSystemDbWrapper
{
    public $db;
    function __construct()
    {
        $this->db = mysqli_connect(..., ..., ..., ...);
    }
}

class bookingSystemAvailabilityManager extends bookingSystemDbWrapper
{
    function checkAvailability($date, $roomID)
    {
        /**
         * check availability for a given room on a given date
         */

        $query = mysqli_real_escape_string("SELECT SOMETHING FROM SOMEWHERE");
        $result = mysqli_query($this->db, $query);
        return $result;
    }
}

This approach works fine for the small and simple classes above. But when I need a class for creating a booking, searching based on location, etc, it seems like a bad idea to be extending the database wrapper for every class. So I need another way to make my database wrapper class available to my other classes, so they can run database queries.
I've read up on dependency injection on nettuts here: http://net.tutsplus.com/tutorials/php/dependency-injection-huh/ but it's a bit beyond my limited understanding of OOP, so I'm unsure of what approach to take, or how to implement it correctly.
TL;DR
How should I make one classes' public vars available to other classes without breaking any principles of OOP, and keep my code readable?

A: I suggest a static class, like this:
<?php
class dbms
    {
        const HOST     = 'localhost';
        const LOGIN    = 'login';
        const PASSWORD = 'myB!GevU1PwD';
        const SCHEMA   = 'mydb';
        const CHARSET  = 'utf8';
        const PORT     = 3306;

        protected static $instance;

        public static function connect()
            {
                if(is_object(static::$instance) && (static::$instance instanceof mysqli))
                    { return static::$instance->ping(); }

                static::$instance = new mysqli(static::HOST, static::LOGIN, static::PASSWORD, static::SCHEMA, static::PORT);

                if(static::$instance->connect_errno)return false;

                static::set_charset(static::CHARSET);
            }

        public static function disconnect()
            {
                static::$instance->close();

                static::$instance = null;
            }

        public static function &getInstance(){ return static::$instance; }
    }
?>

Should be easy-extendable, and seen everywhere you need:

*

*There is only one shared connection for static instance;

*It might be easy repurposed via extend without loosing performance;

*It accessible from everywhere you need, as it's a static class.


text:
Q: preg_replace appending character to match I'm looking for a way to convert a numeric into a string that could be used to represent a version.
Let's say we have
$foo = 123

I'd like to be able to convert this into $foo = "1.2.3"
So far I've tried
$foo = 123;
$string = preg_replace("[^0-9]",'$0\.',$foo);

But that doesn't seem do do anything at all, $string just comes back as empty/null.
What am I doing wrong?

A: You can do this, (documentation):
$string = wordwrap($foo, 1, '.', true);

A: Simply use str_split(), followed by join():
join('.', str_split($foo));

A: You said that it's already numeric.
$foo = 123;
echo implode('.', str_split($foo));

A: ^ means NOT ie [^0-9] means anything thats not in 0123456789
You also need to delimit your search using / (other characters are available)
This allows you to use modifiers (you can look that up)
You dont need to escape the replace characters either as its not a REGEX pattern
$foo = 123;
$string = preg_replace("/[0-9]/",'$0.',$foo);

Have you looked at the examples of preg_replace() in the php manual?
http://php.net/manual/en/function.preg-replace.php


text:
Q: Multi Class Random Forest If a decision tree splits into 2 classes, how is random forest able to create multiple buckets in classification?
Can you post any link about this theory?
What is the theory behind it?

A: A junction in a decision tree doesn't split in two classes. It splits in two subtrees. The outcome of a decision tree is determined by following junctions until you arrive in a leaf node. A simple 2 level tree with 3 binary junctions
has 4 leaves
    J
   / \
  J   J
 / \ / \
L  L L  L

With 4 leafs, you can have up to 4 classes, but in general many leaf nodes will belong to the same class.
Of course, with a forest, each tree has many leafs and there are many leafs in the forest, so there are man many leafs across the whole forest.
You can even look at the number of decision trees to decide how reliable an outcome is. If your forest has 100 trees and 3 classes, one input may result in a 90-6-4 distribution and another input may give a 50-30-20 outcome. Both inputs are apparently class 1, but the second input is less certainly so.


text:
Q: Replicate C# Math.IEEERemainder in Lua? I am trying to replicate the behavior of Math.IEEERemainder (in C#) in Lua. I know that I can always write the entire thing from scratch, but I am trying to avoid it if there is something built-in.
I have tried the % operator and math.fmod. None of them behave the same.
For instance:
Math.IEEERemainder(3.0,2.0) //-1
(3.0%2.0) --1
math.fmod(3.0,2.0) --1

A: function IEEERemainder(x, y)
   y = y + 0.0
   local q1 = math.floor(x/y)
   local q2 = math.ceil(x/y)
   local r1 = x - y * q1
   local r2 = x - y * q2
   local d1 = math.abs(r1)
   local d2 = math.abs(r2)
   local r = (d1 < d2 or d1 == d2 and q1 % 2 == 0) and r1 or r2
   return r == 0 and x < 0 and -r or r
end


text:
Q: dynamically change visibility of markers I'm using angular 1.2.15 and angular-google-maps 1.0.18 to display several dozen markers.  What I want to do is independently turn on/off the visibility of groups of markers (as designated by class name) dynamically.  I'm able to use the angular-google-maps directive to render the map and all of the markers.  I just don't know how to dynamically change marker visibility with angular-google-maps.  Any help would be greatly appreciated.
HTML:
<google-map center="map.center" zoom="map.zoom" draggable="true">
  <markers ng-repeat="blotter in blotters" class="{{blotter.name}}" models="blotter.stories" options="{visible:true}" coords="'self'" doCluster="true">
  </markers>
</google-map>

Controller:
$scope.map = {
  center: {latitude: 39.111, longitude: -119.89},
  zoom: 10
};

$scope.blotters= [{ 'stories': [], 'title': 'Local News', 'name': 'local_news', 'id': 1, 'filterString': filterString1},
        { 'stories': [], 'title': 'Sports', 'name': 'sports', 'id': 2,  'filterString': filterString2},
        { 'stories': [], 'title': 'Local Government','name': 'local_government', 'id': 3, 'filterString': filterString3}];

And in another function (not shown here) I load each blotter's stories.  Each of those stories has a latitude and longitude attribute.

A: I was able to implement this by switching from angular-google-maps to angularjs-google-maps.  Then, I implemented markers using the standard Google maps api to add a marker object to each story in the scope.  See here for an example.