text:
Q: How to annotate boxplots using svyboxplot library in R I am trying to figure out how to label the boxplots that appear after I use the svyboxplot library for R.
I have tried the following:
svyboxplot(~ALCANYNO~factor(REGION), design=ihisDesign3, xlab='Region', ylab='Frequency', ylim=c(0,10), colnames=c("Northeast", "Midwest", "South", "West"));

SOLUTION: Add the following to factor:
labels = c('Northeast', 'Midwest', 'South', 'West')

This changes the example above to the following:
svyboxplot(~ALCANYNO~factor(REGION,
           labels=c('Northeast', 'Midwest', 'South', 'West')),
           design=ihisDesign3, xlab='Region', ylab='Frequency',
           ylim =c (0, 10))

A: I am Creating a dataset to explain:
options(width = 120)
library (survey)
library (KernSmooth)

xd1<-
"xsmoke age_p psu stratum       wt8
13601       3    22   2      20  356.5600
32966       3    38   2      45  434.3562
63493       1    32   1      87  699.9987
238175      3    46   1     338  982.8075
174162      3    40   1     240  273.6313
220206      3    33   2     308 1477.1688
118133      3    68   1     159  716.3012
142859      2    23   1     194 1100.9475
115253      2    35   2     155  444.3750
61675       3    31   1      85  769.5963
189813      3    37   1     263  328.5600
226274      1    47   2     318  605.8700
41969       3    71   2      58  597.0150
167667      3    40   2     230 1030.4637
225103      3    37   2     316  349.6825
49894       3    70   2      68  517.7862
98075       3    46   2     130 1428.7225
180771      3    50   1     250  652.4188
137057      3    42   1     186  590.2100
77705       2    23   1     105 1687.2450
89106       3    48   1     118  407.6513
208178      3    50   1     290  556.5000
100403      3    52   2     133 1481.8200
221571      1    27   2     310  833.5338
10823       2    72   1      16 1807.6425
108431      3    71   2     145  945.6263
68708       1    46   1      94 1989.3775
23874       3    23   2      33 1707.8775
150634      3    19   2     206  761.1500
231232      3    42   2     326 1487.4113
184654      2    42   2     255 1715.2375
215312      3    57   1     300  483.5663
40713       2    57   2      56 2042.2762
130309      3    23   1     177  948.5625
25515       2    55   1      35 2719.7525
235612      2    83   2     333  603.3537
13755       2    36   2      20  265.1938
2441        3    33   1       4 1062.1200
157327      3    77   1     215 2010.6600
66502       3    20   2      91 1122.9725
230778      1    55   2     325 1207.3025
74805       3    54   1     101 1028.5150
166556      1    50   1     229 1546.9450
91914       1    68   1     121  428.5350
89651       3    59   2     118  143.5437
149329      3    44   2     204 1064.7725
212700      2    59   2     295 1050.1163
454         1    79   1       1  275.5700
125639      1    27   1     170  785.1037
55442       3    47   1      76  950.3312
145132      3    77   1     197 1269.2287
123069      3    24   1     167  216.1937
188301      1    55   2     260  426.6313
852         2    66   2       1 1443.4887
3582        3    81   1       6  790.8412
235423      1    44   2     333  659.4238
42175       2    40   1      59 1089.6762
57033       3    43   1      78  226.8750
177273      2    85   1     244  392.7200
218558      3    40   2     305 1680.2700
27784       2    45   1      39  280.0550
81823       3    43   1     110  965.0438
76344       3    26   1     103 1095.6012
114916      3    56   2     154  436.8838
35563       3    78   1      49  333.2875
192279      3    30   2     267  722.0312
61315       1    48   2      84 1426.5725
219903      3    43   1     308  791.5738
42612       3    25   1      60  658.1387
178488      3    33   2     246  675.1912
9031        1    27   2      14  989.4863
145092      2    64   1     197  960.1912
71885       3    53   2      97  595.4050
38137       2    75   1      53 1004.0912
140149      1    21   1     190 1870.9350
162052      3    25   1     223  892.7775
89527       2    39   2     118  518.1050
59650       3    26   2      82  432.7837
24709       2    84   1      34  453.9013
18933       3    85   1      27  582.3288
24904       3    35   2      34 1027.5287
213668      3    39   1     298 3174.1925
110509      3    30   1     149  469.8188
72462       3    63   1      98  386.2163
152596      3    19   1     209 1328.2188
17014       4    62   1      24  294.9250
33467       2    50   1      46 1601.4575
5241        3    33   1       9 1651.0988
215094      3    23   1     300  427.6313
88885       1    21   1     118 1092.2613
204868      2    60   2     285  781.2325
157415      2    31   2     215 1323.5750
71081       2    44   2      96 1059.2088
25420       3    38   1      35  530.7413
144226      1    27   1     196 1126.3112
47888       3    46   2      66  965.4050
216179      3    29   2     301 1237.6463
29172       3    68   1      41 1025.9738
168786      1    47   1     232  680.6213
94035       2    23   2     124  330.4563
170542      1    25   2     234  757.2287
160331      2    33   2     220  636.3900
124163      3    80   2     167  287.6988
71442       2    37   1      97  442.2300
80191       2    74   2     107  871.0338
199309      3    29   2     277  485.2337
91293       3    35   2     120  138.3187
219524      2    68   1     307  609.5862
119336      3    85   2     160  149.7612
31814       3    68   1      44  396.6913
54920       1    28   2      75  532.7175
161034      3    29   2     221  791.0100
177037      1    50   1     244  626.2400
119963      1    54   1     162  374.1062
107972      2    58   1     145  944.8863
22932       3    60   1      32  310.6413
54197       3    23   2      74  931.2737
209598      3    23   1     292 1078.2950
213604      1    74   2     297  588.5000
146480      3    27   1     200  212.0588
162463      3    55   2     223 1202.0925
215534      3    33   2     300  430.3938
100703      1    53   1     134  463.6200
162588      3    27   1     224  612.0250
222676      1    35   1     312  292.7000
220052      3    84   1     308 1301.4738
131382      3    36   1     178  825.9512
102117      3    28   1     137  451.4075
70362       3    52   2      95  185.2562
188757      3    22   2     261  704.3913
215878      2    37   1     301  789.9837
45820       3    18   2      64 2019.4137
84860       3    47   1     113  149.0200
110581      3    37   1     149  526.0775
207650      3    51   2     289  688.0538
40723       3    59   2      56  497.6050
169663      3    19   2     233  845.0362
191955      1    36   1     267  735.7350
213816      3    18   2     298 2275.3513
120967      3    48   2     163 1055.3238
209430      2    42   2     291 1771.0225
21235       3    21   1      30 1204.5663
131326      3    29   1     178  331.9588
19667       1    57   1      28  638.9138
74743       2    48   1     101 1208.8763
178672      3    66   2     246  338.2013
100174      3    24   2     133 1733.6275
69046       3    24   2      94  542.4863
79960       1    41   2     107  567.6363
108591      2    42   1     146  978.3775
235635      3    24   1     334 1382.9437
187426      2    54   2     259  478.2362
28728       3    39   2      40 1165.6175
205348      3    32   2     286 1082.9913
218812      3    30   1     306  308.1037
168389      3    48   2     231  593.2475
145479      1    21   1     198  864.2663
105170      2    40   1     141 1016.7862
155753      2    78   2     212 1109.0025
169399      3    28   1     233 1467.1363
55664       1    63   1      76  904.3763
74024       2    51   1     100  547.5538
85558       1    25   1     114  893.8825
142684      3    54   2     193 1203.3212
198792      1    22   1     277 1800.3325
82603       3    70   2     110  827.3763
171036      2    50   2     235 2003.9725
1616        1    42   2       2  590.5662
57042       3    45   1      78 1021.7287
45100       2    38   2      63 1807.9288
134828      2    28   1     183  715.1187
91167       3    26   2     120  480.1950
170605      3    40   2     234  507.2763
175869      3    77   1     242  386.2987
81594       2    82   2     109  580.0838
37426       1    20   2      52 1159.1613
113799      3    85   1     153  459.5450
24721       3    18   2      34 2912.7575
26297       3    45   2      36 1304.4925
57074       1    51   1      78  602.2112
185000      3    34   1     256  583.5738
94196       3    44   2     124 2344.1087
80656       3    45   2     108 1340.9713
14849       1    46   1      22  967.2525
145730      2    73   1     198  418.8037
56633       3    34   2      77 1011.5488
273         2    54   1       1  786.2138
60567       1    40   2      83  315.2925
47788       1    38   2      66 1105.9188
76943       2    53   2     103  537.7062
165014      3    34   1     227  824.3125
188444      3    22   1     261  623.2225
29043       1    35   1      41  724.9025
165578      3    25   1     228  596.0275
50702       3    43   2      69  985.9662
197621      3    39   2     275 1310.1163
26267       3    41   2      36 1030.3900
29565       1    60   2      41  920.8550
20060       3    36   2      28  157.2188
119780      2    20   1     162  863.8100"
tor <- read.table(textConnection(xd1), header=TRUE, as.is=TRUE)

# Grouping variable "xsmoke"  must be a factor

tor$xsmoke <- factor(tor$xsmoke,levels=c (1,2,3),
                labels=c('Current SMK','Former SMK', 'Never Smk'), ordered=TRUE)

is.factor(tor$xsmoke)

# object with survey design variables and data
nhis <- svydesign (id=~psu,strat=~stratum, weights=~wt8, data=tor, nest=TRUE)

MyBreaks <- c(18, 25, 35, 45, 55, 65, 75, 85)

svyboxplot (age_p~xsmoke,
            subset (nhis, age_p>=0),
            col=c("red", "yellow", "green"), medcol="blue",
            varwidth=TRUE, all.outliers=TRUE,
            ylab="Age at Interview",
            xlab=" "
            )

The Factor variable xsmoke is coded as tor$xsmoke <- factor(tor$xsmoke,levels=c (1,2,3),
                    labels=c('Current SMK','Former SMK', 'Never Smk'), ordered=TRUE)  which should be useful

__________________________________________enter code here


text:
Q: Returned interface{} type assertion I need function that make query to database.
I use github.com/gocraft/dbr, so i create helper function:
//SelectData - selects data from database
func SelectData(table, fields, where string, data interface{}) interface{} {

    var ptr reflect.Value

    ptr = reflect.New(reflect.TypeOf(data)) // create new pointer

    obj := ptr.Interface()

    sess := Session

    query := sess.Select(fields).
        From(table)

    if len(where) > 0 {
        query.Where(where)
    }

    _, err := query.Load(obj)

    if err != nil {
        panic(err)
    }

    return obj

}

then i try to use it:
//CheckUser - checks is user registered in db
func CheckUser(userid string) User {
    var user User
    var i interface{}

    i = db.SelectData("users", "*", "", user)

    fmt.Printf("=%#v \n", i)

    user = i.(User)
    return user
}

But i get runtime error:
interface conversion: interface {} is *models.User, not models.User
D:/Go/src/runtime/panic.go:513 (0x42ccb6)
        gopanic: reflectcall(nil, unsafe.Pointer(d.fn), deferArgs(d), uint32(d.siz), uint32(d.siz))
D:/Go/src/runtime/iface.go:248 (0x4091ac)
        panicdottypeE: panic(&TypeAssertionError{iface, have, want, ""})
C:/Users/vasalt/go/src/wcenter/models/model_user.go:29 (0x9dda3a)
        CheckUser: user = i.(User)
C:/Users/vasalt/go/src/wcenter/controllers/ctrl_main.go:59 (0x9e03b6)
        SetPageData: fmt.Printf("=result = %#v\n", models.CheckUser("1234"))

And debug output:
=&models.User{UID:sql.NullString{String:"1", Valid:true}, UserID:sql.NullString{String:"1234", Valid:true}, UserGroup:sql.NullString{String:"1", Valid:true}}

So it succesfully retrieve data from datbase, but it return &models.User not just models.User and i cant figure out how convert interface{} with *models.User to models.User

A: I think this should work. You can typecast it to *User and return User value or *User depending on your use case.
user = i.(*User)
return *user

A:  ptr = reflect.New(reflect.TypeOf(data)) // create new pointer

 obj := ptr.Interface()

reflect.New returns a reflect.value representing a pointer to a new data-type entity.and ptr.Interface() returns a real value of ptr of which type is *data.
So when you invoke i = db.SelectData("users", "*", "", user),it will returns *User.You can't use type assertion i.(User) except i.(*User).

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to extend the array with functions that are generators and able to chain them? How do I extend Array with functions that returns a generator object and be able to chain them?
I have tried extending the Array to see if I can chain generator functions. The first call works, but the next chain would not, because it returns a generator object and I have no idea how to extend that.
Array.prototype.select = function* (fn) {
    let it = this[Symbol.iterator]();
    for (let item of it) yield fn(item);
}

Array.prototype.where = function* (fn) {
    let it = this[Symbol.iterator]();
    for (let item of it) {
        if (fn(item)) yield item;
    }
}

I want to be able to chain generators like this to an array
let result = arr.select(v => v * 2)
                .where(v => v % 3 === 0);

for (let item of result) console.log(item);

A: You could store both methods as a prototype function of Object and handover the iterator object, because both functions take a generator and returns an iterable object.

Object.prototype.select = function* (fn) {
    for (let v of this) yield fn(v);
}

Object.prototype.where = function* (fn) {
    for (let v of this[Symbol.iterator]()) if (fn(v)) yield v;
}

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9],
    result = array[Symbol.iterator]()
        .select(v => v * 2)
        .where(v => v % 3 === 0);

console.log(...result);

A: Without modifying Object, you can still make these methods chainable by using a technique I've coined as "superclassing".
You start by defining your base class which Array will extend, then you modify the prototype chain of Array to artificially extend your base class.
Note how the select() and where() methods encapsulate your original generator functions to return new instances of the class so that the methods are chainable.

class Enumerable {
  constructor (getIterator) {
    this[Symbol.iterator] = getIterator;
  }

  select (fn) {
    return new Enumerable(function * () {
      for (const value of this) {
        yield fn(value);
      }
    }.bind(this));
  }

  where (fn) {
    return new Enumerable(function * () {
      for (const value of this) {
        if (fn(value)) yield value;
      }
    }.bind(this));
  }
}

Object.setPrototypeOf(Array, Enumerable);
Object.setPrototypeOf(Array.prototype, Enumerable.prototype);

const array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const result = array
  .select(v => v * 2)
  .where(v => v % 3 === 0);

for (const item of result) {
  console.log(item);
}

A: If you do not mind overextending, the first iterator returns just an object.
You can check by doing console.log(typeof arr.select(v => v * 2));.
Hence, you can simply define: Object.prototype.where = function* (fn) {};

Array.prototype.select = function* (fn) {
    let it = this[Symbol.iterator]();
    for (let item of it) {
      yield fn(item);
    }
};

Object.prototype.where = function* (fn) {
    let it = this[Symbol.iterator]();
    for (let item of it) {
        if (fn(item)) yield item;
    }
};

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let result = arr.select(v => v * 2)
                .where(v => v % 3 === 0);

for (let item of result) {
  console.log(item);
}

If you want that the order does not matter, you could extend both Array and Object like this.

Array.prototype.select = function* (fn) {
        let it = this[Symbol.iterator]();
        for (let item of it) {
          yield fn(item);
        }
    };

Array.prototype.where = function* (fn) {
    let it = this[Symbol.iterator]();
    for (let item of it) {
        if (fn(item)) yield item;
    }
};

Object.prototype.select = Array.prototype.select;
Object.prototype.where = Array.prototype.where;

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

// Chain 1.
let result1 = arr.select(v => v * 2).where(v => v % 3 === 0);

console.log('Chain 1');
for (const item of result1) {
  console.log(item);
}

// Chain 2.
let result2 = arr.where(v => v % 3 === 0).select(v => v * 2);

console.log('Chain 2')
for (const item of result2) {
  console.log(item);
}


text:
Q: (edit) Brushless Motor - Why does the stator burn up if the rotor doesn't rotate? If I was to apply power to a 3 phase stator, which in turn creates a magnetic field that's projected onto the rotor (with magnets), and (in a friction-less world) would cause the rotor to rotate (bearings on the forward and aft of the rotor).
If the rotor was to become jammed/stuck/no longer able to spin, why does the stator burn up? Wouldn't the magnetic field continue to be applied to the rotor?
I apologize if the specific terms are incorrect. I'm mainly trying to understand why the stator becomes damaged if the rotor is unable to spin. Obviously there's no physical damage between the stator/rotor (rubbing,ect).

A: This answer was given prior to the op changing the question. Originally, the question referred to the motor as being a squirrel cage type. Subsequently, after several comments, the op changed it to a brushless motor. You just can't get the staff any more!
When you stall a 3 phase motor it becomes a transformer and, because the rotor is the secondary AND is shorted out (by necessity for it to operate as a motor), you end up with a shorted transformer.
Ask yourself why a transformer burns when the secondary is shorted.

A: The induction motor generates the currents in the rotor by induction (hence the obvious name), these currents then generate torque by interaction with field generated by the stator. The magnitude of the emf generated in the rotor is dependent on the frequency it sees - the difference between the speed it is rotating at and the speed the rotating field generated by the stator - this is the 'slip' usually expressed as a proportion of the synchronous speed.
The frequency is therefore at its highest when the rotor is stationary, though the induced current isn't necessarily at its highest, since the rotor winding (the squirrel cage in this case) has inductance that limits the current, but in any case, the rotor current generates its own field, that opposes the main field, reducing the back emf at the stator windings, so that the current through them also rises.

The stator current is therefore at its highest at locked rotor. Even without the loss of cooling that you get from the rotor spinning, the stator will be hottest like this.


text:
Q: Access element of nested data structure created under function from function argument I have following function where I build dict of dicts dynamically (here DoD is created statically for simplicity):
import json
def fun(dummyArg1, dummyArg2):
  DoD = {'a': {'aa':1, 'ab':2}, 'b': {'ba':3, 'bb':4}, 'c': '5'}
  print json.dumps(DoD, sort_keys=True, indent=4)
  # FURTHER CODE THAT WILL WORK WITH DoD VARIABLE GOES HERE

In [1]: fun(1,2)
Out[1]:
{
    "a": {
        "aa": 1,
        "ab": 2
    },
    "b": {
        "ba": 3,
        "bb": 4
    },
    "c": "5"
}

Is it possible to specify particular DoD element content during function call? I would like to have something like:
fun(dummyArg1, dummyArg2, DoD["b"]["ba"] = "New Value")

I know that it is possible e.g. via passing list where 0th position is new value, 1st position is "outer" dict key and 2nd position is "inner" dict key:
import json
lst = ["New Value", "b", "ba"]
def fun(arg1, arg2, additionalParams):
  DoD = {'a': {'aa':1, 'ab':2}, 'b': {'ba':3, 'bb':4}, 'c': '5'}
  DoD[additionalParams[1]][additionalParams[2]] = additionalParams[0]
  print json.dumps(DoD, sort_keys=True, indent=4)
  # FURTHER CODE THAT WILL WORK WITH DoD VARIABLE GOES HERE

In [1]: fun(1,2,lst)
Out[1]:
{
    "a": {
        "aa": 1,
        "ab": 2
    },
    "b": {
        "ba": "New Value",
        "bb": 4
    },
    "c": "5"
}

But as you can see it is not very robust (changing value under key 'c' requires rewriting the function code) nor elegant. Is there better approach?
Bonus question: Why in last example after assignment "ba" contains ["New Value"] instead of "New Value"?
PS: Even if DoD will be created dynamically there will always be DoD["b"]["ba"] element.

A: You can use **kwargs and check root, i.e.:
import json

def fun(arg1, arg2, root, **additionalParams):
  DoD = {'a': {'aa':1, 'ab':2}, 'b': {'ba':3, 'bb':4}, 'c': '5'}

  if root:
    DoD[root][additionalParams.keys()[0]] = additionalParams.values()[0]
  else:
    DoD[additionalParams.keys()[0]] = additionalParams.values()[0]

  print json.dumps(DoD, sort_keys=True, indent=4)

test1:
fun(1,2, root="b", ba = "new value")

Output:
{
    "a": {
        "aa": 1,
        "ab": 2
    },
    "b": {
        "ba": "new value",
        "bb": 4
    },
    "c": "5"
}

test2:
fun(1,2, root=None, c = "new value")

Output:
{
    "a": {
        "aa": 1,
        "ab": 2
    },
    "b": {
        "ba": 3,
        "bb": 4
    },
    "c": "new value"
}

NOTE: You can pass root in **additionalParams but you should consider not preserved the order in keyword arguments passed to the function.

A: This is a weird way to set up a program, but assuming you have your reasons I think you might be looking for splat arguments [*args] or [**kwargs]. With a splat argument you can have your "formal arguments" aka "required arguments" to the function (dummyArg1, dummyArg2 in this case) then your splat arg. So your def would be
def fun(dummyArg1,dummyArg2,*args):

Your call would be
fun(1,2,'abc','def',4,'etc')

and inside your code args would be represented as a tuple = ('abc','def',4,'etc')
Then you can use your tuple to sort out your dictionary walk:
l = len(args)
if l == 3:
  DoD[args[1]][args[2]] = args[0]
elif l == 2:
  DoD[args[1]] = args[0]

Of course this could become cumbersome if you have exceptionally deep dictionaries in which case you might want to look at more complex walking methods.


text:
Q: MS SQL advanced job scheduling for last working day Given a (for us) large datastream, of about 2GB/day. This data has to be incorporated/structured/cleansed into a destination database (this part is solved).
Until now we were dropping and creating a new datatable every day for the whole dataset of the current month, and then union into a materialized table of the previous months' dataset.
Besides, that this is a very un-elegant way, also unfortunately by the end of the month this query is becoming quite massive and draining the server for up to 1,5 hours daily.
I thought I do a parameterized query for date by grabbing all the data for DateMax
(
declare @ReportDateMax datetime
set @ReportDateMax = dateadd(dd,-1, cast(getdate() as date)

)
however it is not good enough-
the problem is the following:
     1. on monday we need to download the data for friday
     2. on tuesday for monday
     3. wednesday for tuesday
     4. thursday for wednesday
     5. friday for thursday
which means that I cannot just download the information for yesterday, as than on monday I would not get anything.
Also ideally, if we just daily data I would like to run twice a day a select query for the previous reporting day.
desired solution:
design a query which selects the previous working day (public holidays are irrelevant for the topic).

A: I have found a solution eventually in another post.
In case somebody else is interested:
                    SELECT  DATEADD(DAY, CASE DATENAME(WEEKDAY, GETDATE())
                    WHEN 'Sunday' THEN -2
                    WHEN 'Monday' THEN -3
                    ELSE -1 END, DATEDIFF(DAY, 0, GETDATE()))


text:
Q: .Net session , how to get data I have a login page called login.aspx that copies the affid into a session and loads the affid on another page called dashboard.aspx.
I collect the session and load it like this :
Login.aspx :
MysqlConn.Open()
            Dim Query As String
            Query = "select * from mdxmain.taffiliate where affID = '" & username.Text & "' and affPassword = '" & password.Text & "'"
            COMMAND = New MySqlCommand(Query, MysqlConn)
            Session("affID") = username.Text

dashboard.aspx :
Dim userid As String = HttpContext.Current.Session("affID")
        If (userid Is Nothing) Then
            Response.Redirect("login.aspx")

    End If

Dim c As New MySqlConnection("Server=test;Database=test;UID=test;PWD=test;")
        c.Open()
        Dim com As New MySqlCommand("SELECT AffID FROM toutcome WHERE affID = '" & CType(Session.Item("affID"), String) & "'", c)
        Dim myReader As MySqlDataReader = com.ExecuteReader(CommandBehavior.CloseConnection)
        myReader.Read()
        affiliateid.Text = myReader.Item(0).ToString()

        myReader.Close()

The problem is that it only collects "affid" from  the database and i have mutiple feilds that i want to use. how do i load all the feilds so i can use them ? So in the mysql query i want to search feilds based on data in the session.

A: In similar scenarios I create a class for my object... in this case I'll call it User
The User class will have several properties such as Name, AccessRights etc.
The class is populated in the login.aspx code and assigned to a session.
All subsequent pages that need to check user credentials will have the following
Private CurrentUser as New User

Protected Sub PageLoad(ByVal sender as Object, ByVal e as EventArgs) Handles Me.PageLoad

    If IsNothing(Session("USER")) Then
       Response.Redirect("Login.aspx")
    Else
       CurrentUser = Session("USER")
    End If

End Sub

You can then access any user details with CurrentUser.NameOfProperty e.g. CurrentUser.Name or CurrentUser.AccessRights etc.

A: ASP.Net session can hold any information that is serializable, so as pointed out you can store whole objects in it if you want, and retrieve fields as needed.
Having said that, I would caution against storing too much sensitive information (like password) in the session as it is generally an antipattern to do so.
We use a wrapper object for our session use that initializes up from HTTPContext, and makes sure we never pass in or use any web specific code in our sub objects while still allowing the overall concept of a session.
So something like this:
Public Class UserSession

    Public Property UserName as String = String.Empty

    Public Sub New(context as HTTPContext)
        ...
        Me.Username = CStr(context.Session("UserName"))
    End Sub

    Public Sub Synchronize(context As HTTPContext)
        ....
        context.Session("UserName") = Me.Username
    End Sub

End Class

And on the login you now could change it to:
Dim us = New UserSession(HttpContext.Current)

MysqlConn.Open()
Dim Query As String
Query = "select * from mdxmain.taffiliate where affID = '" & username.Text & "' and affPassword = '" & password.Text & "'"
COMMAND = New MySqlCommand(Query, MysqlConn)

us.UserName = username.Text
... Set any other properties you need ...
us.Synchronize(HttpContext.Current)

And then on the page you can just do:
Dim us = New UserSession(HttpContext.Current)

DoStuff(us.UserName)

Edit:
I just realized that I didn't really give you details of how to set  the properties initially. You can do it one of two ways.
One is to do it exactly like you were in your example (Session("SomeKey") = "SomeValue") Which is actually how we manage ours due to a unique login process. Essentially the object as-is is read-only since no changes are persisted (and this is how we want it) but that may not be the best for everyone.
The perhaps better way if you will want to change the values as you go would be to implement a "Synchronize" method to store properties back to the session. This would handle the initial loading, and any changes after the fact.
You also could back the properties directly on the session if you didn't want the extra step.
See edited method above.


text:
Q: How to design database with the default data that can be overwritten in some cases I'm designing the database model for the delivery application.
I have a DeliveryWeek entity that represents a single week and a DeliveryDay entity that represents a day of the week (Monday-Friday).
There is also a DeliveryWeekDay entity that joins DeliveryWeek and DeliveryDay in many-to-many relationship.
There is also DeliveryHour entity and DeliveryDayHour entity that joins DeliveryDay and DeliveryHour in many-to-many relationship.
For most of the weeks delivery hours are the same but, in some cases, (holiday week) they might be different.
I want to be able to modify default delivery hours for all new DeliveryWeeks but for some DeliveryWeeks these hours can be overwritten.
Should I use two separate tables? For example DefaultDeliveryHours for the default values and every time when I create a new DeliveryWeek I should make a new DeliveryHour entries based on DefaultDeliveryHour data?

A: I think there are two ways you could go:
First is without DeliveryWeekDay:
---------------      -------------
| DeliveryWeek|      |DeliveryDay|
|-------------|      |-----------|
|Year (PK)    |      |Id (PK)    |
|Weeknr (PK)  |      |Weekday    |
|MonId        |--->  |Properties |
|TueId        |--->  -------------
|WedId        |--->
|ThuId        |--->
|FriId        |--->
---------------

Via the id you could define different DeliveryDays with different properties. Your code (program or sql trigger) should then make sure that MonId only references monday weekdays etc. for the other weekdays!
The second variant would be with a DeliveryWeekDay relation table - which looks like:
---------------    -----------------    -------------
| DeliveryWeek|    |DeliveryWeekDay|    |DeliveryDay|
|-------------|    |---------------|    |-----------|
|Year (PK)    |<---|Year (PK/FK)   |--->|Id (PK)    |
|Weeknr (PK)  |    |Weeknr (PK(FK) |    |Weekday    |
---------------    |DDayId (PK/FK) |    |Properties |
                   -----------------    -------------

Here you also have to make sure that your code (program vs sql trigger) makes sure that for every DeliveryWeek there are 5 entries (for every weekday) within your DeliveryWeekDay table - except if there is a holiday within that week.
In both ways you could make DeliveryDay.Id = 1 the default and use other id values for your special cases.
The same concept goes for your DeliveryHour table. Please don't use an extra default table, because it is only a redundant one.

A: If I understand you correctly you are using the "DeliveryWeekDay" entity as reference.
You could design your "DeliveryWeekDay" like this:
ID,DeliveryWeekID,DeliveryDayID,DeliveryHoursID, DefaultDayID, DefaultHoursID.
So if "DeliveryDayID" is null you return "DefaultDayID" and if "DeliveryHoursID" is null you could return "DefaultHoursID". Assuming you query by SQL:
SELECT ID,DeliveryWeekID,ISNULL(DeliveryDayID,DefaultDayID),ISNULL(DeliveryHoursID,DefaultHoursID)

This way you can have default value but also change the default for some entries.


text:
Q: How to show file path in ? I tried <input type="file" value="path..." /> but not working.
How to fix?

A: The file input cannot be prepopulated by the webpage.
This is to avoid situations such as:
<input
  type="file"
  value="path-to-standard-location-for-quicken-data-files"
  style="display: none">

A: I am afraid that for security reasons this is not possible. The browser will dictate how the file input field will be handled and only the user can change the value by clicking on the Browse button.
From the W3C specification:

input type="file":
       Creates a file select control. User agents may use the value of the
  value attribute as the initial file
  name.

A: As you don't know anything about the file structure on the users end, you cannot predefine the file to pick. And it would be pretty insecure when you could just make the <input /> hidden and send it with a form...


text:
Q: Why do Material UI tabs stop working when I use a .map to populate the content dynamically instead of hard coding? I have implemented Material UI's tabs successfully by hard-coding the content, but when I tried to make a  my hard coded tabs with a .map function to populate the content from a data source (simple json), it no longer works. Can anyone see why? The only change I made was to the MyTabs component below where there are now two .map functions instead of hard coded tabs.
Many thanks for your help!
Here is my data:
export const TabsData = [
  {
    tabTitle: 'Tab 1',
    tabContent: 'Hello 1',
  },
  {
    tabTitle: 'Tab 2',
    tabContent: 'Hello 2',
  },
  {
    tabTitle: 'Tab 3',
    tabContent: 'Hello 3',
  },
];

Here is my MyTabs component:
import React, { useState } from 'react';

// Material UI
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';

// Data
import { TabsData } from '../../page-templates/full-page-with-tabs/FullPageWithTabsData';

//Components
import TabContentPanel from '../tabs/tab-content-panel/TabContentPanel';

const MyTabs = () => {
  const classes = useStyles();
  const initialTabIndex = 0;
  const [value, setValue] = useState(initialTabIndex);

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };
  return (
    <>
     <Tabs
       value={value}
       onChange={handleChange}
       aria-label=""
       className={classes.tabHeight}
       classes={{ indicator: classes.indicator }}
     >
      {TabsData.map((tabInfo, index) => (
        <>
         <Tab
            label={tabInfo.tabTitle}
            id={`simple-tab-${index}`}
            ariaControls={`simple-tabpanel-${index}`}
         />
        </>
       ))}
    </Tabs>
    {TabsData.map((tabInfo, index) => (
        <TabContentPanel value={value} index={index}>
           {tabInfo.tabContent}
        </TabContentPanel>
    ))}
    </>
  );
};

export default MyTabs;

And here is the TabsPanel component:
import React from 'react';
import PropTypes from 'prop-types';

// Material UI
import { Box } from '@material-ui/core';

function TabContentPanel(props) {
  const { children, value, index, ...other } = props;
  const classes = useStyles();
  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`simple-tabpanel-${index}`}
      aria-labelledby={`simple-tab-${index}`}
      {...other}
    >
      {value === index && <Box className={classes.contentContainer}>{children}</Box>}
    </div>
  );
}

TabContentPanel.propTypes = {
  children: PropTypes.node,
  index: PropTypes.any.isRequired,
  value: PropTypes.any.isRequired,
};

export default TabContentPanel;

A: It doesn't work because you added some extra Fragments (<> and </>) in the Tabs component and the Tabs component doesn't accept a Fragment as a child:
If you remove those, it will work as expected:
{TabsData.map((tabInfo, index) => (
  <Tab
    label={tabInfo.tabTitle}
    id={`simple-tab-${index}`}
    key={tabInfo.tabTitle}
    ariaControls={`simple-tabpanel-${index}`}
  />
))}

And please use the key prop with a unique id if you create an array of elements. Each child in a list should have a unique "key" prop.


text:
Q: Phase transitions, Landau Ginzburg theory and Symmetry reduction On one side of critical temperature (usually for $T<T_{c}$), symmetry is reduced w.r.t the symmetry on the other (usually $T>T_{c}$) regime. I heard on the road (near a theoretical physics institute) that the symmetry group for $T<T_{c}$ has to be a subgroup of the symmetry group for $T>T_{c}$. Can one prove this for both 1st and higher order transitions ?
Also, I found that the phases which one can generate in the regime below $T_{c}$ are the ones which obey the symmetry properties of the Landau free energy expression we start with.
For example, for structural phase transition of $BaTiO_{3}$ with cubic symmetry for $T>T_{c}$, depending on whether I expand the free energy to 4th order or 8th order respectively (cubic symmetry of $BaTiO_{3}$ for $T>T_{c}$ kept into account), I get different number of possible phases (2 and 3 respectively) below the critical temperature but as expected, all are subgroups of the cubic symmetry group.
Can one generate all possible symmetry subgroups of G for $T<T_{c}$ i.e. all possible phases starting from a particular phase for $T>T_c $ (with a given symmetry group G), depending on what order expansion is used for the Landau free energy ?
Also, does the validity of hyperscaling within the a certain region of temperature around the critical temperature (which is of the order of the region of smearing of the transition curve around $T_c$) for continuous phase transitions as above, imply anything for the reduction in symmetry around $T=T_{c}$ ?


text:
Q: Calling a member of IDispatch COM interface from C# I wanted to call the GetIdsOfNames function from a COM object that implements the IDispatch interface in c#. I've written the following code but it fails with the DISP_E_UNKNOWNNAME. Is this the correct approach to do this?
 Object so = Activator.CreateInstance(Type.GetTypeFromProgID("ProgID"));
 Object[] args = new Object[5];
 string[] rgsNames = new string[1];
 rgsNames[0] = "PrintNormal";
 uint LOCALE_SYSTEM_DEFAULT = 0x0800;
 uint lcid = LOCALE_SYSTEM_DEFAULT;
 int cNames = 1;
 int[] rgDispId = new int[1];
 args[0] = IntPtr.Zero;
 args[1] = rgsNames;
 args[2] = cNames;
 args[3] = lcid;
 args[4] = rgDispId;
 Object result = so.GetType().InvokeMember("GetIDsOfNames", BindingFlags.InvokeMethod, null, so, args);

Thanks,
Richard

A: No you cannot, because InvokeMember internally uses GetIDsOfNames, and this one only checks actual methods, not the first 6 in IDispatch. Or in other words, GetIDsOfNames cannot be invoked using IDispatch's method Invoke. That is how COM works.

A: Yes, doesn't work, the RCW doesn't expose the IDispatch methods.  You have to obtain the IDispatch interface reference explicitly.  This worked well:
using System;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;

class Program {
    static void Main() {
        Object so = Activator.CreateInstance(Type.GetTypeFromProgID("SAPI.SpVoice"));
        string[] rgsNames = new string[1];
        int[] rgDispId = new int[1];
        rgsNames[0] = "Speak";
        IDispatch disp = (IDispatch)so;
        Guid dummy = Guid.Empty;
        disp.GetIDsOfNames(ref dummy, rgsNames, 1, 0x800, rgDispId);
        Console.WriteLine(rgDispId[0]);
    }

    [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("00020400-0000-0000-C000-000000000046")]
    private interface IDispatch {
        int GetTypeInfoCount();
        [return: MarshalAs(UnmanagedType.Interface)]
        ITypeInfo GetTypeInfo([In, MarshalAs(UnmanagedType.U4)] int iTInfo, [In, MarshalAs(UnmanagedType.U4)] int lcid);
        void GetIDsOfNames([In] ref Guid riid, [In, MarshalAs(UnmanagedType.LPArray)] string[] rgszNames, [In, MarshalAs(UnmanagedType.U4)] int cNames, [In, MarshalAs(UnmanagedType.U4)] int lcid, [Out, MarshalAs(UnmanagedType.LPArray)] int[] rgDispId);
    }
}


text:
Q: Seq toDictionary How do i construct a dictionary from a Seq. I dont seem to be able to get syntax right.
So i have a Seq and i would like to construct a dictionary from it, something like
Document
<Overrides>
  <token key="A" value="1"/>
  <token key="B" value="2"/>
  <token key="C" value="3"/>
  <token key="D" value="4"/>
  <token key="E" value="5"/>
  <token key="F" value="6"/>

let elem = docs |> Seq.map(fun x -> x.Descendants(XName.op_Implicit "Overrides").Elements(XName.op_Implicit "token"))
            |> Seq.head
            |> Seq.iter(fun (k: XElement , v:XElement) ->  k.Attribute(XName.op_Implicit "key").Value, v.Attribute("value").Value)

but get runtime error
Error   1   This expression was expected to have type     XElement     but here has type     'a * 'b

A: To build a dictionary from a seq, you generally use the dict function. It takes a seq of key/value tuples, so the problem boils down to producing this sequence of tuples. With System.Xml.Linq you navigate the XML get the attribute values in a sequence.
Here's the code:
let x = @"<Overrides>
  <token key='A' value='1'/>
  <token key='B' value='2'/>
  <token key='C' value='3'/>
  <token key='D' value='4'/>
  <token key='E' value='5'/>
  <token key='F' value='6'/>
  </Overrides>"

#if INTERACTIVE
#r "System.Xml"
#r "System.Xml.Linq"
#endif

open System.Xml.Linq

let docs = XDocument.Parse x

let elem = docs.Root.Descendants(XName.Get "token")
            |> Seq.map (fun x -> x.Attribute(XName.Get "key").Value, x.Attribute(XName.Get "value").Value)
            |> dict

Seq.head returns the first element of a sequence, it's not useful here unless you want to use it to get to the Overrides node.
Seq.iter applies a function to each element in a sequence much like a for/foreach loop, just for the side-effects of the function. It's not useful here unless you want to build the dictionary imperatively, i.e. add key/values to an already existing dictionary.

A: In your example, Seq.iter iterates over a sequence of 'token' XElements. So, in order to compile, your lambda should be (fun xel -> xel.Attribute(XName.op_Implicit "key").Value, xel.Attribute("value").Value). However, even if it compiles after this correction, I recommend you simplify the code by usinig Mauricio's approach.


text:
Q: Call Centre Models Can anyone suggest me, which Mathematical(Statistical) methods can be used to predict incomingcalls by a given time interval at a call centre? Please cite any research paper or a website that may help in this kind of forecasting.
Can incoming calls be treated as apoisson distribution in such a scenario?

A: A few random hits from a relevant Google Scholar search gives:
Call center demand forecasting: improving sales calls prediction accuracy through the combination of statistical methods and judgmental forecast
Antipov, A and Meade, N., et al. (2002) Forecasting call frequency at a financial services call centre. Journal of the Operational Research Society 53(9):953--960.

A: Avramidis, Deslauriers, and L'Ecuyer (2004). Modeling Daily Arrivals to a Telephone Call Center, Management Science, 50, 7, pp. 896-908.


text:
Q: Check if an element is contained in the values (array) of a json column in MySql I have the following values inside a cell of a json column in MySql:
{
    "produttori": [
        "8",
        "9"
    ],
    "articoli_alternativi": [
        "3",
        "9"
    ],
    "articoli_accessori": [
        "5",
        "6",
        "7",
        "8"
    ],
    "tecnologie": [],
    "fornitori": [
        "9",
        "8"
    ],
    "classificazioni": [
        "3",
        "4"
    ]
}

I would like to make a query that extracts data based on the existence of a value in the array at the fornitori key.
For now I've tried this:
query = 'SELECT nome, formulati_commerciali FROM articolo WHERE JSON_CONTAINS(JSON_EXTRACT(dati, "$.fornitori"), "' + \
        value+'", "$")'

Which print is:
SELECT name, data FROM articolo WHERE JSON_CONTAINS(JSON_EXTRACT(data, "$.fornitori"), "8", "$")

Basically the condition is that value ("8") must be inside the fornitori list, otherwise skips the element.

Unfortunately, the query did not produce any results.

I would like to know how you can formulate such a query in MySql. I will need them often!
Thanks in advance!

A: This should do it:
SELECT name, data
FROM articolo
WHERE JSON_CONTAINS(data, '"8"', '$.fornitori')

The double quotes around 8 are important, in order to properly match the JSON data. On the other hand, the query consistently uses single quotes for string literals.

A: You can use
SELECT data
  FROM
  (
    SELECT  @i := @i + 1 AS rn,
            JSON_UNQUOTE(JSON_EXTRACT(data,CONCAT('$.fornitori[',@i-1,']'))) AS elm,
           data
      FROM information_schema.tables
     CROSS JOIN articolo
     CROSS JOIN (SELECT @i := 0) r
  ) q
 WHERE elm = 8

in order to search for the spesific value within a spesific
array("fornitori")
Demo


text:
Q: Application.COMAddIns Subscript out of range Following the sample case below
https://msdn.microsoft.com/en-us/library/bb608614.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1
Run into a 'Subscript out of range' in
Set addIn = Application.COMAddIns("ExcelImportData")
New to VSTO and C#. How do I debug this?

A: If the add-in subscript is out of Range, it suggests that you've either made a typo in the name of the add-in while creating the VSTO project, or you've failed to open Excel using the debugger (which automatically loads the add-in).
You can ensure that Excel is loading properly by adjusting the Project Properties in Visual studio:

Above, my full path to Excel is:

C:\Program Files (x86)\Microsoft Office\root\Office16\Excel.exe

Then, once you've pressed F5 to start Excel, you can check the loaded COM add-ins by clicking on the COM add-ins button on the Developer tab.


text:
Q: How to trigger existing route in Apache Camel? There is a route which read from SFTP after 30 Minutes
 public class ApplicationRoutesBuilder extends RouteBuilder {
                  "sftp://10.10.10.10/emp"
                + "?username=xxx"
                + "&password=yyy" // Stored on wildfly server
                + "&download=true" //Shall be read chunk by chunk to avoid heap space issues. Earlier download=true was used:
                + "&useList=true"
                + "&stepwise=false"
                + "&disconnect=true"
                + "&passiveMode=true"
                + "&reconnectDelay=1800000"
                + "&bridgeErrorHandler=true"
                + "&delay=30000"
                //+ "&fileName=" + sftpFileName
                + "&include="+ sftpFileName
                + "&preMove=$simple{file:onlyname}.$simple{date:now:yyyy-MM-dd'T'hh-mm-ss}.processing"
                + "&move=$simple{file:onlyname.noext}.$simple{date:now:yyyy-MM-dd'T'hh-mm-ss}.success"
                + "&moveFailed=$simple{file:onlyname.noext}.$simple{date:now:yyyy-MM-dd'T'hh-mm-ss}.failed"
                + "&readLock=idempotent-changed"
                + "&idempotentRepository=#infinispan"
                + "&readLockRemoveOnCommit=true"

           //ROUTE IS
           from("ABOVE SFTP STRING")
            .onException(GenericFileOperationFailedException.class)
                .onWhen(exchange -> {
                        Throwable cause = exchange.getException(GenericFileOperationFailedException.class).getCause();
                        return (cause != null && cause.toString().equalsIgnoreCase("2: No such file"));
                    })
                    .handled(true)
                    .logExhausted(true)
                    .logExhaustedMessageHistory(true)
                     // For troubleshooting. TODO: remove on final deploy
                     .log("Could not find file")
                    .end()
            .to(archiveReceivedFile(sftpFileName))
            .log("Archived Successfully in HRM Archive Directory")
            .bean("service1", "enrichFromAd")
            .log("Loaded IFS and AD Successfully into Memory")
            .split(body().tokenizeXML("EmploymentRequest", "EmploymentRequests")) // Split and tokenize the requests, streaming individual requests to message queue
            .unmarshal(new JaxbDataFormat(JAXBContext.newInstance(EmploymentRequest.class)))
            .bean("service1", "updateEmployeeData")
            .marshal(new JaxbDataFormat(JAXBContext.newInstance(EmploymentRequest.class)))
            .inOnly(EMPLOYEES_QUEUE)
                    .choice()
                    .when(header("CamelSplitComplete"))
                        .log("Download xml file completed");

I want to manually trigger this route. How can we do it using Apache Camel?
//As of now we are reloading or undeploying and deploying or restarting server to trigger route at load  or decrease time to 30 Seconds. But i do not want this. I can either create trig file or rename or may be trig using JSP page. But what code will trigg this thread?
Following is context initialization:
@ApplicationScoped
public class ApplicationCamelContext extends DefaultCamelContext {
    private static final Logger LOGGER = LoggerFactory.getLogger( ApplicationCamelContext.class.getName() );
    @PostConstruct
    void customize() {
        LOGGER.info("Started ApplicationCamelContext: customize");
        setName("employee-import");
        getShutdownStrategy().setTimeout(2L);
        LOGGER.info("Shutdown ApplicationCamelContext: customize");
    }

}

A: You may make the route on-demand using Content Enricher EIP. Camel provides enrich() and pollEnrich() as  apart of Java DSL to implement it.
Here is a unit test case that does pretty much the same thing. Using message delivery at an endpoint to trigger an sftp action.
On a side note, the example above uses a vm: component but you may use direct:, seda: or vm: components at the from() construct, based on your specific use case. Their differences are explained in another answer here. I think seda: is the best fit in this specific case.
The route implementation should be like
seda:trigger -> pollEnrich(sftp) -> rest of the processing
Once this is ready, you may use a ProducerTemplate to deliver a message to seda:trigger to kickstart SFTP download. When to use the ProducerTemplate is totally upto you for implementation (trigger file/rest endpoint..)


text:
Q: What does "made out to" mean? In Runaway Jury (2003), Marlee meets jury consultant Rankin Fitch:

Fitch: What's your price?
Marlee: Ten million. Non-negotiable.

Fitch took out a check:

Fitch: This is made out to cash. Five hundred thousand dollars...
...to walk away from my jury.

What does "made out to" mean?

A: In this context.  Fitch is writing a check. That is a written and signed instruction to the bank to pay someone some money from his bank account.
Usually you write the name of the person you want to pay on the check.  We would say.

This check is made out to Millie J. Frank.

It is (or used to be) possible to write "cash" instead of a name, in which case the bank would pay the check in cash, instead of into a named bank account. That is less secure, but it is also anonymous. See https://www.fiscaltiger.com/making-a-check-out-to-cash/
In the UK, most banks don't allow cheques made out to cash, as they are too much of a security and crime risk. Cheques are now almost completely obsolete in the UK; I've probably written about 2 in ten years. It is possible to make a check out to cash in the USA.

A: A check (British English spelling 'cheque') is made out to whoever or whatever is written in the place for the payee details.
This cheque was made out to CIT England Ltd. A signed cheque made out to 'cash' may, under some circumstances, be exchanged at once for cash in a bank. This can be insecure, so some countries' banking systems no longer allow this to be done.


text:
Q: Setting variables from textbox values in objective-c Sort of new to objective-c, just wondering how I can set a variable as a value from a textbox. I'm setting up my login screen and will be using a JSON request to process the variables.
@interface LoginController : UIViewController
{
    IBOutlet UITextField *txtUsername;
    IBOutlet UITextField *txtPassword;
    IBOutlet UIButton *btnLogin;
}

-(IBAction)btnLogin:(id)sender;

@end

Everything is defined  in the above .h
@implementation LoginController

-(IBAction)btnLogin:(id)sender
{
    username = [txtUsername];
}

Just need to know the syntax to set that username variable to the text in the textbox when btnLogin is clicked. (.m file above)

A: You get the value of the text in the text field like so :
-(IBAction)btnLogin:(id)sender
{
    NSString * username = [txtUsername text];
}

also please to the documentation of the UITextField


text:
Q: Ui elements not scaling correctly I am making a mobile game with Unity. When you win or die in the game you get this screen, most of the game we have developed with the resolution set to a 18:9 aspect ratio and it always scaled properly over to 16:9.
However just recently when switching to 16:9 the button's get all squished like this. The canvas scaling is set to match witdth/height and set to 0.5 at 2160x1080. How can we fix this.
Thanks in advance,
Roan van der Duim.

A: It could be that you need to set the canvas scaler to Scale with Screen Size. I don't know if you already have it set to scale with screen size, otherwise you just need to adjust the anchors of your UI objects. Hope it helps.


text:
Q: Read Outlook attachment content in Outlook add-in (C# ) while creating a mail I am trying to develop an outlook add-in in VS 2010. It's purpose is to scan email body and attachment content for some key words and if any such words are found, email sending should be blocked.
I am able to read email body and subject and to the validation but I am not understanding how to read an attachment content (txt file) while composing the mail.
attachment.GetTemporaryPath() is not giving the attachment path. I guess this works only for mails in inbox.
One way I found was saving the attachment to a temp folder and reading it (attachment.saveAs()).
Is this the only way  to read attachment content while composing a mail ?
Possible Duplicate : C# Outlook 2007 - How do I access attachment contents directly from my addin?
But as suggested in there, I cant use Redemption. Is there any other way?

A: Yes, saving the attachment data to a temporary file and reading it s the only way. In theory, you can use Attachment.PropertyAccessor.GetProperty to read the PR_ATTACH_DATA_BIN property, but you will run into problems for the large (> 64kB) files.
You can also use Extended MAPI to open the attachment data as IStream (IAttach::OpenProperty(PR_ATTACH_DATA_BIN, IID_IStream)), but it is only accessible through C++ or Delphi. You can use Redemption (any language - I am its author) that wraps Extended MAPI and exposes AsArray and AsText properties on both RDOAttachment and the Attachment object exposed by the Safe*Item objects.


text:
Q: Stripe.js v3 elements requiring double tap to focus (but only on iPad/iPhone) I've been working with Bootstrap 4 beta and Stripe.js v3. If you're not familiar with this newer version of Stripe.js, it's basically injecting iframes into spans, and making the spans act as if they are form inputs. I'm not in love with the idea, but it's supposedly more PCI compliant that the older version of Stripe.js (v2).
Demo here: https://codepen.io/skunkbad/pen/BdgYmY
Reducing the HTML down to what represents my credit card input looks like this:

Due to CSS styles from Bootstrap 4, this span.form-control has a display of "flex", and I have to change that or I can't see what I type into the field.
#card-number.form-control {
    display:block;
}

This ends up working fine for all of the browsers I have tried:

*

*Firefox on Ubuntu 16.04

*Chrome on Ubuntu 16.04

*Internet Explorer on Windows 8.1

*Chrome on Android N Phone

*Safari on iPad

*Safari on iPhone

But on the IOS devices that I've tried (iPad and iPhone), I have to double tap the field to get focus and start typing. The Stripe.js Elements demo on the Stripe website doesn't have this problem, so I'm assuming it's related to Bootstrap 4's CSS.
Full code for your testing enjoyment:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Stripe.js v3 with Bootstrap 4 (beta) Test</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">

Stripe.js v3 with Bootstrap 4 (beta) Test

        <form id="payment-form">

            Name on Card

              A
              <input type="text" class="form-control" id="name">
              B

            Credit Card Number

              C

              D

            CVC Number

              E

            Expiration

              F

          <button id="payment-submit" class="btn btn-primary">Submit Payment</button>
        </form>

There's only so much one can do to alter the styles and fonts of the Stripe Elements, but again I think the problem is coming from Bootstrap 4's CSS. I've tried fiddling around with the styles of the span, but without success.
So my question is, what specific changes can I make to my CSS that would allow iPad and iPhone users to simply click once like everyone else?

A: Well, I figured it out, or at least I think I figured it out. I just changed the display type from block to inline-block, and IOS Safari seems a lot happier.
#card-number.form-control {
    display:inline-block;
}

I'm not sure why block wouldn't work, because it did for all the other devices I used ... but it is what it is.


text:
Q: Powerpoint- fast ways to "insert and link" an image I make a lot of slides with png images (graphs made with matplotlib) that are frequently updated. I love being able to insert and link these images, since the slides stay up-to-date when the images are updated.
However, the mechanics of insert and link are slow and awkward (you have to click on "Insert", then "Picture", then "picture from this device", then click the "Insert" dropdown on the dialog box and change to "Insert and Link".) You can speed it up slightly by using alt-NPD but then you still need to change the dropdown on the dialog box.
Does anyone know any tips to speed this up further? For example, I would love to be able to drag an image into powerpoint and have it link itself automatically.


text:
Q: Is there a way to serialize an object in debug mode? Often I will fix an obscure bug involving very complicated classes.  Now I want to build an automated regression test for it.  Ideally there would be a way to serialize the class from debug mode, and re-instantiate it in the unit test.  For simplicity you can assume the classes are serializable, like a vector of a few thousand specific Integers.  Is there a way to do this, or do I need to spend substantial amounts of time reconstructing the class in code?
I am mainly looking for an answer in java/eclipse, but I would be interested in hearing about any IDE with this feature.

A: Window > Show View > Display. You can run arbitrary commands at any point in debug mode where a breakpoint is set.  If the class is seralizable, it can be serialized from there.


text:
Q: Does Database.rollback on a savepoint release Select for Update locks I'm trying to understand Salesforce's locking mechanism. I ran a test which does the following:

*

*Calls Database.setSavepoint().

*Issues a Select for Update query.

*Calls Database.rollback(savepoint).

*Delays for several seconds.

*Exits the transaction.

I expected other threads to be able to access the record once step 3 competed. What I see is that while the changes to the record are rolled back by step 3, other threads cannot access the record until after step 5. In other words, while the changes may be rolled back, the locks aren't released.
Is this understanding correct? Is there any way for the locks to be released by the rollback?

A: There are no threads in Apex and transaction demarcation in SF is Sort of Squishy™. The acquisition of the lock by SELECT..FOR UPDATE is done in the context of a transaction. This transaction happens to be the "parent" of the transaction(s) performed by one or more savepoints. The lock is released when this parent transaction ends...but calling rollback on a savepoint does not affect the parent transaction.
Savepoint is usually implemented as a nested transaction. A transaction is started and within that transaction you can preserve the state of the database via a savepoint. You can do so multiple times. Each time you do it, a new nested transaction is started within the parent. When you roll back to a savepoint, the parent transaction is alive and well.
In SF's implementation this is easy to prove by considering the case of multiple savepoints:
Savepoint sp1 = Database.setSavepoint();
// do some work
Database.rollback(sp1);

Savepoint sp2 = Database.setSavepoint();
// do some more work
Database.rollback(sp2);

If the first call to rollback ended the "parent" transaction (wherever it was started), the second call to rollback would have issues.


text:
Q: When I tried to access a secured web service through spring client, I'm getting an exception : signingKey cannot be null? Caused by: com.sun.xml.wss.XWSSecurityException: java.lang.NullPointerException: signingKey cannot be null
    at com.sun.xml.wss.impl.dsig.SignatureProcessor.sign(SignatureProcessor.java:328)
    at com.sun.xml.wss.impl.filter.SignatureFilter.process(SignatureFilter.java:313)
    at com.sun.xml.wss.impl.HarnessUtil.processWSSPolicy(HarnessUtil.java:83)
    at com.sun.xml.wss.impl.HarnessUtil.processDeep(HarnessUtil.java:237)
    at com.sun.xml.wss.impl.SecurityAnnotator.processMessagePolicy(SecurityAnnotator.java:162)
    at com.sun.xml.wss.impl.SecurityAnnotator.secureMessage(SecurityAnnotator.java:137)
    at com.sun.xml.wss.impl.misc.XWSSProcessor2_0Impl.secureOutboundMessage(XWSSProcessor2_0Impl.java:96)
    ... 29 more
Caused by: java.lang.NullPointerException: signingKey cannot be null

A: Google gave this: http://forum.springsource.org/archive/index.php/t-50083.html.


text:
Q: EclipseLink Result Cache not caching results I want to cache the results of database queries by the query string + the query arguments.
I'm using EclipseLink's result caching to try and achieve this but am hitting the database for every query.
Note: I made an example with the same annotations and logic, but removed all business domain terms.
I have turned on mysql general query log and confirmed the queries are hitting the database everytime. When I change the named query to just be a query by with 1 parameter being the primary key, the query is cached.
I've tried using both @Cache and @Cacheable annotations on the entity, as well as no Cache annotations.
The documentation states, using result caching you don't need the primary key or indexed fields.
@Entity
@Table(name = "Ball")
@XmlRootElement
@Cache
@NamedQueries({
    @NamedQuery(name="Ball.findBallWithColor",
                query="SELECT b FROM Ball b WHERE b.color = :color",
                hints = {
                        @QueryHint(name=QueryHints.QUERY_RESULTS_CACHE, value = "true"),
                        @QueryHint(name=QueryHints.QUERY_RESULTS_CACHE_SIZE, value = "10")
                        }
    )})
public class Blue implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    private BigInteger ballID
    private Color color;

}

public enum Color {

   BLUE,
   YELLOW,
   ORANGE,
   RED;

}

The code that creates the named query and executes it:
This query gets called several times through the course of 1 request to our endpoint and the query hits the database everytime.
public List<Ball> findBallsWithColor(Color color) {

        TypedQuery<InstitutionLtvCreditScoreGroup> query = em.createNamedQuery("Ball.findBallWithColor", Ball.class);
        query.setParameter("color", Color.BLUE);
        List<Ball> blueBalls = query.getResultList();

        return blueBalls;

    }

Persistance Unit:
    <persistence-unit name="Example" transaction-type="JTA">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <jta-data-source>${some_source}</jta-data-source>
        <exclude-unlisted-classes>false</exclude-unlisted-classes>
        <shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
        <properties>
            <property name="eclipselink.weaving.changetracking"
                value="false" />
            <property name="eclipselink.target-database" value="MySQL" />

            <property name="eclipselink.cache.coordination.protocol"
                value="fish.payara.persistence.eclipselink.cache.coordination.HazelcastPublishingTransportManager" />
            <property name="eclipselink.cache.coordination.channel"
                value="myChannel" />

            <property name="eclipselink.logging.logger"
                value="org.eclipse.persistence.logging.DefaultSessionLog" />
            <property name="eclipselink.logging.level" value="WARNING" />

            <property name="eclipselink.jdbc.batch-writing" value="JDBC" />

            <property name="eclipselink.jdbc.batch-writing.size"
                value="1000" />
        </properties>
    </persistence-unit>

A: After much testing and reading up on specs, and I actually found something very very subtle with why the caching was not working.
JPA 2.2 defines the @Cacheable annotation that can be used in conjunction with <shared-cache-mode/> property in the persistence.xml file.
We have it defined as follows: <shared-cache-mode>ENABLE_SELECTIVE<shared-cache-mode/>. This means caching is enabled on the entities that are explicitly annotated that they are cached.
Problem is, with the property defined as so in the persistence.xml, we have to use the @cacheable annotation on the entities. EclipseLink 2.7 has annotation extensions, (annotations not found in the spec). One of these is @Cache which is very similar
So with <shared-cache-mode>ENABLE_SELECTIVE<shared-cache-mode/>
@Cache
@Entity
class MyEntity {}

Will not be cached.
@Cacheable(true)
@Entity
class MyEntity{}

Will be cached.
The eclipseLink spec says to use @Cache in place of JPA's @Cacheable, but I presume this would then mean we can't use that persistence property.


text:
Q: Duplicate Rules: "The XXX field is invalid for this field mapping" - during deployment During a deploy from source control to an org, I get this error:
Contact.Standard_Rule_for_Contacts_with_Duplicate_Leads
Duplicate Rule The Phone field is invalid for this field mapping.

What would the reasons be for this to occur?

A: How I got into this state is another story ...
Here's why this can happen:

Your source control is out of sync with the deployment target org.

The specific reason in our org was:

*

*Source control was populated from PROD. This included the default duplicate rule Contact.Standard_Rule_for_Contacts_with_Duplicate_Leads.

*This default duplicate rule includes mapping of the OOTB Phone field on Contact.

*Shield Platform deterministic encryption was (much later in time) enabled for the Contact.Phone field and deployed to PROD

*Duplicate rules don't support probabilistic encryption fields in the Field Mapping. SFDC auto-disables these mappings upon detecting a probabilistically-encrypted field.

*No one realized this (because the rule had never been activated) so source control's copy of the duplicate rule was never updated.

*A subsequent deploy (e.g. a CI job) from source control of that duplicate rule to any Org that originated from PROD fails with the error The Phone field is invalid for this field mapping


text:
Q: Move part of string to another string Maybe I don't have the right keywords but I can't seem to find how to do it.
Let's say I have these two string :
firstString = "I am a string";

secondString = "I am a long";

Is there a method that would allow me to move part of string 1 to string 2 ?
Move, not copy.
The final results would be :
firstString = "I am a"

secondString = "I am a long string"

The Problem
I have a string that contains a lot of characters. I want to send this string to SQLServer but the function that receives it can't hold more than 8000 char. So I need to send a request every 8000 characters.

*

*Check if String1 is longer than 8000 Char

*If it is, take the first 8000 Char and MOVE them into String2

*Insert String2 into SQL

*Repeat

*If it's lenght is smaller than 8000 Char, send String 1 to SQL

A: Strings are immutable so what you are really doing is reassigning part of firstString to itself and assigning the other part concatenated to the end of secondString.  There is no built in method to achieve this, but the code is pretty simple
secondString += firstString.Substring(6);
firstString = firstString.Substring(0,6);

A:
Is there a method that would allow me to move part of string 1 to string 2 ? Move, not copy.

Since .NET strings are immutable, they cannot support methods with "move" semantic. Every modification of a string requires creation of a new object, entailing copying.
EDIT (in response to the edit of the question) It looks like your problem has to do with splitting the string at 8K characters, not necessarily moving parts of the string. In this case, you could use this simple code to pass parts of the string to SQL:
string string1 = GetReallyLongString();
const int sqlMax = 8000;
while (true) {
    if (string1.Length > sqlMax) {
        SendToSql(string1.Substring(0, sqlMax));
        string1 = string1.Substring(sqlMax);
    } else {
        SendToSql(string1);
        break;
    }
}

Here is a quick demo on ideone.

A: As strings are immutable, you can't change them. You create new strings with parts from the original strings:
firstString = "I am a string";
secondString = "I am a long";

// concatenate second string with part from first string
secondSring = secondString + firstString.Substring(6);

// create a new string from part of the first string
firstString = firstString.Substring(0, 6);

A: Inspired by dasblinkenlight's solution, but using yield to make a static method, and using as few substrings as possible to reduce memory usage.
using System;
using System.Collections.Generic;

public class Test
{
    public static void Main()
    {
        string string1 = "quick brown fox jumps over the lazy dog";
        foreach (var strSection in string1.SplitInto(8))
            Console.WriteLine("'{0}'", strSection);
    }
}
public static class MyExtensions
{
    public static IEnumerable<string> SplitInto(this string value, int size)
    {
        for (int i = 0; i < value.Length; i += size)
        {
            if (i + size <= value.Length)
                yield return value.Substring(i, size);
            else
                yield return value.Substring(i);
        }
    }
}

See it run at Ideone.

A: Many ways to do that:
var partofstring = firstString.Substring(10, 14);
firstString = firstString.Replace(partofstring, "");

secondString += partofstring;


text:
Q: Python selenium loop getting slower and slower Im trying to scrape a review website (similar to Trustpilot).
Firstly, i got a list of ~50k links of urls (complains) to scrape. Then, im scraping specific data from each url/complain.
Problem is, my forloop is getting increasingly slower. It began scraping an url every 3 seconds, but now its rate is at 20s/iteration.
Could someone review my code and point out potential flaws?
Tks
for url in tqdm(urls):
    driver.get(url)
    count +=1
    try:
        df_load = pd.DataFrame({'id' : [counta],
         'caption' : [driver.find_element_by_xpath(
            '//*[@id="complain-detail"]/div/div[1]/div[2]/div/div[1]/div[2]/div[1]/h1').text],
         'details': [driver.find_element_by_xpath(
            '//*[@id="complain-detail"]/div/div[1]/div[2]/div/div[1]/div[2]/div[1]/ul[1]').text],
         'status' : [driver.find_element_by_xpath(
            '//*[@id="complain-detail"]/div/div[1]/div[2]/div/div[1]/div[2]/div[3]/span[2]/strong').text],
         'complaint' : [driver.find_element_by_xpath(
            '//*[@id="complain-detail"]/div/div[1]/div[2]/div/div[2]/p').text]})
        df = pd.concat([df_load, df])
    except:
        print(f'ID {counta} did not work')
        pass

A: Using concat on a dataframe is very slow and heavy on memory, each time it's called, a new copy of the dataframe is returned. See the replies here for greater detail:
Why does concatenation of DataFrames get exponentially slower?


text:
Q: Linear regression line on a scatter plot in python I am trying add a linear regression line to my scatter plot, but the way my data are stored and/or structured make the task pretty tricky for me. I managed to create a scatter plot with my data using "sns.scatterplot", but couldn't replicate it with "sns.regplot".
By using the following piece of code, I was able to produce the figure bellow :
sns.set_theme(color_codes=True)

sns.scatterplot(x=100, y=dict_all_mv['dict_100'])
sns.scatterplot(x=90, y=dict_all_mv['dict_90'])
sns.scatterplot(x=80, y=dict_all_mv['dict_80'])
sns.scatterplot(x=60, y=dict_all_mv['dict_60'])
sns.scatterplot(x=40, y=dict_all_mv['dict_40'])
sns.scatterplot(x=20, y=dict_all_mv['dict_20'])

plt.show()

The data displayed on the y axis are stored in nested dictionaries. The type and a print of one of the dictionaries are displayed bellow :
print(type(dict_all_mv['dict_100']))
print(dict_all_mv['dict_100'])

<class 'dict'>
{'P1S1': 0.2825781935483871, 'P2S1': 0.1566529827586207, 'P3S1': 0.16534197660818717, 'P4S1': 0.2463573039215686, 'P5S1': 0.21233809917355378, 'P6S1': 0.2780758316831682, 'P7S1': 0.261270830357143, 'P8S1': 0.25920007258064504, 'P9S1': 0.17294190131578946, 'P10S1': 0.18588214503816788, 'P1S2': 0.1870260291970803, 'P2S2': 0.2059823125, 'P3S2': 0.17782266216216217, 'P4S2': 0.1835217697841726, 'P5S2': 0.21022608870967743, 'P6S2': 0.2695895306122449, 'P7S2': 0.2393472735042735, 'P8S2': 0.18402302247191013, 'P9S2': 0.17260260273972605, 'P10S2': 0.20730387826086952}

I want to plot all the values stored in each dictionaries on the y axis, while the x axis values are equals to 100 for each values of 'dict_100', 90 for each values of 'dict_90', 80 for 'dict_80', etc. I have tried some options to plot a linear regression line with sns.regplot and lmplot, but without any success. Here is one of my failed attempts :
sns.regplot(x=100,y=dict_all_mv['dict_100'])
sns.regplot(x=90,y=dict_all_mv['dict_90'])
sns.regplot(x=80,y=dict_all_mv['dict_80'])

plt.show()

I got this error message :
AttributeError: 'int' object has no attribute 'shape'
My goal is to obtain a graph like this one:
Plot with a discrete x variable showing means a linear regression line
I am pretty sure the solution is to use regplot or lmplot based on the descriptions made at seaborn.pydata.org, but I don't know how to structure the code to get the results that I want.
So any help is welcome ! :)

A: To have the y-values in "long form", you can concatenate the values in the dictionaries:
ys = [yi for di in dict_all_mv.keys() for yi in dict_all_mv[di].values()]

The corresponding x-values can be obtained similarly, but instead of the value from the dictionary, the numeric value at the end of the key is added:
xs = [int(di[5:]) for di in dict_all_mv.keys() for yi in dict_all_mv[di].values()]

With these two lists you can call sns.regplot:
sns.regplot(x=xs, y=ys)


text:
Q: Expand Json based on relation I have following JSON data, If any one of the child name is matching with any of the parent name then i want to create new json set.
var PARENT_CHILD = {
  'Newton': ['Plato', 'Aristotle'],
  'Aristotle': ['Einstein'],
  'Plato': ['Tesla', 'Edison'],
  'Einstein': ['Hawking']
};

I want to convert it into like below:
 {
  "Newton": {
    "child": "Plato, Aristotle"
  },
  "Plato": {
    "parent": "Newton",
    "child": "Tesla, Edison"
  },
  "Aristotle": {
    "parent": "Newton",
    "child": "Einstein"
  },
  "Einstein": {
    "parent": "Aristotle",
    "child": "Hawking"
  },
  "Tesla": {
    "parent": "Plato"
  },
  "Edison": {
    "parent": "Plato"
  },
  "Hawking": {
    "parent": "Einstein"
  }
 }

A: You can use Array.reduce on the entries in PARENT_CHILD, creating a new entry in the output for the parent (if it doesn't already exist) and adding the child array to it, and then creating a new entry (with parent property) for each of the children of that parent:

var PARENT_CHILD = {
  'Newton': ['Plato', 'Aristotle'],
  'Aristotle': ['Einstein'],
  'Plato': ['Tesla', 'Edison'],
  'Einstein': ['Hawking']
};

var result = Object.entries(PARENT_CHILD).reduce((acc, [parent, child]) => {
  if (acc[parent]) {
    acc[parent].child = child.join(', ');
  }
  else {
    acc[parent] = { child : child.join(', ') };
  }
  child.forEach(name => acc[name] = { parent });
  return acc;
}, {});

console.log(result);


text:
Q: How to use the eulervm font only for a few letters in math mode? I would like to use the font type provided eulervm, but including this packages in the LaTeX document forces this font type to all letters. As an MWE, consider the following:
\documentclass{article}
\usepackage{xcolor}
\usepackage{amsmath}
\usepackage{eulervm}
\begin{document}
$E=m\times \color{red}c^2$
\end{document}

Here I would like to achieve that only c will have the font type of eulervm. Could you please help me how to reach this goal?

A: The package declares
\DeclareSymbolFont{letters}       {U}{zeur}{m}{n}

so instead of loading the package just declare that font as a math alphabet

\documentclass{article}
\usepackage{xcolor}

\DeclareMathAlphabet\matheuvm{U}{zeur}{m}{n}
\usepackage{amsmath}

\begin{document}
$E=m\times \color{red}\matheuvm{c}^2$
\end{document}


text:
Q: Angular 6 PrimeNG custom editor I am trying to customize my PrimeNG Editor I'm having adding a select dropdown list with custom font sizes [12px, 14px, 16px...]
Here is the component HTML

                     ...
                      <select class="ql-size">
                            <option value="12px">12</option>
                            <option value="14px">14</option>
                            <option value="16px">16</option>
                        </select>

                   ...

I can get the select list to show with all the font sizes

I'm not sure how to add the functionality to change the font size when selecting an option in the list. I don't see any examples in their docs for typescript. How can I make a select list of custom font sizes?
Here are the docs I followed
example

A: Firstly,put your component.ts
import { Editor } from 'primeng/editor';
declare var Quill: any;

and add this line in constructor
var fontSizeStyle = Quill.import('attributors/style/size');
fontSizeStyle.whitelist = ['24px', '48px', '100px', '200px'];
Quill.register(fontSizeStyle, true);

At the last,change your html

   <select class="ql-size">
       <option value="24px">24</option>
       <option value="48px">48</option>
       <option value="100px">100</option>
       <option value="200px">200</option>
   </select>

Example

A: First get the style/size  whitelisted in the .ts:
constructor(){
    var fontSizeStyle = Quill.import('attributors/style/size');
    fontSizeStyle.whitelist = ['0.75em','1em','1.5em','2.5em', '24px', '48px', '100px', '200px'];
    Quill.register(fontSizeStyle, true);
}

Now in the html file we used this whitelisted options:

   <select class="ql-size">
     <option value="0.75em">small</option>
     <option value="1em" selected></option>
     <option value="1.5em">large</option>
     <option value="2.5em">huge</option>
   </select>

   <select class="ql-size">
      <option value="24px">24</option>
      <option value="48px">48</option>
      <option value="100px">100</option>
      <option value="200px">200</option>
    </select>

Check the change of the value of the first dropdown options.
You can declare the var Quill so it doesn't have problems with the undefined variable: (this is how primeng does it too)
declare var Quill: any;

Working example here:
https://stackblitz.com/edit/quill-55477705?file=src/app/app.component.ts


text:
Q: Как написать простую функцию? function mobile(){
    $mobiles = array("iPhone","iPod","Android");
    foreach( $mobiles as $mobile ) {

    }
}

Как теперь с помощью $_SERVER['HTTP_USER_AGENT'] проверить: есть mobile - cделать одно, а если не mobile - то другое?
A: Вам поможет preg_match.
Вот само условие:
if(preg_match('/iPhone|iPad|Android/i', $_SERVER['HTTP_USER_AGENT']))
{
    //Выполняем что-то важное
}

Получить паттерн из массива можно так:
$pattern = '/' . implode('|', $mobiles) . '/i';

Тогда, соответственно, его нужно будет вставить вместо '/iPhone|iPad|Android/i'.
Что получится в итоге:
function mobile(...){
    ...
    $mobiles = array("iPhone","iPod","Android"); //если массив не будет меняться извне, можно сразу записать паттерн как '/iPhone|iPad|Android/i'
    $pattern = '/' . implode('|', $mobiles) . '/i'; //иначе строим паттерн из массива

    if(preg_match($pattern, $_SERVER['HTTP_USER_AGENT']))
    {
        //Выполняем что-то важное
    }
}

Обновление
Минимальная по коду функция, удовлетворяющая Вашим требованиям:
function isMobile()
{
    return preg_match('/iPhone|iPad|Android/i', $_SERVER['HTTP_USER_AGENT']);
}

Применение
if(!isMobile()) //если не мобильник
{
    //показываем
}


text:
Q: Как реализовать цикл, который будет работать, пока есть строки для ввода Здравствуйте.
Задачка  по этой ссылке.

Условие
Дана база данных о продажах некоторого интернет-магазина. Каждая строка входного файла представляет собой запись вида Покупатель товар
  количество, где Покупатель — имя покупателя (строка без пробелов),
  товар — название товара (строка без пробелов), количество — количество
  приобретенных единиц товара.
Создайте список всех покупателей, а для каждого покупателя подсчитайте количество приобретенных им единиц каждого вида товаров.
  Список покупателей, а также список товаров для каждого покупателя
  нужно выводить в лексикографическом порядке.

Задачу я решил, только не знаю как реализировать цикл, который будет работать, пока есть строки для ввода. Так как надо написать код для варианта, когда мы не знаем сколько точно будет введено строк.
Мое решение:
dic = {}
while True: #это неверно
    a = input().split(' ')
    if not a[0] in dic:
        dic[a[0]] = {a[1]:a[2]}
    else:
        if not a[1] in dic[a[0]].keys():
            dic[a[0]].update({a[1]:a[2]} )
        else:
            dic[a[0]][a[1]]=int(dic[a[0]][a[1]]) + int(a[2])

for x in sorted(dic.keys()):
    print(x +':')
    for y in sorted(dic[x].keys()):
        print (y, dic[x][y])

A: Читать данные в вашем случае нужно немного иначе.
Сделайте такой импорт
from sys import stdin

Так вы получите доступ к стандартному потоку ввода.
Пройтись в цикле по всем строкам можно таким образом:
for i in stdin:
    //

A: Решил таким образом:
def Example(Path_File):
    with open(Path_File, 'r') as file: # Открываем файл
        lines = [line.strip() for line in file.readlines() if line != '\n'] # Делаем список из строк файла
        result = dict() # Делаем пустой словарь, тут будет результат
        for i in lines: # Проходим по списку строк который сделали
            time_var = i.split() # Разбиваем строку i на список из 3 элементов, а именно
                                 # 1 элементом будет Имя, 2 элементом - Товар, 3 элементом - Кол-во
            if time_var[0] not in result.keys():
                # Проверяем есть ли ключ с менем time_var[0] (Там имя покупателя) в нашем словаре
                result[time_var[0]] = {time_var[1]: int(time_var[2])} # Добавляем его
            else: # В противном случае
                if time_var[1] in result[time_var[0]]: # Если у покупателя есть такой товар
                    result[time_var[0]][time_var[1]] += int(time_var[2]) # Увеличиваем кол-во этого товара
                else: # В противном случае
                    result[time_var[0]].update({time_var[1]: int(time_var[2])}) # Добавляем ему этот товар
    return result # Возвращаем результат

Использование:
print(Example(r'C:\Users\user\Desktop\test\bd_file.txt'))

В bd_file.txt я поместил следующее:
Ivanov paper 10
Petrov pens 5
Ivanov marker 3
Ivanov paper 7
Petrov envelope 20
Ivanov envelope 5

Результат:
{
    'Ivanov': {
        'paper': 17,
        'marker': 3,
        'envelope': 5
    },
    'Petrov': {
        'pens': 5,
        'envelope': 20
    }
}

A: Решил задачу благодаря совету Кирилла Малышева использовать sys.stdin, вот мой код:
from sys import stdin
# Используются вложенные в друг друга словари
# Словарь покупателей (sales). Ключ = имя покупателя, значение = словарь покупок
# Словарь покупок. Ключ = название предмета, значение - количесвтво
sales = {}
for line in stdin.readlines():
    person, product, amount = line.split()
    amount = int(amount)
    if sales.get(person) == None:
        sales[person] = {}
    sales[person][product] = sales[person].get(product,0) + amount
# Сортируем покупки и преобразуем в список используя генератор списков
sales = [(s, sorted([(j, sales[s][j]) for j in sales[s]])) for s in sales]
# Выводим
for person in sorted(sales):
    name, products = person[0], person[1]
    print(name, end=":\n")
    for p in products:
        print(*p)

A: Чтобы читать ввод построчно, пока он не закончится, можно использовать sys.stdin файловый объект. Любое API, которое файл ожидает, примет этот объект (детали могут зависеть, чему в вашем окружении sys.stdin присвоен -- это может не "настоящий" файл). К примеру, sys.stdin можно передать в pandas.read_table():
#!/usr/bin/env python
import sys
import pandas as pd  # $ pip install pandas

df = pd.read_table(sys.stdin, delim_whitespace=True,
                   names=['buyer', 'product', 'amount'])
print(df.groupby(['buyer', 'product']).sum())

Для примера ввода из ответа @Alban, этот код выводит:
$ python . <input.txt
                 amount
buyer  product
Ivanov envelope       5
       marker         3
       paper         17
Petrov envelope      20
       pens           5

Файлы в Питоне являются итераторами над строками, поэтому их можно в for-цикл как есть передать for line in sys.stdin:. Чтобы принимать ввод как из стандартного ввода так и из файлов, указанных в командной строчке, можно fileinput.input() использовать:
#!/usr/bin/env python
import fileinput
from collections import Counter

counter = Counter()
for line in fileinput.input():
    buyer, product, amount = line.split()
    counter[buyer, product] += int(amount)

Что на том же вводе приводит к:
Counter({('Petrov', 'envelope'): 20,
         ('Ivanov', 'paper'): 17,
         ('Petrov', 'pens'): 5,
         ('Ivanov', 'envelope'): 5,
         ('Ivanov', 'marker'): 3})

Чтобы напечатать в желаемом отсортированном виде:
last_buyer = None
for (buyer, product), amount in sorted(counter.items()):
    if last_buyer != buyer:  # new buyer
        print(buyer, end=' ')
        last_buyer = buyer
    else:
        print(' ' * len(buyer), end=' ')
    print(product, amount)

Результат:
Ivanov envelope 5
       marker 3
       paper 17
Petrov envelope 20
       pens 5

A: from collections import defaultdict
from sys import stdin

clients = defaultdict(lambda: defaultdict(int))
for line in stdin.readlines():
    client, thing, value = line.split()
    clients[client][thing] += int(value)

for client in sorted(clients):
    print(client + ':')
    for thing in sorted(clients[client]):
        print(thing, clients[client][thing])


text:
Q: Can docpad-plugin-ghpages be hosted on GitHub Pages? I am Thinking of moving my Jekyll site to Docpad and was reading through documentation but was unclear on whether I could use docpad-plugin-ghpages with project pages for organistions where GitHub pages hosts at orgname.github.io/projectname
For example my current website (on GitHub at https://github.com/jesusdiedforme/jesusdiedfor.me) is hosted at jesusdiedforme.github.io/jesusdiedfor.me (then CNAMEd to my domain)
Any help would be appreciated thanks
ian

A: Yes! You can use docpad-plugin-ghpages to generate a site for GitHub Organization pages as well.  There is nothing specific to personal pages, just substitute https://github.com/username/username.github.io.git for https://github.com/organization/organization.github.io.git.


text:
Q: java mail classcastexception during getcontent When i am trying to retrieve gmail content through getcontent() method i am getting following exception
java.lang.ClassCastException: com.sun.mail.imap.IMAPInpustream cannot be cast to javax.mail.Multipart
So I converted the inputsream to string but it ios reurning all the data including which is not text/html. But i want only text/html data with attachment if any.
My code:
if(contentType.contains("multipart/alternative") || contentType.contains("multipart/MIXED")){
            Log.i("content type...","inside if stmt "+contentType);
            Multipart mp = (Multipart)gmsg.getGmailContent();
            try {
                for(int k=0;k<mp.getCount();k++){
                      javax.mail.BodyPart p = mp.getBodyPart(k);
                      if("text/html".equals(p.getContentType())){
                         /* gContent.loadDataWithBaseURL("https://mail.google.com",
                                  p.getContent().toString() , "text/plain","UTF-8", null); */
                          Log.i("msg", p.getContent().toString());
                      }
                    }
            } catch (MessagingException e) {
                // TODO Auto-generated catch block
                Log.i("error", e.toString());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

I have included mail.jar,activation.jar,additional.jar in libs folder.
Searched in google a lot but didn't get any solution.
Plz help..Thanks in advance..

A: If you want to read strings then:
Replace
if("text/html".equals(p.getContentType())){

with
if("text/plain".equals(p.getContentType())){

A: You really should use the isMimeType method.  Did you find the msgshow.java demo program?
The getContent method may not be able to convert the data to the correct Java class if the JavaBeans Activation Framework (JAF) configuration isn't working properly.  JAF looks for META-INF/mailcap files to figure out how to convert MIME types to Java classes.  There's such a configuration file in the JavaMail jar file.  If the jar files are messed up, the configuration files are missing, or the class loader isn't working right to allow you to load these configuration files, the conversion won't work.
Also, the workaround here might help.


text:
Q: rails form to send to my email address On submission of the contact form in my app I am looking to have the form data be sent to my email.
I looked into using action mailer, but on the rails guides it shows configurations for an automated email from you to a new user on signup.
Is there a potential solution out there using simple form?
I can create the form, just need a little help with configuration so it sends to my email.
I appreciate any advice!

A: You can just do it like a normal form, submit request to your rails server. Then your server collect the data and send email to you using ActionMailer.
If you don't want to do like that, maybe this GEM can help you:
https://github.com/plataformatec/mail_form


text:
Q: Removed Archer example from wikipedia. I have question about example illustration Convergence of random variables in probability but not almost surely.

Suppose a person takes a bow and starts shooting arrows at a target. Let $X_n$ be his score in $n$-th shot. Initially he will be very likely to score zeros, but as the time goes and his archery skill increases, he will become more and more likely to hit the bullseye and score $10$ points. After years of practice the probability that he hit anything but $10$ will be getting increasingly smaller and smaller and will converge to $0$. Thus, the sequence $X_n$ converges in probability to $X = 10$.
Note that $X_n$ does not converge almost surely however. No matter how professional the archer becomes, there will always be a small probability of making an error. Thus the sequence $(X_n)$ will never turn stationary: there will always be non-perfect scores in it, even if they are becoming increasingly less frequent.

https://en.wikipedia.org/w/index.php?title=Convergence_of_random_variables&diff=879355996&oldid=879219919
For me this example is true. But not for 69.181.249.190. Why? You have any idea?

69.181.249.190 talk 36,722 bytes -957 →Convergence in probability: removed false archer example

A: The archer example incorrectly suggests that if there is always a small-but-positive probability of missing the target, then the archer misses infinitely often.
Counter-example: Consider $\{X_n\}_{n=1}^{\infty}$ with:
$$X_n=\left\{\begin{array}{}
10  & \mbox{ with prob $1-1/2^n$}\\
0& \mbox{ else (miss target)}
\end{array}\right.$$
We don't care about independence but you can assume the variables are mutually independent if you want. We observe
$$\sum_{n=1}^{\infty}P[X_n\neq 10]<\infty$$
So by the Borel-Cantelli lemma we conclude that (with prob 1) we miss only finitely often. So $X_n\rightarrow10$ both in probability and with prob 1.

On the other hand, if the variables are mutually  independent with
$$P[X_n=10]=1-1/n, P[X_n=0]=1/n$$
then we can conclude (either by Borel-Cantelli or by direct calculation) that we miss infinitely often with prob 1. This is a classic example where $X_n\rightarrow10$ in probability but not with prob 1.
Overall, it depends on the rate at which the miss probabilities converge to zero.


text:
Q: cleaning up after an exception I have a code such as this:
class myclass
{
     myclass()
     {
        // doing some init here
      }
     ~myclass()
     {
        // doing some important clean up here
     }
     void Do()
     {
          //    doing some work which may throw exception
      }
}

and I am using this class in this way:
MyFunction()
{
    myclass mc;
    mc.do();
 }

My question is :
If there is an exception in do function, what would happen? Is destructor of myclass called?
If no, what is the best way to handle this type of situations? Assume that I don't have the source code and I am sure about what is happening in destructor.

A:
If there is an exception in do function, what would happen?

If you have any handler, it will be handled.

Is destructor of myclass called?

Yes, definitely. The standard quotes this::

An object of any storage duration whose initialization or destruction
  is terminated by an exception will have destructors executed for all
  of its fully constructed subobjects (excluding the variant members of
  a union-like class), that is, for subobjects for which the principal
  constructor (12.6.2) has completed execution and the destructor has
  not yet begun execution. Similarly, if the non-delegating constructor
  for an object has completed execution and a delegating constructor for
  that object exits with an exception, the object's destructor will be
  invoked. If the object was allocated in a new-expression, the matching
  deallocation function (3.7.4.2, 5.3.4, 12.5), if any, is called to
  free the storage occupied by the object.

This whole process is known as "stack unwinding":

The process of calling destructors for automatic objects constructed
  on the path from a try block to a throw-expression is called "stack
  unwinding." If a destructor called during stack unwinding exits with
  an exception, std::terminate is called (15.5.1).
C++11 15.5.1 The std::terminate() function [except.terminate]
2 … In the situation where no matching handler is found, it is
  implementation-defined whether or not the stack is unwound before
  std::terminate() is called.

A: If the exception is caught somewhere, then stack unwinding will guarantee that the destructor is called for this object (and, in general, all automatic variables that go out of scope as a result of the exception). This is a very important guarantee, without which we could not use techniques like RAII to write exception-safe code.
If the exception is not caught, then the program will be terminated, and it's implementation-dependent whether or not the stack will be unwound first. If it's important to destroy the object cleanly even in that situation, then one option is to catch and rethrow the exception, outside the object's scope.
If the program is ended in some other way, e.g. by calling exit() or terminate(), or receiving an unhandled signal, then the stack won't be unwound. If you need clean destruction in these situations, then things will get messy.

A: C++ does not have explicit "finally" clauses like many other languages, but instead you rely in "RAII" which essentially is a technique of using scoped "automatic" variables and relying on the fact that their destructor will get called at the appropriate moment when they go out of scope.
In your case the destructor of myclass will be called even if mc.do() throws an exception. In a lot of these "closure" issues, the object you put at the top of the scope block is a class that is used only for the purpose of invoking the destructor on termination.
The "D" language comes with a special closure syntax. There have been attempts to write libraries that do that in C++ and with lambdas it is certainly easier to write than now than it used to be although I do not think they are a formal part of C++ as yet.


text:
Q: maven tycho can not resolve project dependency I try to build my eclipse plugin-in projects by maven tycho, but it shows "cannot resolve dependencies", here are details:

*

*I have two projects, one plug-in project "A", one java project "B", "A" reference the "B" indeed.

*I write pom for them, after running "mvn package", it shows information like this.
Cannot resolve project dependencies:
    Software being installed: A 1.0.0.qualifier
    Missing requirement: A 1.0.0.qualifier requires "bundle B 0.0.0" but it could not be found.