text:
Q: How to check checboxes in a php table? So I have a guestlist in a PHP table, but I want to check the guests that have arrived.
$sql='SELECT * FROM guestlist LIMIT ' . $this_page_first_result . ',' .  $results_per_page;
$result = mysqli_query($connect, $sql);

echo "

ID	Name	Surname	Check-in
";
while($row = mysqli_fetch_array($result)) {
    echo "
" . $row["id"]. "
            " . $row["name"]. "
             " . $row["surname"]. "
            <input type='checkbox' class='get_value' name='checkbox'  ".$row["check-in"]. ">
            <input type='submit' name='submit' value='submit' ".$row["submit"]. ">

";
}
echo "
";

A: I do not know what $row['check-in'] contains but you just need use html checked:
if($row["check-in"]=='on'){
    $checked=" checked='checked'";
}else{
    $checked='';
}
echo "<input type='checkbox' class='get_value' name='checkbox'  ".$checked.">	";

Edit: to use in loop:
echo "<input type='checkbox' class='get_value' id='checkbox[]' name='checkbox[]'  ".$checked.">	";


text:
Q: Array Index Out Of Range - Error when optional unbinding I have an entity called Settings with an attribute called backgroundColor of type Int, if it is 1 then the view controller will have a background of white if 0 then a background of dark grey.
But I am getting the following error when trying to open the view controller;

fatal error: Array Index out of range

For the following line in my function
    if settingsArray.count == 1 {
        setting = settingsArray[1]
    } else if settingsArray.count <= 0 {
      println("No settings in array")
    }

View Controller
var settingsArray: [Settings]!
var setting: Settings!
var backgroundSetting: Bool = true

override func viewWillAppear(animated: Bool) {
    backgroundSettings()
}

override func viewDidLoad() {
    super.viewDidLoad()
    backgroundSettings()
}

// Function to fetch settings and change background
func backgroundSettings() {

    var error: NSError?
    let request = NSFetchRequest(entityName: "Settings")
    self.settingsArray = moc?.executeFetchRequest(request, error: &error) as! [Settings]

    if settingsArray.count == 1 {
        setting = settingsArray[1]
    } else if settingsArray.count <= 0 {
      println("No settings in array")
    }

    if setting != nil {

        if setting.backgroundColor == 1 {
            backgroundSetting = true
        } else if setting.backgroundColor == 0{
            backgroundSetting = false
        }

    }

    if backgroundSetting == true {
        self.view.backgroundColor = UIColor.whiteColor()
    } else if backgroundSetting == false {
        self.view.backgroundColor = UIColor.darkGrayColor()
    }

}

//Button to change the color and settings
@IBAction func backgroundColor(sender: AnyObject) {

    if setting != nil {

        if setting.backgroundColor == 1 {
            setting.backgroundColor = 0
        } else {
            setting.backgroundColor = 1
        }

        var error: NSError?
        moc?.save(&error)

    } else {

        println("No settings available")

        var settings = NSEntityDescription.insertNewObjectForEntityForName("Settings", inManagedObjectContext: moc!) as! Settings

        settings.backgroundColor = 1

        var error: NSError?
        moc?.save(&error)

    }

    backgroundSettings()

}

Any ideas where I may be going wrong ?

A: In Swift (as in Objective C and many other languages), the indexes of arrays start at 0. (See this wikipedia article for a list on this.)
This means when you check if settingsArray.count == 1, there will be only (exactly) one item in your list. Since indexes start at 0, this item will be at index 0, hence the Error.
So either you check if settingsArray.count == 2 and leave setting = settingsArray[1], or you change to setting = settingsArray[0].

A: ETA:
I have been having another think about this. I have left my old answer below so that the previous comments make sense.
In if let thisSetting = settingsArray?[0] … if settingsArray is nil then the right side is potentially effectively nil[0]. Therefore I believe that this may eliminate the crash:
// ...
if !settingsArray.isEmpty {
    if let thisSetting = settingsArray?[0] {
        setting = thisSetting
    }
}

settingsArray[0] being nil would I think then be a separate issue. Which I think would relate to the lifecycle.
Previous answer follows:
I believe that the problem may be being caused by you calling func backgroundSettings() from viewDidLoad() - i.e. too early in the View Controller lifecycle - and before the values have been initialized.

redpajama_set_name: RedPajamaStackExchange


text: Q: From Hamilton-Jacobi to Hamilton-Jacobi-Bellman I have been reading Gelfand's "Calculus of variations" book up to the chapter that talks about the Hamilton-Jacobi equation. Is it easy to transition from there to the Hamilton-Jacobi-Bellman? or are those two things completely different? What is a reference for that?


text:
Q: Target of URI doesn't exist: 'package:meta/meta.dart' I`m using the flutter plugin of here to execute de hello_map_app example.
I follow the instructions of  https://developer.here.com/documentation/flutter-sdk-navigate/4.8.1.0/dev_guide/topics/quick-start.html
to I did flutter pub get, restarted Android studio but I have errors in the pluggin.
Errors reported in Android Studio Dart Analisis

A: Can you please directly import the hello_map example from this link - https://github.com/heremaps/here-sdk-examples/tree/master/examples/latest/explore/flutter
Unzip the HERE SDK for Flutter plugin to the plugins folder that can be found inside the example app project. Rename the folder to 'here_sdk': hello_map/plugins/here_sdk
Set your HERE SDK credentials to
hello_map/android/app/src/main/AndroidManifest.xml
hello_map/ios/Runner/Info.plist
Please Note Following:
Your IDE should use -
Flutter 2.2.2
Dart version 2.13.3
Newer versions may also work, but are not guaranteed to work. The Flutter version 2.0.6 and Dart 2.12.0 are also supported. It is recommended to use the Dart version that is bundled with Flutter.


text:
Q: How to exclude an item in Django loop? Hopefully just a quick question. I am having some difficulty wrapping my mind around to using Django loop function. I have a simple page which is fetch some data from db. Everything seems fine although loop function melting my mind.
Simply my loop:
{% if books %}
{% for reader in books %}
{{ reader.title }}
{{ reader.booknumber|default_if_none:"" }}
 {% endfor %}
{% else %}

My result like:
Elena 141
Elena
M.Mary 1035
P.Paul 141
P.Paul
T.Mark 741
T.Mark
T.Mark

My Expect result like:
Elena 141
M.Mary 1035
P.Paul 141
T.Mark 741

Thats because some of booknumber cell is emtpy in my db. I just wonder how do i put them out of loop? I'm using defult_if_none func for hide "None" but didnt find a way for hiding\excluding title (if doesnt have booknumber). I really appreciate if someone could help me out. Thank you in advance.

A: try this
{% if books %}
   {% for reader in books %}
      {% if reader.title and reader.booknumber %}
         {{ reader.title }}
        {{ reader.booknumber|default_if_none:"" }}
      {% endif %}
    {% endfor %}
{% endif %}

More about Django templates
https://docs.djangoproject.com/en/3.1/ref/templates/builtins/

A: c.grey has the right answer but you really should be doing this processing in your views file using __isnull:
SomeModel.objects.filter(booknumber__isnull=False)


text:
Q: equivalent of within(), attach() etc. for working within an environment? I want to add an environment to a search path and modify the values of variables within that environment, in a limited chunk of code, without having to specify the name of the environment every time I refer to a variable: for example, given the environment
ee <- list2env(list(x=1,y=2))

Now I would like to do stuff like
ee$x <- ee$x+1
ee$y <- ee$y*2
ee$z <- 6

but without appending ee$ to everything (or using assign("x", ee$x+1, ee) ... etc.): something like
in_environment(ee, {
    x <- x+1
    y <- y+2
    z <- 6
})

Most of the solutions I can think of are explicitly designed not to modify the environment, e.g.

*

*?attach: "The database is not actually attached.  Rather, a new environment
is created on the search path ..."

*within(): takes lists or data frames (not environments) "... and makes the corresponding modifications to a copy of 'data'"

*There are two problems with <<-: (1) using it will cause NOTEs in CRAN checks (I think? can't find direct evidence of this, but e.g. see here — maybe this only happens because of the appearance of assigning to a locally undefined symbol? I guess I could put this in a package and test it with --as-cran to confirm ...); (2) it will try to assign in the parent environment, which in a package context [which this is] will be locked ...

I suppose I could use a closure as described in section 10.7 of the Introduction to R by doing
clfun <- function() {
   x <- 1
   y <- 2
   function(...) {
      x <<- x + 1
      y <<- y * 2
   }
}
myfun <- clfun()

This seems convoluted (but I guess not too bad?) but:

*

*will still incur problem #1 (CRAN check?).

*I think (??) it won't work with variables that don't already exist in the environment (would need an explicit assign() for that ...)

*doesn't allow a choice of which environment to operate in - it's necessarily going to work in the enclosing environment, not with arbitrary environment ee
Am I missing something obvious and idiomatic?

A: Thanks to @Nuclear03020704 ! I think with() was what I wanted all along; I was incorrectly assuming that it would also create a local copy of the environment, but it only does this if the data argument is not already an environment.
ee <- list2env(list(x=1,y=2))
with(ee, {
    x <- x+1
    y <- y+2
    z <- 6
})

does exactly that I want.

Just had another idea, which also seems to have some drawbacks: using a big eval clause. Rather than make my question a long laundry list of unsatisfactory solutions, I'll add it here.
myfun <- function() {
    eval(quote( {
        x <- x+1
        y <- y*2
        z <- 3
    }), envir=ee)
}

This does seem to work, but also seems very weird/mysterious! I hate to think about explaining it to someone who's being using R for less than 10 years ... I suppose I could write an in_environment() based on this, but I'd have to be very careful to capture the expression properly without evaluating it ...

A: What about with()? From here,

with(data, expr)
data is the data to use for constructing an environment. For the default with method this may be an environment, a list, a data frame, or an integer.
expr is the expression to evaluate.
with is a generic function that evaluates expr in a local environment constructed from data. The environment has the caller's environment as its parent. This is useful for simplifying calls to modeling functions. (Note: if data is already an environment then this is used with its existing parent.)
Note that assignments within expr take place in the constructed environment and not in the user's workspace.
with() returns value of the evaluated expr.

ee <- list2env(list(x=1,y=2))
with(ee, {
    x <- x+1
    y <- y+2
    z <- 6
})


text:
Q: Integral cohomology ring of K(Z,3) Computing the cohomology of Eilenberg Maclane spaces is a feasible but difficult problem in algebraic topology. The general answer is quite complicated (see the MO answer and the reference therein https://mathoverflow.net/a/24759/184 )
However the cohomology of K(Z,2) is quite simple, it is just a polynomial algebra on a generator in degree two. I am wondering about the next easiest case.

What is the integral cohomology ring of K(Z,3)?

You can get quite far with spectral sequence calculations, but if this is worked out in detail somewhere, why reinvent the wheel?

A: Given a complex oriented cohomology theory $E$, one can define a formal scheme of Weil pairings on the associated formal group, as explained in the paper "Weil pairings and Morava $K$-theory" by Matthew Ando and me.  If we let $R_E$ denote the ring of functions on this scheme, then there is a natural map $R_E\to E^*K(\mathbb{Z},3)$.  This is an isomorphism if $E$ is Morava $K$-theory or Morava $E$-theory.  I think that it is also an isomorphism for $E=MU$ or $E=kU$ but not for $E=H$.  However, there is a natural short exact sequence
$$ kU^*K(\mathbb{Z},3)/v \to H^*K(\mathbb{Z},3) \to \text{ann}(v,kU^*K(\mathbb{Z},3)) $$
(where $v$ is the standard generator of $\pi_2kU=kU^{-2}(\text{point})$).  I think that this is probably an effective way to understand $H^*K(\mathbb{Z},3)$.
Some other things that are going on in the background here:

*

*There is a fibration $K(\mathbb{Q}/\mathbb{Z},2)\to K(\mathbb{Z},3)\to K(\mathbb{Q},3)$.  Here $K(\mathbb{Q},3)$ is the rationalisation of $S^3$ and is not so hard to understand.

*$K(\mathbb{Q}/\mathbb{Z},2)$ is the colimit of the spaces $K(\mathbb{Z}/n,2)$.

*One can understand $K(\mathbb{Z}/n,2)$ using the multiplication map $K(\mathbb{Z}/n,1)\times K(\mathbb{Z}/n,1)\to K(\mathbb{Z}/n,2)$.


text:
Q: How can I pass methods in javascript? I often need to pass methods from objects into other objects. However I usually want the method to be attached to the original object (by attached I mean 'this' should refer to the original object). I know a few ways to do this:
a) In the object constructor: ObjectA = function() { var that = this; var method = function(a,b,c) { that.abc = a+b+c }}
b) In objectA which has been passed objectB: objectB.assign(function(a,b,c) { that.method(a,b,c) })
c) Outside both objects: objectB.assign(function(a,b,c) { objectA.method(a,b,c) })
I want to know if there is a simpler way to pass methods attached to their original objects.

A: You can define a "createDelegate" method for all functions:
Function.prototype.createDelegate = function(scope) {
    var method = this;
    return function() {
        return method.apply(scope, arguments);
    }
}

And then use like:
var myDelegate = myFunction.createDelegate(myScope);

calling "myDelegate" will execute "myFunction" with "this" pointing to "myScope" and the same arguments as passed to myDelegate

A: As long as you call the other method with its appropriate owner object, this will always refer to the correct owner.

A: You can delegate if you like, or just call the object that lacks the method from the defined method scope-
instance.method.call(Other-Object/*,argument,...*/)

For example, if Array has a filter method, you can call it as if it were a method of a node list object.
var list=document.getElementsByTagName('p'), a=[],

list= a.filter.call(list,function(itm){return itm.className=='sidebar'});


text:
Q: Как получить Instagram access_token в правильном формате? После авторизации в Instagram я получаю access_token но проблема в том что я получаю его в следующем формате:
/auth#access_token=token
Я пытаюсь забрать его из GET, но падает ошибка. Можно как-то получить токен вида /auth?access_token=...

A: Ответ очень прост - никак, нужно использовать библиотеки для интеграции инсты с Laravel что бы уже в контроллере получать данные. Или можно заняться идиотизмом и js-сом выгребать адрес строки и получать ключ, но основня проблема ждет когда проходишь по ссылке - по факту в адресной строке появляются 2 одинаковых ключа.


text:
Q: Determine what kind of encoding is used on a file? I have a file that I believe to be an XML type file but when I change the extension to TXT and open it through a text editor I get
.�2�'��7cõ'¥¶_ä™πUUUN?¯ÖÀuóbåqW÷õxó_i}Ï08Y'û¡d≈§•§è«/Óÿ`*∆cÅ·x…ëë«Öµ¶fi—

Is there anyway to determine what kind of encoding is being used?
EDIT:
The file is a ptx file used for legal deposition software. I am trying to create a reader for the mac.
This is contents of the file from a hex editor.
1D 2E 01 00 08 32 01 00 27 05 00 00 02 37 63 9B D5 B4 A6 5F 8A AA B9 55 55 55 4E 3F F8 85 CB 75 97 62 03 8C 71 57 D6 9B 78 97 5F 69 7D EC 30 38 59 E2 9E C1 64 C5 A4 A5 A4 8F C7 2F EE D8 60 2A C6 63 81 E1 78 C9 07 91 91 C7 85 B5 A6 DE D1 0D 00 B2 03 99 27 0E 07 E2 3A 22 13 23 0C 4A 14 6C 0A AF 3E 29 53 AA 7E AE C3 3B 01 F6 11 14 27 74 3A C0 D7 D5 D7 22 27 18 55 B7 53 2A 5D 84 5E 3B F7 50 36 07 0C 30 1E F9 D4 FB C1 D7 02 5D 80 F6 85 6D 9C 30 1C 98 B0 C2 74 42 37 8F 76 F0 A4 D7 90 88 09 D1 2A 88 E6 56 BD 41 F5 C3 B2 08 05 8F 15 3B B8 E4 8C 59 2D 12 51 F4 68 7A 15 7A C3 D2 AB 87 68 84 FF 5E 7C 18 D7 21 0F E2 C4 D7 FC 4F B6 1B BC E2 7C 9C 6D FE DA C4 CB E3 60 C3 33 63 74 E6 B7 AB 6A DE B3 9F D2 6E E1 47 51 3B 0B CE EE 6E 21 A1 3C 26 6D A1 59 08 63 93 14 D3 CB 22 F9 E3 A8 E6 9F 8A 69 D7 44 93 4B AE 4D 49 C2 4F 06 7C AD 1D FC 0E C3 B7 CB 75 EB 87 74 84 FE 4F A5 5F 80 9F B3 F4 2A 7B 20 9A 54 73 5E 81 F8 B2 F8 5D 88 D7 8A EB 99 49 2E F7 F0 2B 0C 2F D8 CB 13 D6 21 35 5E 45 F7 53 61 E7 76 8E 5E F5 CB BC 2F 21 F4 8D 91 A3 82 79 A9 DF E0 1B 2E 38 D1 09 C9 2C 78 E9 E3 93 91 8D 7F 27 BE F7 45 B6 EA C0 A7 99 89 92 EF 2E 5A 39 AC CD 70 EF 90 9F CF A5 57 AC 55 D8 62 7E 02 D0 67 84 D1 21 29 B0 E9 94 59 7C 96 FE F1 3F 80 3D 9D 42 61 E1 AB 44 3C 55 70 F1 87 BB F3 2E BC FE 04 24 F5 11 55 6B 36 5D BE 54 F6 EB 63 B8 88 20 0F 25 4E 7E 50 DA CA E6 F2 E8 60 E9 0A A4 E1 65 C2 DC 05 D1 4C FB CB 2D 28 79 91 B3 87 75 93 8E B3 43 69 C7 35 73 E3 3E B5 CD 4B 62 B6 F8 5B 2D A9 B3 73 4F 4C 78 8B AC 3C C0 21 5B 97 45 E3 A8 57 2A D4 D3 70 7E 22 9A 27 63 28 0F 38 6C 67 B2 29 A6 42 83 AD 15 DE CE 5E 95 CA 2F 48 CD F9 9A E6 C6 D0 F4 06 96 62 F8 98 58 ED 43 27 B9 9A DB 4B 21 69 6B CB A6 58 F8 09 C5 31 07 A4 3D F9 CD 4C C9 CB 6F 64 8E AA 15 0D 39 27 5B 2E 7C 2D 5B 0F 55 54 AB D7 57 0D 10 CC AA FC 87 D0 FF 7C 01 05 00 00 02 5E 63 BB D1 A6 A6 5F E5 55 51 55 55 55 77 8F FF 1A 92 50 86 CC D9 C6 DE 2A DB 52 DD 29 78 97 BA AC DB C2 CE 03 80 E8 87 52 53 AE 66 F8

A: Doesn't look like an common charset. Almost any encoding preserves ASCII characters in some form.
So I see a few possibilities:

*

*The file in a compressed text/xml file

*The file in a encrypted text/xml file

*It's a binary file format

*It's obfuscated

Now if we look at it we see sequences with repeated characters like "UUU" and "ëë" occur quite often. Since encrypted data appears completely random this makes the second option unlikely.
What makes you think that this should be an xml file? And since the file is binary you might want to post the beginning of the file in hex instead of text.
Looking at your hex-dump I'm pretty sure it's not encrypted. And sequences like "01 00" are typical for an uncompressed binary format. So that's my best guess.

Writing a parser from just a sample file is rather hard. First thing I'd try is looking for a format specification on the net.
If you try to figure out a file format you can either start reversing the application creating them(That's rather hard if the program is compiled to assembly, and rather easy for byte-code such as java or .net use).
Or you start with a simple file. Make minimal changes to it in the program and compare the differences in the file. That's a lot of work, and only possible for rather simple file formats.

I couldn't find a specification when searching a bit. And there seems to be only a single implementation. You could try contacting the company who created it, but I somehow doubt they'll help. So I guess you need to reverse engineer the format yourself. That's probably not easy and quite a bit of work. Good look.


text:
Q: Linear Algebra Hint. Linear Transformation Consider a linear transformation $A: \mathbb{R}^{m} \longrightarrow \mathbb{R}^{n}$. I have to prove equivalence of 6 claims. I I couldn't prove one implication.

$$|Ax - Ay| = |x - y| \Longrightarrow \langle Ax, Ay \rangle = \langle x, y \rangle$$

Any hint? I didn't want the solution.

A: HINT
$$|Ax-Ay|=\sqrt{\langle Ax, Ay \rangle\langle Ax, Ay \rangle}$$

A: Note that from the assumptions,
$$|Ax| = |Ax - A0| = |x - 0| = |x|.$$
Fix $x, y \in \mathbb{R}^m$. Then
\begin{align*}
&|x - y|^2 = |Ax - Ay|^2 \\
\implies \, &|x|^2 + |y|^2 - 2\langle x, y\rangle = |Ax|^2 + |Ay|^2 - 2\langle Ax, Ay\rangle \\
\implies \, &2\langle x, y\rangle = 2\langle Ax, Ay\rangle.
\end{align*}


text:
Q: using incremented variable in echo statement batch file without modifying it again and again I am using command prompt in windows 7 but my question should apply for any windows version xp and above.
I am using a variable but want to echo incremented value in an echo statement .
Currently , I increment then echo then decrement variable as shown below
set /a count=<some value>
set /a count+=1
echo %count%
set /a count-=1
Process count having <same value>

I hope there is a better way to increment the value of the variable by just using echo.
Thanks.

A: You want something effectively like echo %count%+1? No, this won't work. The only way to do math in cmd is the set /a command.
I personally won't touch my original variable but use a dummy var;
set /a xcount=count+1
echo %xcount%

(just a thing of personal preference).
What actually would work:
set /a count=5
cmd /c set /a x=count+1
cmd /c set /a x=count+1 & echo/ this is plus one
cmd /c "<nul set /p "x=%Count% plus one is " & set /a x=count+1 &echo/. Ready."
echo %count% is still 5

because the set command is then done (in a new process) directly "on the command line" and set /a shows the result when done on the command line (but doesn't show the result in a batch file).
Contra: It's quite easy to show just the number (first cmd... line), but if you want to put some text "around", it quickly gets ugly (second line to append text, third line to put text around the number). And you open a new process. If you do it in a loop (as the variable name count suggests), it may slow down your script considerably.

A: You could use delayed expansion, via SETLOCAL and ENDLOCAL, without creating an intermediate variable or running another instance of cmd.exe.
Rem Ensure extensions are enabled for SET /A functionality
Rem  and disable delayed expansion.
SetLocal EnableExtensions DisableDelayedExpansion
Rem Define variable named count with the string value of an integer
Set "count=5"
Rem Print the value
Echo %count%
Rem Enable delayed expansion
SetLocal EnableDelayedExpansion
Rem increment the variable value
Set /A count += 1
Rem Print the new value
Echo !count!
Rem Discard variables defined or modified during previous SETLOCAL
EndLocal
Rem Print the value
Echo %count%
@Rem Optional PAUSE for GUI invoked script
@Pause

A: A for /f loop is another means that avoids delayed expansion or setlocal / endlocal which can be used to get offset values without modifying the original count:
@Echo off
For %%O in (+ -)Do for /f "Delims=" %%G in ('Set /A "count%%O=1"')Do Echo(%Count% %%O 1 = %%G


text:
Q: Can you get a similarity percentage between items using ElasticSearch? I'm considering using ElasticSearch to hold, search and get statistics on data but I'm not sure if what I would like to do is possible or not.
The main goal would be to get the percentage of similarity between items stored in the database. For example, given the two following identical objects:
{'Item A': [{'name':'bob', 'age':20}]}, {'Item B': [{'name':'bob', 'age':20}]}

I would like to compute something like this:
Item ID1 | Item ID2 | Matching percentage
 Item A   | Item B   | 100
Does ElasticSearch allow for such computations, looking for similarity percentage between fields of two given objects ? If not what would you suggest ?
Thank you for your time,
Oliver


text:
Q: How to get the columns index from datatable which column name contains like 'ColumnName' I have a datatable which contains columns created dynamically:
Name | Role | Comm w1 | Role | Comm w2 | .... | Total Comm |

I want to get all columns index which contains Comm.
The expected result should be:
2
4
...

A: You can use LINQ to do this fairly easily.
First we need to cast the Columns to DataColumn because LINQ needs it to be IEnumerable<DataColumn> but Columns is DataColumnCollection. Then constrict the columns to ones that contain "Comm", then select the ordinal of each column, then make that a list.
List<int> columnIndexes = dt.Columns.Cast<DataColumn>()
    .Where(column => column.ColumnName.Contains("Comm"))
    .Select(column => column.Ordinal).ToList();

A: Your question is unclear on what you want the output to be, whether you just want to print the positions of the columns to screen, or store them in a way to use them later.
Furthermore, this is a very simple solution.. if it wasn't for that then I wouldn't be participating.. so for future reference please provide what you have tried and what you are expecting.  It helps all that are involved in trying to help you find a solution.  Please reference "How to ask a good question" if you experience any trouble.
using System;
using System.Data;
using System.Xml;

public class Program
{
    public static void Main()
    {
        var dt = new DataTable { Columns = { "Name", "Role", "Comm w1", "Comm w2",  "Total Comm"}};

        foreach(DataColumn column in dt.Columns){
            if(column.ColumnName.Contains("Comm")){
                Console.WriteLine(column.Ordinal.ToString());
            }
        }
    }
}

// Output:

// 2
// 3
// 4

Let me know if this helps.

A: The below should do what you need
foreach (DataColumn col in dataTable.Columns)
{
       if (col.ColumnName.Contains("Comm"))
       {
         var index = col.Ordinal;
       }
 }

But as mentioned, it is best if you attempt something first.

A: The other answers are right, it will get you what you are asking for, but I don't think how they use them is quite right. I would do something like this:
List<int> indexes = new List<int>();
foreach (DataColumn column in dataTable.Columns)
{
    if (column.ColumnName.Contains("Comm"))
    {
      indexes.Add(column.Ordinal);
    }
}

This way you have the list of indexes afterwards to use however you wish.


text:
Q: how to use custom.cnf in mysql server 8 docker-compose file? trying to use custom configuration file in docker-compose mysql 8. The docker-compose.yml looks like
version: '3'
services:
  db:
    container_name: test-mysql8
    image: mysql/mysql-server:8.0
    volumes:
      - <host path to>/mycustom.cnf:/etc/mysql/conf.d/custom.cnf
    environment:
      - MYSQL_ROOT_PASSWORD=pass
      - MYSQL_DATABASE=testdb
      - MYSQL_USER=testuser
      - MYSQL_PASSWORD=testpassword
    ports:
      - "3306:3306"
    restart: always

  adminer:
    image: adminer:latest
    restart: always
    ports:
      - "8080:8080"

Below is the custom config file, mycustom.cnf
[mysqld]
max_allowed_packet=32M
character-set-server=utf8
collation-server=utf8_bin
transaction_isolation=READ-COMMITTED

Run the docker-compose up -d and verify the variables docker exec -it test-mysql8 bash
mysql -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.0.23 MySQL Community Server - GPL

Copyright (c) 2000, 2021, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show variables like '%max_allowed_packet';
+---------------------------+------------+
| Variable_name             | Value      |
+---------------------------+------------+
| max_allowed_packet        | 67108864   |
| mysqlx_max_allowed_packet | 67108864   |
| slave_max_allowed_packet  | 1073741824 |
+---------------------------+------------+
3 rows in set (0.00 sec)

Expecting the variable value as given in  mycustom.cnf as max_allowed_packet=33554432 instead of max_allowed_packet=67108864
I know that command can be used in compose file as below, but I want to use custom file
......
command: --character-set-server=utf8 --collation-server=utf8_bin --max-allowed-packet=32M --transaction-isolation=READ-COMMITTED
......

A: My way without config file. This is elegant when we only want to change a few parameters:
mysqldb:
    image: mysql:8.0.29
    command:
        --default-authentication-plugin=mysql_native_password
        --max_connections=666
        --bind-address=0.0.0.0
        --transaction-isolation=READ-COMMITTED
    ports:
    - 3306:3306

    environment:
    - MYSQL_ROOT_PASSWORD=pass
    - MYSQL_TCP_PORT=3399
    - MYSQL_DATABASE=appdb

    volumes:
    - mysql:/var/lib/mysql
    - mysql_config:/etc/mysql

Check this with:
mysql -uroot -ppass -h127.0.0.1 -P3306 -e 'show global variables like "max_connections"';

An alternative to the configuration files. See details https://hub.docker.com/_/mysql official mysql docker image.

A: I tried to replace image: mysql/mysql-server:8.0 with image: mysql:8.0 and this worked.


text:
Q: How to make Console App listen for keypresses from other processes? I'm new to C# programming and I'm attempting to write a Console App that will run in the background and perform an action when a key is pressed (ideally I would like to know how to do this for any key but, if that's not possible, then a specific key).
Here's an idea of what I want (please excuse and feel free to correct any bad coding as I'm just starting out).
public static void Main(string[] args)
{
    while(true)
    {
         ConsoleKeyInfo cki = Console.ReadKey();
         if( cki.Key == ConsoleKey.R )
         {
              Console.WriteLine("Run me");
         }
     }
 }

The above seems to work but only if the Console App is in focus. I would like it to happen even if the app isn't in focus.
I've done some research and read about registering 'hotkeys' but also read that this is dangerous in case another application is requiring that key?
I've also read similar questions on here but they seem to deal with Windows Forms and not just Console Apps.
Can anyone help shed any light on this?

A: You need to use
[DllImport("user32", SetLastError = true)]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
[DllImport("user32", SetLastError = true)]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

But to make it work from console you'll need to create hidden form that will handle messages for you. Check out this class. It does exactly what you want.


text:
Q: completely connected subgraphs from a larger graph in networkx I have tried not to repost here, but I think my request is very simple and I am just inexperienced with network graphs. When using the networkx module in python, I would like to recover, from a connected graph, the subgraphs where all nodes are connected to each other (where the number of nodes is greater than 2). Is there a simple way to do this?
Here is my example:
A simple graph with seven nodes. Nodes 1,2,3 are shared connections, nodes 1,2,4 all share connections, and nodes 5,6,7 all share connections.
import networkx as nx
G=nx.Graph() #Make the graph
G.add_nodes_from([1,2,3,4,5,6,7]) #Add nodes, although redundant because of the line below
G.add_edges_from([(1,2),(1,3),(2,3),(1,4),(2,4),(1,5),(5,6),(5,7),(6,7)]) # Adding the edges

My desired output would be: ([1,2,3],[1,2,4],[5,6,7])
I can think of slightly laborious methods for writing this but was wondering if there was a simple inbuilt function for it.

A: It sounds like you want to discover the cliques in your graph. For this you could use nx.clique.find_cliques():
>>> list(nx.clique.find_cliques(G))
[[1, 2, 3], [1, 2, 4], [1, 5], [6, 5, 7]]

nx.clique.find_cliques() returns a generator which will yield all cliques in the graph. You can filter out the cliques with fewer than three nodes using list comprehension:
>>> [g for g in nx.clique.find_cliques(G) if len(g) > 2]
[[1, 2, 3], [1, 2, 4], [6, 5, 7]]


text:
Q: java spring : unexpected token: * In my jpa interface, i have the following code:
public interface ConsultationRequestRepository extends CrudRepository<ConsultationRequest, Integer> {

    @Query("select * from ConsultationRequest where status = ?1")
    List<ConsultationRequest> findRequestsByStatus(ConsultationStatus status);
}

but it complains with the error:
antlr.NoViableAltException: unexpected token: *

what is wrong in this code?

A: Never forget that JPA is not SQL, even if there is similar expression.
You want to get all entries and put it into a POJO or a list so you have to specify it in your select clause, like this :
public interface ConsultationRequestRepository extends CrudRepository<ConsultationRequest, Integer> {

    @Query("select c from ConsultationRequest c where status = ?1")
    List<ConsultationRequest> findRequestsByStatus(ConsultationStatus status);
}

A: Try to change your query in the following way:
@Query("select c from ConsultationRequest c where c.status = ?1")

Or you can use native query:
@Query("select * from ConsultationRequest where status = ?1", nativeQuery = true)

More about using @Query annotation you can find here


text:
Q: Timing out randomized algorithm I have a randomized recursive backtracking algorithm to generate Sudoku puzzles (see here).  It works fast enough on average, but the worst-case runtime is unacceptably slow.  Here is a histogram of the runtime in milliseconds for 100 trials (the "More" is about 200,000 ms!):

I would like to improve the algorithm by simply timing it out after t ms, and restarting with a new random seed.  To prevent this from repeating infinitely, I would either stop after n tries or increase t after each failed try.  If t is much larger than the median, there's a good chance of getting a much faster run on a subsequent try.
Questions:

*

*How can I adjust the timeout period t for different processors? Is there a fast, reliable way to benchmark processor performance prior to each run?  Alternatively, should I adapt to the processor over several runs, for instance using the mean runtime of all previous runs?  I am running this on Android, if that's relevant.

*Is there a better strategy entirely to avoid the long tail in the distribution of the runtimes?

A: Since your algorithm is recurisve, why not establish a maximum recursion depth?  If the particular random seed leads to a recursion depth that you have empirically established to be high enough that you will hit the long tail, abort at that point.
By visual approximation, it looks like after 4500ms you will not get significant returns on your investment for the given seed.  Rerun that benchmark also tracking recursion depth, and see what that number is.  I would run more than 100 samples, though.
That solution is CPU speed independent.

A: *

*Yes there is, it is called confidence interval. By running the algorithm several time in pre-processing (or on the fly), you can determine with x% confidence (where x is a parameter) what is the interval where the median of running time lays in.
You can reduce the interval size by decreasing x or increasing the number of times the algorithm runs.
Of course if you cannot really run the algorithm itself, you can try to benchmark it on some machine and find the confidence interval (let it be I), and create some function f(I,s) that given a timing of a different algorithm (the timing of it is s) on a different machine (M), predicts what should be the interval for the machine M.
finding s is done in a similar manner - using confidence interval.

*Your approach seems fine, I'd probably do the same - I will first set up a small factor, and increase it after each failing attempt. Note that this is somehow similar to the congestion control in the TCP protocol (from the field of networks) to find the accepted rate of transfer of packages over the net.


text:
Q: How do I use switch with structs in C Hi I have the following code snippet from here:
void handleGenieEvent(struct genieReplyStruct *reply) {
    if (reply->cmd != GENIE_REPORT_EVENT) {
        printf("Invalid event from the display: 0x%02X\r\n", reply->cmd) ;
        return;
    }
    /**/
    if (reply->object == GENIE_OBJ_KEYBOARD) {
        if (reply->index == 0)  // Only one keyboard
            calculatorKey(reply->data);
        else
            printf("Unknown keyboard: %d\n", reply->index);
    } else
    if (reply->object == GENIE_OBJ_WINBUTTON) {
        /**/
        if (reply->index == 1) {    // Clock button on main display
            //do smth
        } else
        if (reply->index == 2) {
            //do smth
        } else
        if (reply->index == 0) { // Calculator button on clock display
            //do smth
        } else
            printf("Unknown button: %d\n", reply->index);
    } else
        printf("Unhandled Event: object: %2d, index: %d data: %d [%02X %02X %04X]\r\n",
      reply->object, reply->index, reply->data, reply->object, reply->index, reply->data);
}

And I am wondering if it's possible to use switch here, especially for the index
I tried this:
switch (reply->index)
    case 0:
        //do smth
    case 1:
        //do smth
    case 2:
        //do smth

but that doesn't work.

A: switch (reply->index)
{
    case 0:
      //do smth
        break;
    case 1:
     //do smth
        break;
    case 2:
     //do smth
        break;
    default:
        printf("Unknown button: %d\n", reply->index);
        break;
}

will work.
Please note that your sample should check the reply-Pointer upon function entry:
void handleGenieEvent (struct genieReplyStruct *reply)
{
    if (NULL == reply)
    {
        // report error
        return;
    }
    else
    {
        // ...
    }
}

A: In this case you should use brackets and the break statement:
switch (reply->index){ <---bracket
    case 0:
        //do smth
        break;
    case 1:
        //do smth
        break;
    case 2:
        //do smth
        break;
}<---bracket

If you want the same funcitonality as the if-else code snippet above, you need the break statements. If you miss the breaks and got case 0 for example, case 1 and 2 will execute as well.


text:
Q: How to change a color of the title of the selected tab at TabLayout? I want to change a color of this area behind the icons at TabLayout, only a line with icons. I also need to change this pink line under the title, but I can't find appropriate parameters at style. My style:
  <style name="AppTabLayout" parent="Widget.Design.TabLayout">
    <item name="tabIndicatorColor">?attr/colorAccent</item>
    <item name="tabIndicatorHeight">4dp</item>
    <item name="tabPaddingStart">6dp</item>
    <item name="tabPaddingEnd">6dp</item>
    <item name="tabBackground">?attr/selectableItemBackground</item>
    <item name="tabTextAppearance">@style/AppTabTextAppearance</item>
    <item name="tabSelectedTextColor">@color/darkPurple</item>
  </style>

  <!-- for text -->
  <style name="AppTabTextAppearance" parent="TextAppearance.Design.Tab">
    <item name="android:textSize">12sp</item>
    <item name="android:textColor">@color/orange</item>
    <item name="textAllCaps">false</item>
  </style>

A: try this use following property of  tab-layout
app:tabIndicatorColor="@color/colorBlack"// it set Selected tab underline color
app:tabSelectedTextColor="@color/colorPrimary"// it set Selected tab  text color
app:tabTextColor="@color/colorAccent"// it set tab text color

A: Add atribute in xml:
<android.support.design.widget.TabLayout
    ....
    app:tabBackground="@drawable/tab_color_selector"
    ...
    />

And create in drawable folder, tab_color_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/tab_background_selected" android:state_selected="true"/>
    <item android:drawable="@color/tab_background_unselected"/>
</selector>

A: For the tab background color, create a selector and put that selector's resource ID like:
<item name="tabBackground">@drawable/selector_name</item>.
For the pink underline, change the color in
<item name="tabIndicatorColor">@color/your_new_color</item>

A: try this

*

*Create bg_color in your drawable folder

<selector xmlns:android="http://schemas.android.com/apk/res/android">

<!-- Non focused states -->
<item android:state_focused="false" android:state_selected="false" android:state_pressed="false" android:drawable="@drawable/timecard"
    android:color="@color/colorText" />
<item android:state_focused="false" android:state_selected="true" android:state_pressed="false" android:drawable="@drawable/timecard_selected"
    android:color="@color/colorSkyBlue"/>

<!-- Focused states -->
<item android:state_focused="true" android:state_selected="false" android:state_pressed="false" android:drawable="@drawable/timecard"
    android:color="@color/colorText"/>
<item android:state_focused="true" android:state_selected="true" android:state_pressed="false" android:drawable="@drawable/timecard_selected"
    android:color="@color/colorSkyBlue"/>

<!-- Pressed -->
<item android:state_selected="true" android:state_pressed="true" android:drawable="@drawable/timecard"
    android:color="@color/colorText"/>
<item android:state_pressed="true" android:drawable="@drawable/timecard_selected"
    android:color="@color/colorSkyBlue" />

*

*and add this in your layout like this

 <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:padding="0dp"
            android:tabStripEnabled="false"
            app:tabIndicatorHeight="0dp"
            android:fitsSystemWindows="true"
            app:tabContentStart="0dp"
            app:tabBackground="@drawable/bg_color"
            app:tabPaddingStart="0dp"
            android:paddingLeft="0dp"
            app:tabPaddingEnd="0dp"
            app:paddingEnd="0dp"
            android:layout_gravity="center_vertical"
            app:tabIndicatorColor="@color/colorSkyBlue"
            android:paddingRight="0dp"
            app:tabSelectedTextColor="@color/colorSkyBlue" />


text:
Q: Remove-ADUser: -Server paramter Is there a way we can know against which server this command is executing?
I have read the documentation for the command but it says will use the default. But how can we be sure?

The default value for the Server parameter is determined by one of the
  following methods in the order that they are listed:

*

*By using Server value from objects passed through the pipeline.

*By using the server information associated with the Active Directory PowerShell provider drive, when running under that drive.

*By using the domain of the computer running Powershell.

A: When running Remove-ADUser (or computer, or object) - the default domain controller for the current domain will be used.
If you're deleting a user from your current domain - you can see whcih DC will be used by using the command Get-ADDomainController -Writable -Discover
If you're crossing domains or forests - you add the -DomainName switch to give you Get-ADDomainController -Writable -Discover -DomainName "yourDomain.com"
This will return an object which includes a "Name" Attribute.
This Cmdlet uses the same discovery method that PowerShell will use when connecting to AD to delete a user or othr object.


text:
Q: Display product excerpt in WooCommerce order details table and sort order items based on that Currently I'm using Woocommerce Short_Description in Details Order answer code to show the product excerpt on WooCommerce checkout page:
add_filter( 'woocommerce_order_item_name', 'add_single_excerpt_to_order_item', 10, 3 );
function add_single_excerpt_to_order_item( $item_name, $item, $is_visible ){
    $product_id = $item->get_product_id(); // Get the product Id
    $excerpt = get_the_excerpt( $product_id ); // Get the short description

    return $excerpt . $item_name ;
}

Then I try to sort the order items alphabetically, based on the product excerpt. Via How to sort WooCommerce order items alphabetically i was able to write following code:
/*
 * Filters the $order->get_items() method results to order all line items by
 * product name
 */
add_filter( 'woocommerce_order_get_items', function( $items, $order ) {

  uasort( $items,
          function( $a, $b ) {
            return strnatcmp( $a['excerpt'], $b['excerpt'] );
          }
        );

  return $items;

}, 10, 2 );

With this code I don't get any error messages, but I don't get the desired result either. Any advice how to sort excerpt by alphabetical order?

A: To display the short product description you can use:
function filter_woocommerce_order_item_name( $item_name, $item, $is_visible ) {
    // Get the product ID
    $product_id = $item->get_product_id();

    // Get the short description
    $excerpt = get_the_excerpt( $product_id );

    // NOT empty
    if ( ! empty ($excerpt ) ) {
        return $excerpt . ' - ' . $item_name;
    }

    return $item_name;
}
add_filter( 'woocommerce_order_item_name', 'filter_woocommerce_order_item_name', 10, 3 );

Note: because the woocommerce_order_item_name hook is executed on multiple pages (as well as WooCommerce email notifications) you could use conditional tags

Regarding sorting, $a['excerpt'] does not exist, you can replace it with get_the_excerpt( $a['product_id'] )
So you get:
function filter_woocommerce_order_get_items( $items, $order, $types ) {
    // Sort an array with a user-defined comparison function and maintain index association
    uasort( $items, function( $a, $b ) {
        // String comparisons using a "natural order" algorithm
        return strnatcmp( get_the_excerpt( $a['product_id'] ), get_the_excerpt( $b['product_id'] ) );
    } );

    return $items;
}
add_filter( 'woocommerce_order_get_items', 'filter_woocommerce_order_get_items', 10, 3 );


text:
Q: Fonts eventually go black in gnome-3 shell I can't seem to find any information or similar reports on the net, it's an issue that's quite hard to search for. I'm not even sure how to put what is happening into keywords that google would get right.
This happens consistently after a few hours of use. It only happens in the shell, while all applications (including gtk+ themed menu bars) seem to render fonts perfectly fine.
And once this happens, I have to open gnome tweak tool and go to the font hinting settings and just change it to any other value, which I assume re-renders the fonts.
Any idea on how I can fix this for good?


text:
Q: Unexpected IF in MySQL procedure Can anyone tell me what is wrong with the following procedure? MySQL says it is an 'unexpected IF'. I looked up the syntax for an IF statement and I simply don't see what the problem is.
create procedure spInsertAccount
(
AccountID INT,
InUse bit,
IsBanned bit,
IsPremium bit,
IsGolden bit,
Username VARCHAR(20),
Password VARCHAR(20),
Email VARCHAR(65),
LoggedInID INT,
CreateDate DATETIME
)

    SET @accountExists = (SELECT * FROM Accounts WHERE AccountID = @AccountID);

    IF (accountExists > 0) THEN

   INSERT IGNORE INTO Accounts(AccountID, InUse, IsBanned, IsPremium, IsGolden, Username, Password,
                        Email, LoggedInID, CreateDate
                       )
        values (@AccountID, @InUse, @IsBanned, @IsPremium, @IsGolden, @Username, @Password,
               @Email, @LoggedInID, @CreateDate);
        #where NOT EXISTS( SELECT * FROM Accounts WHERE AccountID = @AccountID);

    END IF;

A: Try this instead
Also check out here http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/
DELIMITER //
create procedure `spInsertAccount`
(
IN AccountID INT,
IN InUse bit,
IN IsBanned bit,
IN IsPremium bit,
IN IsGolden bit,
IN Username VARCHAR(20),
IN Password VARCHAR(20),
IN Email VARCHAR(65),
IN LoggedInID INT,
IN CreateDate DATETIME
)
BEGIN
    SET @accountExists = (SELECT * FROM Accounts WHERE AccountID = @AccountID);

    if (accountExists > 0) THEN
        INSERT IGNORE INTO Accounts(AccountID, InUse, IsBanned, IsPremium, IsGolden, Username, Password,Email, LoggedInID, CreateDate)
        values (@AccountID, @InUse, @IsBanned, @IsPremium, @IsGolden, @Username, @Password,
               @Email, @LoggedInID, @CreateDate);
        #where NOT EXISTS( SELECT * FROM Accounts WHERE AccountID = @AccountID);

    END IF;
END //


text:
Q: C++ vector::size_type: signed vs unsigned; int vs. long I have been doing some testing of my application by compiling it on different platforms, and the shift from a 64-bit system to a 32-bit system is exposing a number of issues.
I make heavy use of vectors, strings, etc., and as such need to count them.  However, my functions also make use of 32-bit unsigned numbers because in many cases I need to explicitly consume a positive integer.
I'm having issues with seemingly simple tasks such as std::min and std::max, which may be more systemic.  Consider the following code:
uint32_t getmax()
{
    return _vecContainer.size();
}

Seems simple enough: I know that a vector can't have a negative number of elements, so returning an unsigned integer makes complete sense.
void setRowCol(const uint32_t &r_row; const uint32_t &r_col)
{
    myContainer_t mc;
    mc.row = r_row;
    mc.col = r_col;
    _vecContainer.push_back(mc);
}

Again, simple enough.
Problem:
uint32_t foo(const uint32_t &r_row)
{
    return std::min(r_row, _vecContainer.size());
}

This gives me errors such as:
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/algorithm:2589:1: note: candidate template ignored: deduced conflicting types for parameter '_Tp' ('unsigned long' vs. 'unsigned int')
min(const _Tp& __a, const _Tp& __b)

I did a lot of digging, and on one platform vector::size_type is an 8 byte number.  However, by design I am using unsigned 4-byte numbers.  This is presumably causing things to be wacky because you cannot implicitly convert from an 8-byte number to a 4-byte number.
The solution was to do this the old fashioned weay:
#define MIN_M(a,b) a < b ? a : b
return MIN_M(r_row, _vecContainer.size());

Which works dandy.  But the systemic issue remains: when planning for multiple platform support, how do you handle instances like this?  I could use size_t as my standard size, but that adds other complications (e.g. moving from one platform which supports 64 bit numbers to another which supports 32 bit numbers at a later date).  The bigger issue is that size_t is unsigned, so I can't update my signatures:
size_t foo(const size_t &r_row)
// bad, this allows -1 to be passed, which I don't want

Any suggestions?
EDIT: I had read somewhere that size_t was signed, and I've since been corrected.  So far it looks like this is a limitation of my own design (e.g. 32-bit numbers vs. using std::vector::size_type and/or size_t).

A: One way to deal with this is to use
std::vector<Type>::size_type

as the underlying type of your function parameters/returns, or auto returns if using C++14.

A: An answer in the form of a set of tidbits:

*

*Instead of relying on the compiler to deduce the type, you can explicitly specify the type when using function templates like std::min<T>.  For example: std::min<std::uint32_t>(4, my_vec.size());

*Turn on all the compiler warnings related to signed versus unsigned comparisons and implicit narrowing conversions.  Use brace initialization where you can, as it will treat narrowing conversions as errors.

*If you explicitly want to use 32-bit values like std::uint32_t, I'd try to find the minimal number of places to explicitly convert (i.e., static_cast) the "sizes" to the smaller types.  You don't want casts everywhere, but if you're using library container sizes internally and you want your API to use std::uint32_t, explicitly cast at the API boundaries so that a user of your class never has to worry about doing the conversion themselves.  If you can keep the conversions to just a couple places, it becomes practical to add run-time checks (i.e., assertions) that the size has not actually outgrown the range of the smaller type.

*If you don't care about the exact size, use std::size_t, which is almost certainly identical to std::XXX::size_type for all of the standard containers.  It's theoretically possible for them to be different, but it doesn't happen in practice.  In most contexts, std::size_t is less verbose that std::vector::size_type, so it makes a good compromise.

*Lots of people (including many people on the C++ standards committee) will tell you to avoid unsigned values even for sizes and indexes.  I understand and respect their arguments, but I don't find them persuasive enough to justify the extra friction at the interface with the standard library.  Whether or not it's an historical artifact that std::size_t is unsigned, the fact is that the standard library uses unsigned sizes extensively.  If you use something else, your code ends up littered with implicit conversions, all of which are potential bugs.  Worse, those implicit conversions make turning on the compiler warnings impractical, so all those latent bugs remain relatively invisible.  (And even if you know your sizes will never exceed the smaller type, being forced to turn of the compiler warnings for signedness and narrowing means you could miss bugs in completely unrelated parts of the code.)  Match the types of the APIs you're using as much as possible, assert and explicitly convert when necessary, and turn on all the warnings.

*Keep in mind that auto is not a panacea.  for (auto i = 0; i < my_vec.size(); ++i) ... is just as bad as for (int i ....  But if you generally prefer algorithms and iterators to raw loops, auto will get you pretty far.

*With division you must never divide unless you know the denominator is not 0.  Similarly, with unsigned integral types, you must never subtract unless you know the subtrahend is smaller than or equal to the original value.  If you can make that a habit, you can avoid the bugs that the always-use-a-signed-type folks are concerned about.


text:
Q: Ideal Font Size depending upon @media tags Here are some media tags I've used to make site responsive.
@media all and (min-width:960px) and (max-width: 1024px){}

@media all and (min-width:769px) and (max-width: 959px){}

@media all and (min-width:569px) and (max-width: 768px){}

@media all and (min-width:481px) and (max-width: 568px){}

@media all and (min-width:321px) and (max-width: 480px) {}

@media all and (min-width:0px) and (max-width: 320px){}

Right now I'm using 16px font size on every size of screens from mobile devices to Desktops. I was wondering how should I change the font size depending upon these @media tags.
What would be the ideal font size as per these tags?
Thank You . . .


text:
Q: Prediction model for [parameter vector] to [time series] Say I have a function $F$ that takes in a parameter vector $P$ (say, a 5-element vector), and produces a (numerical) time series $Y[t]$ of length $T$ (eg $T$=100, so $t=1,...,100$). The function could be simple or complicated (e.g. enzyme reaction models).
I want to make a neural network that predicts the output $(Y[t])$ that would result from feeding a new parameter set $(P')$ into the function. How can this be done?
A simple feed-forward network can work (I've tried it on $T=10$), but if $T$ is much bigger  it requires a very large number of output nodes, and doesn't take into account the temporal correlation / relationships between points. Is it possible/better to use a RNN or Transformer instead?
Note that this is not a 'standard' RNN problem: There are no exogenous inputs at each time step, and it is not a 'pure' time series forecasting problem (e.g. predicting stock prices based their historical values).
(An answer with some code would be very appreciated if possible.)


text:
Q: node js using Mongo and Redis simulteniously I am developing a little project using Node.js. I am using mongoose for models, therefore i am using MongoDb. And i keep sessions in MongoStore. Also i want to use socket.io running several processes of Node. From socket.io docs:
    The MemoryStore only allows you deploy socket.io on a single process.
If you want to scale to multiple process and / or multiple servers
you can use our RedisStore which uses the Redis
NoSQL database as man in the middle.

So i think i need Redis too. I am new in Node and i want to know - is it normal to use two databases to manage different parts of application. Or is there a way to work with socket.io when running several processes of Node and use only MongoDb

A: Just recently a solution that uses MongoStore with pub/sub functionality using mubsub (Pub/sub for Node.js and MongoDB) has appeared.
It can be attached to socket.io in almost the same way as you would with RedisStore:
io.configure(function() {
    io.set('store', new MongoStore({host: 'localhost', port: 27017, db:'session_db'}));
});

More information and source at: https://github.com/kof/socket.io-mongo

A: The Redis store is already built into Socket.IO, but more importantly has 2 important features that are particularly needed for Socket.IO:
1) Publish-subscribe (to communicate between processes)
2) Key-value store (to store all the info about connections)
While the key-value store part can be done with MongoDB, it doesn't provide the pub-sub functionality.
Bottom line, IF you need to scale beyond one process (meaning you are expecting more than some thousand concurrent request) than RedisStore is the solution.
Resources:

*

*Examples in using RedisStore in socket.io

*http://www.ranu.com.ar/2011/11/redisstore-and-rooms-with-socketio.html


text:
Q: LoadRunner VuGen Script Replay Failing for Citrix Module Login I am using LoadRunner VuGen to record a test I would like to execute using a Citrix module. I am able to successfully record the actions but when I play the actions back, it stops at the following line of code:
ctrx_wait_for_event("LOGON", CTRX_LAST);

The Citrix ICA Client screen is displayed and it is waiting for the Username, Password, and Domain to be entered by I am unable to manually enter the information in and after a couple a seconds it fails. When I initially record my actions, I am logging into Citrix via a web URL. But when I play back the actions it goes directly to the Citrix ICA Client screen without ever opening the URL.

A: This is Citrix application where Logging into the Citrix Desktop is taking too much time than the parameterized hence throwing the TimeOut Error.
In the error if the IP address is also mentioned, then it is usually is a citrix connectivity/network connectivity issue.
We had a similar error without any IP address, we did the following which resolved the issue:
Check if there are any active citrix sessions, if yes clear/terminate all the sessions. Then run the VuGen script from VuGen and dont try manually
Upgrade the ICA client if it is older than 13, we are using 14.x version


text:
Q: iOS UIWebview crash if copy text from the displayed pdf i've tried to search a lot inside stackoverflow and in google before ask my question.
Seems to be similar questions but for me without answer.
So i'm trying to ask!!
i've a view controller presented as presentModalViewController with inside a uitoolbar and a uiwebview.
In the web view is displayed a pdf file. The web view as default allow me to select a text and show to me the copy function of the standard UIMenuController.
At this point if i dismiss the view controller the app crash with this logged error showed in the console:
libobjc.A.dylib`objc_msgSend:
0x372daf68:  teq.w  r0, #0
0x372daf6c:  beq    0x372dafaa               ; objc_msgSend + 66
0x372daf6e:  push.w {r3, r4}
0x372daf72:  ldr    r4, [r0]
0x372daf74:  lsr.w  r9, r1, #2
0x372daf78:  ldr    r3, [r4, #8]
0x372daf7a:  add.w  r3, r3, #8
0x372daf7e:  ldr    r12, [r3, #-8]
0x372daf82:  and.w  r9, r9, r12
0x372daf86:  ldr.w  r4, [r3, r9, lsl #2]
0x372daf8a:  teq.w  r4, #0
0x372daf8e:  add.w  r9, r9, #1
0x372daf92:  beq    0x372dafa6               ; objc_msgSend + 62
0x372daf94:  ldr.w  r12, [r4]
0x372daf98:  teq.w  r1, r12
0x372daf9c:  bne    0x372db17e               ; objc_msgSendSuper_stret + 34
0x372daf9e:  ldr.w  r12, [r4, #8]
0x372dafa2:  pop    {r3, r4}
0x372dafa4:  bx     r12
0x372dafa6:  pop    {r3, r4}
0x372dafa8:  b      0x372dafb0               ; objc_msgSend_uncached
0x372dafaa:  mov.w  r1, #0
0x372dafae:  bx     lr

I don't understand if this is a my error o a bug of the uiwebview
I've also tried to use CGPDFDocument for render a pdf page but i'm not able to show the UIMenuController and select the text and perform the standard copy action inside the document.
I've also tried to start with this excellent project but also in this i can not perform copy action - https://github.com/vfr/Reader
Basically these are the used code.
I'm working with iOS 5 with ARC
- (void)viewDidLoad
{
[super viewDidLoad];

if (![urlPdfFile hasPrefix:@"http"]) {

NSString *ofType = [urlPdfFile pathExtension];
NSString *pathForResource = [[[urlPdfFile lastPathComponent] componentsSeparatedByString:@"."] objectAtIndex:0];
NSString *inDirectory = [urlPdfFile stringByDeletingLastPathComponent];

NSString *url = [[NSBundle mainBundle] pathForResource:pathForResource
                                                ofType:ofType
                                           inDirectory:inDirectory];

[self loadCatalogueFile:url];
} else {
[self loadFile:urlPdfFile];
}

}

- (void)viewDidUnload
{
[self setMyWebView:nil];
[super viewDidUnload];
}

-(void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
[self.view removeFromSuperview];
self.view=nil;
[self viewDidUnload];
}

-(void)loadCatalogueFile:(NSString*)url {

 NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:url]];
[myWebView loadRequest:request];
}

-(void)loadFile:(NSString*)url
{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
[myWebView loadRequest:request];
}

-(void) webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
//
}

-(void)webViewDidFinishLoad:(UIWebView *)webView
{
//
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
//
}

Thank you very much for your help!!!

A: Had the same problem.
Mine was caused because I retained the view controller which holds the UIWebView, and re-used it.
To fix it just create the view controller each time from scratch.


text:
Q: Is there any way to put range of numbers in a list that the difference of each number is more than x? I'm writing a code to takes two inputs n and k.
n is the maximum range of our number.
k is the minimum value that we want to use to put n numbers together.
If you couldn't understand pay attention to:
The code gets two inputs n and k:
n, k = [int(a) for a in input().split()]

For example n = 5 and k = 2.
I want to sort the numbers from 1 to 5(n) that their difference between each two of them is equals of more than 2(k) and if the condition is not suitable for our n print "Impossible".
For example if n = 2 and k = 2 , then their difference will be less than 2(k) anyway.
I wrote this:
n, k = [int(a) for a in input().split()]
list = []
for i in range(n+1, 1):
    if i - (i-2) >= k:
        list.append(i)
        print(list)

    elif n <= k:
        print("Impossible")

What I want is this:
For example if n = 5 and k = 2,
the output should be:
1 4 2 5 3

and for n = 2 and k = 2:
Impossible

But its not working I'm so confused is there any function or anything that can help me in this?

A: Your code "doesn't work" because your if statement doesn't do anything useful:
if i - (i-2) >= k:

Do the algebra to simplify this:
if 2 >= k:

This merely tests the input value several times.
Work with pencil and paper for a bit.  How can you arrange the numbers from 1 to n such that the least difference will be as large as possible?  Look at the example you posted earlier: what is the pattern there?  Extend it for, say, 8 and 9 numbers.
Find that pattern.  That one, general solution will lead you immediately to a solution where possible, and "impossible" for everything else.
Another possibility is to try all possible arrangements (use itertools.permutation) and check them all for a solution.
Third is to generate solutions, backtracking when you hit a dead-end.  This requires a little extra work to learn recursion, or to get the same effect with iteration.
Does that get you going?


text:
Q: TortoiseSVN Reports an error file foo.c "is locked outside of the working copy" This problem has been solved. I didn't find any description of this particular problem and am posting the problem description and resolution for other people to reference.
On SVN Commit TortoiseSVN reports the error

"file foo.c is locked outside of the working copy"

I have not encountered this error message (no error code given) from subversion before.  No information was given by the error message regarding what type of lock was occurring.
SVN Cleanup did not resolve the problem.

A: Short Answer: The problem was solved by breaking the existing lock.
The first thing I tried was using SVN Cleanup, but that did not resolve the problem.
Looking for SVN Locks on the file using TortoiseSVN->Check for modifications, and selecting "check repository" revealed that the user had the files locked.

A: Run

svn cleanup

first and if it will not solve the problem then run same cleanup to root directory.


text:
Q: Jmeter: How to handle CSRF token from child URL which is not avialable while recording I have to use Jmeter to perform load testing for a website.For this I have to record the login page and play back with real loads from CSV file.The website uses CSRF token for login.
While play back the recorded URLS using HTTPs Script recorder,this "/xyz/j_spring_security_check" calls\spawns an URL,/xyz/login.html(This URL is not available in the recorded http requests but could see in the view results tree,that is why I termed this as "calls\spawns",Please correct me with right term ), which generates the CSRF token and session ID.
The /xyz/j_spring_security_check later uses the CSRF token,session token,Username and password to login.
Now the problem is since the URL is called internally,I couldn't postprocess CSRF token from the /xyz/login.html URL.
Please help me to know,how to get the CSRF token which is part of response body of  internally called URL and not available in the recorded http requests.
p.s:I know how to extract the CSRF token from the request response.

A: I had a similar, I had included "HTTP URL Re-writing Modifier" and as well as removed off the Different call made on the Child Window. Just enabled the Save/Submit action of the Child window.
This worked for my scenario where a user had Search for a specific value in a child window.

A: I had this issue. It was due to view results tree size capacity. Increase the view results tree size in Jmeter properties like this:
view.results.tree.max_size = 0.

All the value you will start to see in view results tree listener. All the tokens and all will be printing.


text:
Q: Update gerando erro de chave duplicada Tenho uma aplicação web em .net 4.5.1 com MVC e entity framework.
O erro ocorre em um CRUD básico.
Recupero o objeto que será o model enviado para a view com o seguinte código:
Professor professor = db.Pessoa
            .Include(p => p.Agenda)
            .Include(p => p.Contato)
            .Include(p => p.Endereco)
            .Include(p => p.SocioEconomico)
            .Include(p => p.SocioEconomico.TelefoneMae)
            .Include(p => p.SocioEconomico.TelefonePai)
            .Include(p => p.Contato.Telefones)
            .Where(p => p is Professor)
            .Single(p => p.Id == id.Value) as Professor;

Esse objeto é enviado para a view e em seguida eu recebo o POST com o objetivo de atualizar um ou mais campos.
No POST tem o seguinte código:
            db.Entry(professor).State = EntityState.Modified;
            db.SaveChanges();

Mas ao passar pela tinha que altera o status da entidade para "Modificado" recebo a seguinte exceção:

An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

Se eu recupero o "Professor" usando o método Find professor = db.Find(id), o update funciona corretamente, mas eu não tenho os objetos "filhos" dele.
Já vi várias possíveis soluções, mas nenhuma funcionou. Alguém já teve o mesmo problema e sabe me dizer qual o erro?

Adicionando toda a definição dos métodos do controller, conforme pedido
GET
 public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Professor professor = db.Pessoa
                .Include(p => p.Agenda)
                .Include(p => p.Contato)
                .Include(p => p.Endereco)
                .Include(p => p.SocioEconomico)
                .Include(p => p.SocioEconomico.TelefoneMae)
                .Include(p => p.SocioEconomico.TelefonePai)
                .Include(p => p.Contato.Telefones)
                .Where(p => p is Professor)
                .Single(p => p.Id == id.Value) as Professor;

            if (professor == null)
            {
                return HttpNotFound();
            }
            return View(professor);
        }

POST
public ActionResult Edit(Professor professor)
        {
            if (ModelState.IsValid)
            {
                db.Entry(professor).State = EntityState.Modified;

                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(professor);
        }

A: Este erro quer dizer que você carregou o objeto professor duas vezes (em objetos diferentes). Durante um método, você só pode carregar o objeto uma única vez.
Se você realmente precisa carregar o objeto duas vezes (por exemplo, quando você quer ter os valores originais dentro do mesmo método), use:
Professor professorOriginal = db.Pessoa
        .AsNoTracking()
        .Include(p => p.Agenda)
        .Include(p => p.Contato)
        .Include(p => p.Endereco)
        .Include(p => p.SocioEconomico)
        .Include(p => p.SocioEconomico.TelefoneMae)
        .Include(p => p.SocioEconomico.TelefonePai)
        .Include(p => p.Contato.Telefones)
        .Where(p => p is Professor)
        .Single(p => p.Id == id.Value) as Professor;

Uma ressalva: não envie este objeto carregado com AsNoTracking() para o contexto, ou o EntityFramework tentará salvar outro objeto com uma nova Id no banco de dados. AsNoTracking() indica que você está carregando o objeto destacado do contexto.

Adendo
Complementando a resposta do @iuristona, se os objetos filhos vêm via POST sem as Ids, o EntityFramework interpreta o objeto vindo do form como um objeto diferente do primeiro. Por isso o erro.

A: Verifique o Id dos objetos filhos, provavelmente esse seja o problema. Você precisará incluir um campo hidden no form para cada Id dos objetos filhos.

A: Verifique em sua base de dados se não existem dois registros com o mesmo ID e se o campo não está auto-incrementando corretamente.


text:
Q: Expected Value of Absolute Value of Difference between Two Independent Uniform Random Variables Let X be Uniform Random Variable on [0,1]. Y is Uniform Random Variable on [0,2]. Given that X and Y are independent, calculate E[|X-Y|].
I have tried calculating the answer using two different methods - both of which I think are correct approaches - but each produces differing results of 2/3 and 3/4.
Method 1) $$\int_{0}^2\int_{0}^1 (|x-y|/2)dxdy$$ I plug the following into Wolfram Alpha and get 2/3: Wolfram calculation
I'm pretty sure this a correct way of going about getting the expected value, since in general for independent x and y, E[g(x,y)] = $$\int_{a}^b\int_{c}^d g(x,y)f(x)f(y)dxdy$$
where of course f(x) and f(y) are the respective distributions of random variables X and Y, and in this particular instance is (1/2)*(1) = (1/2).
Method 2) E[X-Y|X>Y] + E[Y-X|Y>X]. This method yields me 3/4 when I calculate it.
The first integral is $$\int_{0}^1\int_{0}^x (.5(x-y))dydx$$
This equals 1/12. The second integral is $$\int_{0}^2\int_{0}^y (.5(y-x))dxdy$$
This equals 2/3. (2/3) + (1/12) = (3/4).
I'm also fairly certain this is a correct procedure, since there are 3 cases: X>Y, X=Y, and X<Y. X=Y will always produce |X-Y|=0. If X>Y, then |X-Y| = X-Y. If X<Y, then |X-Y| = Y-X. Summing the expectations should yield me a correct result.
Which answer is correct (or neither)? Have I made a careless computational blunder in one of the methods? Or is one of the methods I used a fundamentally incorrect approach to solving the given problem?
EDIT: So, Method 2 is full of errors on my part, which can be noted in the comment section. While I'm certain the correct answer is 2/3, I have found a line of reasoning that yields 3/4 using conditional expectation that I am not able to disprove.
E[|X-Y|] = Pr(Y>1)(E[Y-X|Y>1]) + Pr(X>Y)(E[X-Y|X>Y]) + Pr(Y>X And 0<Y<1)*(E[Y-X|Y>X And 0<Y<1])
Pr(Y>1) = 1/2
Pr(X>Y) = 1/4
Pr(Y>X and 0<Y<1) = 1/4
E[Y-X|Y>1] = 1 (this is intuitive if you think about the symmetry)
E[Y-X|Y>X And 0<Y<1] = E[X-Y|X>Y] (once again intuitive by symmetry)
Now, by linearity of expectation, E[X|X>Y] - E[Y|X>Y] = E[X-Y|X>Y] = 0.5. Given what we know about Y, it is fair to treat Y as uniform on [0,1] in this instance. Therefore, if we expect X to be 0.5, then Y is uniform on [0,0.5], giving expectation of 0.25. The same logic applies in reverse to give us E[X|X>Y] = 0.75. You can see integral proof here: OSU Conditional Expectation Slides.
Finally, summing it all up, (1/2)(1) + (1/4)(1/2) + (1/4)*(1/2) = 3/4.
Can anyone see where I went wrong with my logic on the conditional expectation? In general, when you apply the above procedure, I think what is being spit back is actually the average of the means of X and Y. However, I'm unsure where the logic is breaking down.

A:
Can anyone see where I went wrong with my logic on the conditional expectation?

Here it is!
$$\mathbb{E}|X-Y|=\mathbb{P}[X>Y]\mathbb{E}[X|X>Y]-\mathbb{P}[X>Y]\mathbb{E}[Y|X>Y]+\mathbb{P}[X<Y]\mathbb{E}[Y|X>Y]-\mathbb{P}[X<Y]\mathbb{E}[X|X>Y]$$
$$\frac{1}{4}\times \frac{2}{3}-\frac{1}{4}\times \frac{1}{3}+\frac{3}{4}\times \frac{11}{9}-\frac{3}{4}\times \frac{4}{9}=\frac{2}{3}$$
Sketch of calculations:
$$\mathbb{E}[X|X>Y]=2\int_{0}^{1}x\Bigg[\int_{0}^{ x} dy\Bigg]dx=\frac{2}{3}$$
$$\mathbb{E}[Y|X>Y]=2\int_{0}^{1}\Bigg[\int_{0}^{ x} ydy\Bigg]dx=\frac{1}{3}$$
This because looking at a drawing you see that the distribution is uniform over a triangle with area $0.5$
Similar brainstorming for the other probabilities
$$\mathbb{E}[Y|X<Y]=\frac{2}{3}\int_{0}^{1}\Bigg[\int_{x}^{ 2}y dy\Bigg]dx=\frac{11}{9}$$
$$\mathbb{E}[X|X<Y]=\frac{2}{3}\int_{0}^{1}x\Bigg[\int_{x}^{ 2} dy\Bigg]dx=\frac{4}{9}$$

A third way to solve the problem is the following:
$$\mathbb{E}|X-Y|=\mathbb{E}[Max(X,Y)]-\mathbb{E}[min(X,Y)]$$
Let's set $U=Max(X,Y)$ and $V=min(X,Y)$.
It is very easy to calculate the two CDF's
$$F_U(u) =
\begin{cases}
0,  & \text{if $u<0$ } \\
\frac{u^2}{2},  & \text{if $0\leq u<1$ } \\
\frac{u}{2},  & \text{if $1\leq u<2$ } \\
1, & \text{if $u \geq2$}
\end{cases}$$
$$F_V(v) =
\begin{cases}
0,  & \text{if $v<0$ } \\
1-(1-v)(1-\frac{v}{2}),  & \text{if $0\leq v<1$ } \\
1, & \text{if $v \geq1$}
\end{cases}$$
now remembering that with non-negative rv we have
$$\mathbb{E}[X]=\int_{0}^{\infty}\bigg[1-F_X\Bigg]dx$$
immediately we get also
$$\mathbb{E}|X-Y|=\mathbb{E}[U]-\mathbb{E}[V]=\frac{13}{12}-\frac{5}{12}=\frac{2}{3}$$


text:
Q: Lasso tool in html5 canvas - replacing the clipTo function with clipPath The code shown below is from this post. It works fine when using fabric.js/1.4.0, but when I update fabric.js to 2.4.3, it fails to run. The issue is that the clipTo funtion has been replaced by a new function called clipPath. Does anyone know how to update this code so it works with clipPath? I've gone through the docs for clipPath and have been searching Google and Stackoverflow for almost 2 days, but I'm still lost.

var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
var img = document.createElement('IMG');

img.onload = function() {
    var OwnCanv = new fabric.Canvas('c', {
        isDrawingMode: true
    });

    var imgInstance = new fabric.Image(img, {
        left: 0,
        top: 0,
    });
    OwnCanv.add(imgInstance);

    OwnCanv.freeDrawingBrush.color = "purple"
    OwnCanv.freeDrawingBrush.width = 4

    OwnCanv.on('path:created', function(options) {
        var path = options.path;
        OwnCanv.isDrawingMode = false;
        OwnCanv.remove(imgInstance);
        OwnCanv.remove(path);
        OwnCanv.clipTo = function(ctx) {
            path.render(ctx);
        };
        OwnCanv.add(imgInstance);
    });
}

img.src = "http://upload.wikimedia.org/wikipedia/commons/3/33/Jbassette4.jpg?uselang=fi";
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.0/fabric.min.js"></script>

<canvas id="c" width="500" height="500"></canvas>

A: Ok, so the path, right after being created is already cached.
What you need to do is set the fill to a color that is not null, using the 'set' method.
Then set the path as clipPath for the canvas, or the Object itself.
If you want to set it just for the object, you need to recalculate its correct position.

var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
var img = document.createElement('IMG');

img.onload = function() {
    var OwnCanv = new fabric.Canvas('c', {
        isDrawingMode: true
    });

    var imgInstance = new fabric.Image(img, {
        left: 0,
        top: 0,
    });
    OwnCanv.add(imgInstance);
    OwnCanv.controlsAboveOverlay = true;
    OwnCanv.freeDrawingBrush.color = "purple"
    OwnCanv.freeDrawingBrush.width = 4

    OwnCanv.on('path:created', function(options) {
        var path = options.path;
        path.set('fill', 'black');
        console.log(path)
        OwnCanv.isDrawingMode = false;
        OwnCanv.remove(path);
        OwnCanv.clipPath = path;
    });
}

img.src = "http://upload.wikimedia.org/wikipedia/commons/3/33/Jbassette4.jpg?uselang=fi";
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.6/fabric.min.js"></script>

<canvas id="c" width="500" height="500"></canvas>

A: You need to have objectCaching on false on the path.
Check here:https://jsfiddle.net/jw6rLx5f/2/

var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
var img = document.createElement('IMG');

img.onload = function() {
    var OwnCanv = new fabric.Canvas('c', {
        isDrawingMode: true
    });

    var imgInstance = new fabric.Image(img, {
        left: 0,
        top: 0,
    });
    OwnCanv.add(imgInstance);

    OwnCanv.freeDrawingBrush.color = "purple"
    OwnCanv.freeDrawingBrush.width = 4

    OwnCanv.on('path:created', function(options) {
        var path = options.path;
        path.objectCaching= false;

        OwnCanv.isDrawingMode = false;
        OwnCanv.remove(imgInstance);
        OwnCanv.remove(path);
        OwnCanv.clipTo = function(ctx) {
          ctx.save();
            path.render(ctx);
            ctx.restore();
        };

        OwnCanv.add(imgInstance);
    });
}

img.src = "http://upload.wikimedia.org/wikipedia/commons/3/33/Jbassette4.jpg?uselang=fi";
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.6/fabric.js"></script>
<canvas id="c" width="500" height="500"></canvas>


text:
Q: How can I extract network coefficients from tensorflow .ckpt into .npy? I am working with the FasterRCNN tensorflow implementation found HERE. When defining the 'train_net' function, in the file train.py, they define a saver with the following command:
saver = tf.train.Saver(max_to_keep=100, write_version=saver_pb2.SaverDef.V1)

As a result, at the end of a training run, a number of .ckpt files are created in the output folder, each one containing the model coefficients snapshot for (by default) every 5000 training iteration steps.
Now, if you try to run the testing process (or if you like to continue training) you have 2 choices for loading a pre-trained model. Either you load one such .ckpt file or you can, alternatively, load an .npy file such as the popular VGG_imagenet.npy (the 2 cases are handled in the function 'load' in the class 'Network' defined in the file 'network.py'.
Is there some way to transform the network coefficients saved in the .ckpt file into an .npy file with the structure of VGG_imagenet.npy? Can I obtain this by importing some lines of code right after the .ckpt info is loaded (in the initialize variables section of SolverWrapper>train_model() in the file train.py)?
Thank you.


text:
Q: Modx change mime type for images have uploaded a webp image to my MODX website. seobility shows me that the content or mime type is missing. but i can't edit the html code of the image. thanks a lot in advance

A: perhabs the images is corrupt you do not need to specify mime types in modx for images.
also if you use pthumb you can create a webp image optimised e.g.
[[pthumb? &input=your path to your image &options=&h=100&w=100&zc=1&f=webp]]

A: It seems Seobility not MODX problem is.
You can directly specify this new type by with header adding it via "Content Type" page:
/manager/?a=system/contenttype


text:
Q: Tomcat cannot open database using jdbc after upgrading to SQL Server 2012 I successfully connected to my database when it was SQL Server 2008 R2.
However after upgrading to SQL Server 2012, I get the following error in my java code
The application server that I am using is Tomcat7
The error is as follows:
Jun 10, 2012 1:56:10 PM org.apache.naming.NamingContext lookup
WARNING: Unexpected exception resolving reference
com.microsoft.sqlserver.jdbc.SQLServerException: Cannot open database "MyDB" requested by the login. The login failed.
    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:197)
    at com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:246)
    at com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:83)

The connection string in context.xml is
<Resource name="jdbc/theDB" type="javax.sql.DataSource" auth="Container"
            factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
            driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver" initialSize="30"
            maxActive="100"
        url="jdbc:sqlserver://localhost:1433;databaseName=MyDB;integratedSecurity=true"
            />

The following is in web.xml
<resource-ref>
<description>My Database</description>
<res-ref-name>jdbc/theDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>

I can connect successfully to the database by opening a Data Connection in Eclipse, and in the fact the connection string that is generated is identical to the url from context.xml that I reproduce above.
Has anyone any ideas?
Thank you!

A: Make sure you the user that is running the application server has sufficient rights to the database.


text:
Q: Some permission are not available in profile? When I am migration profiles from one organization to another that time I need some permission in Target organization,
but in target organization these permissions are not available.
Can anyone tell me what I need to do to make these permission available in target organization.
1) ManageNetwork
2) ManageCssUser
3) EditownQuota
4) ManagePartners
5) ManageSelfService
6) ManageTranslation


text:
Q: Crop visible part of image I have a div with overflow:hidden which contains image (.draggable()) that is usually larger then the div and I need to get only visible part of the image and send it to server side script and save as new file. So my question is, how to get only that visible part?
Thanks!

A: You have two options, depending on the method that your are moving your image in the div, save the parameters in inputs using javascript and pass them using POST method when submitting.
For example you pass the TOP and LEFT of image and you already know the WIDTH and HEIGHT of div, so if the left is -375px, you know that you should crop the image from 375px to (375px + div's WIDTH) and same goes for top.
Better option is to use this nice jQuery plugin:
http://deepliquid.com/content/Jcrop.html

A: You should look at the absolute top and left values of the image and compare it with same top and left of the div, take the differences along with the div width and send all this data to server side where you can crop the image via some other programs /library.

A: The solution is by getting the x,y position of the draggable. You can get that data by using .top() and .left() on your div. Then you should send the whole image to your server with the top, left, width, height data and crop it on your server-side.
Please note that I think that it would be possible to crop it to the Client side by using a Canvas HTML5 element and some tricky javascript.


text:
Q: Extern php file showing up IF radio button true I want to build a guide where you first choose what kind of recipe you want to create.
The next side I want to show up with the needed further questions:
If you choose drinkA then show content of subfile xyz.
But what ever I try it doesnt show me the content of the result of the radiobuttons.

          <input type="radio" name="type" value="tea">

<?php
    if($_POST['type'] == "coffee") {
      include ("inc/coffee.php");
   } else if($_POST['type'] == "specialityCoffee") {
      include ('inc/speciality-coffee.php');
   } else if($_POST['type'] == "coldDrip") {
      include ('inc/cold-drip.php');
   } else if($_POST['type'] == "tea") {
      include ('inc/tea.php');
    }

?>

A: You are creating a <form> for each iteration and adding the type="radio" to a form tag. You should create the form tag outside of the foreach loop.
I think you are looking for the input element like <input type="radio"> and you should make sure that you don't duplicate the id's in the loop.
That could be done by using for example id="one-$val"
foreach ($json_var as $value) {
    if ($value["name"] === "counting animals") {
        printf('');
        printf("<form id=\"form1\">");
        foreach ($value["choices"] as $val) {
            printf("<input name=\"image-pick\" value=$val type=\"radio\" id=\"one-$val\" >" );
            printf("");
        }
        printf("</form>");
    }
}


text:
Q: HTML is it possible to set second class inherit the main id? Is it possible for me to set the second class to inherit the main class ID?
Codepen: https://codepen.io/jayvicious/pen/EXardz

.productholder {
  width: 50%;
  display: inline-block;
}

#content2p {
  padding-top: 19px;
  padding-bottom: 40px;
  margin-left: 6cm;
  width: auto;
}

.bookingFormHeader {
  display: inline-flex;
  background-color: lightgrey;
  width: 300px;
  border: 25px solid green;
  padding: 25px;
  margin: 25px;
}

Test Test

Explanation :-
I've set a container with the id content2p . Here i want to put two class side by side. The first class productholder is working fine. My only issue would be bookingFormHeader . It's indenting to the bottom, i want to make it same line as below example output:

The booking is actually a form with border box :

I've tried many ways by changing the display to the following :-
inline-block
 flex
 table
 inline-table
Yet i've got no luck , is there any element I'm missing??
Appreciate in advance.

A: Is this what you are after? Please adjust margins and width to you liking.

#content2p {
  padding-top: 19px;
  padding-bottom: 40px;
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.bookingFormHeader {
  background-color: lightgrey;
  width: 100px;
  border: 25px solid green;
  padding: 25px;
  margin: 25px;
}

Test Test

A: You also use class inside id


text:
Q: Player character not adding to GridPane Javafx I'm making a 2D game that requires a 2D character which will be able to eventually move around objects itself. I've been trying to get my movement method to work, and whilst I think with help I've cracked it, I've noticed that I've only been adding an image to the gridPane and not the character itself. Whilst I'm confident I can just add an image and manipulate that, I would like to add the keeper from  createKeeper().
     public class Main extends Application {

            public static void main(String[] args) {

            launch(args);
        }

            @Override

            public void start(Stage stage) {

       create(stage);

        }

            private void create(Stage theStage) {

                GridPane root = new GridPane();
                root.getColumnConstraints().add(new ColumnConstraints(100));

                Text t1 = new Text(250, 50, "Sokoban");
                t1.setId("title");
                t1.setFont(Font.font(java.awt.Font.SERIF, 25));

                Image image = new Image(getClass().getResourceAsStream("title.png"));
                Label label1 = new Label("");
                label1.setGraphic(new ImageView(image));
                label1.setTranslateY(50);
                label1.setTranslateX(225);

                Text t3 = new Text(260, 350, "Quit");
                t3.setFont(Font.font(java.awt.Font.SERIF, 25));

                Button btn = new Button();

                btn.setText("Start");
                btn.setFont(Font.font(java.awt.Font.SERIF, 25));

                btn.setOnAction(new EventHandler<ActionEvent>() {
                    @Override
                    public void handle(ActionEvent event) {

                        Level.runLevel1(theStage);

                        System.out.println("Hello World!");
                    }
                });

                Pane buttonPane = new Pane();
                buttonPane.setId("root");

                btn.setLayoutX(250);
                btn.setLayoutY(250);

                buttonPane.getChildren().addAll(label1, t3, btn);

                Scene scene = new Scene(buttonPane, 560, 560);
                buttonPane.getStylesheets().addAll(this.getClass().getResource("application.css").toExternalForm());

                theStage.setResizable(false);
                theStage.setTitle("Menu");
                theStage.setScene(scene);
                theStage.show();

            }

   }

        public class Level {

private static ImageView image1 = ImageLoader.showWareHouseImage();
            private static final int KEYBOARD_MOVEMENT_DELTA = 2;
            static int xPosition;
            static int yPosition;
            static WarehouseKeeper keeper = new WarehouseKeeper(image1, xPosition, yPosition);;

            public static void runLevel1(Stage theStage) {

                keeper.yPosition = 5;
                keeper.xPosition = 5;

                Group root = new Group();

                int columnAmount = 12;
                int rowAmount = 12;

                GridPane gameGrid = new GridPane();

                for (int i = 0; i < columnAmount; i++) {
                    ColumnConstraints columnn = new ColumnConstraints(45);
                    gameGrid.getColumnConstraints().add(columnn);

                }

                for (int i = 0; i < rowAmount; i++) {

                    RowConstraints row = new RowConstraints(45);
                    gameGrid.getRowConstraints().add(row);
                }

                gameGrid.setStyle("-fx-background-color: white; -fx-grid-lines-visible:true");
                Scene scene = new Scene(root, (columnAmount * 40) + 66, (rowAmount * 40) + 66, Color.WHITE);

                root.getChildren().add(gameGrid);

                gameGrid.add(image1, xPosition, yPosition);

                moveWareHouse(theStage, keeper);

                theStage.setScene(scene);

                theStage.show();

            }

            private static void moveWareHouse(Stage theStage, WarehouseKeeper keeper) {

                theStage.addEventFilter(KeyEvent.KEY_RELEASED, event -> {

                    event.consume();

                    switch (event.getCode()) {

                    case W:
                        System.out.println("up");
                        keeper.setyPosition(keeper.getyPosition() - KEYBOARD_MOVEMENT_DELTA);
                        break;
                    case D:
                        keeper.setxPosition(keeper.getxPosition() + KEYBOARD_MOVEMENT_DELTA);
                        break;
                    case A:
                        keeper.setyPosition(keeper.getyPosition() + KEYBOARD_MOVEMENT_DELTA);
                        break;
                    case S:
                        keeper.setxPosition(keeper.getxPosition() - KEYBOARD_MOVEMENT_DELTA);
                        break;

                    }
                });

            }

  }

        public class WarehouseKeeper extends ImageLoader {

            private Image playerImage;
            private ImageView image;
            private int speed;
            int xPosition;
            int yPosition;

            public WarehouseKeeper(ImageView wareHouseImage, int xPosition, int yPosition) {

                super(wareHouseImage);

                this.speed = speed;
                this.xPosition = xPosition;
                this.yPosition = yPosition;

            }

            public int getxPosition() {
                return xPosition;
            }

            public void setxPosition(int xPosition) {
                this.xPosition = xPosition;
            }

            public int getyPosition() {
                return yPosition;
            }

            public void setyPosition(int yPosition) {
                this.yPosition = yPosition;
            }

   }

      public class ImageLoader {

            public static ImageView wareHouseImage;
            private Object diamondImage;
            private Object wallImage;
            private Object mapImage;
            private Object crateImage;

            public ImageLoader(ImageView wareHouseImage){

                this.wareHouseImage = showWareHouseImage();

            }

            public  ImageView getWareHouseImage() {
                return wareHouseImage;
            }

            public Image setWareHouseImage(Image wareHouseImage) {
                this.wareHouseImage = showWareHouseImage();

                return wareHouseImage;
            }

            public static ImageView showWareHouseImage() {

                ImageView wareHouse = new ImageView();
                wareHouse.setFitHeight(45);
                wareHouse.setFitWidth(45);

                Image wareHouseImage = new Image("application/warehouse.png");
                wareHouse.setImage(wareHouseImage);

                return wareHouse;

            }
    }


text:
Q: Pythonic way to assign an instance of a subclass to a variable when a specific string is presented to the constructor of the parent class I want to be able to create an instance of a parent class X, with a string "Q" as an extra argument.
This string is to be a name being an identifier for a subclass Q of the parent class X.
I want the instance of the parent class to become (or be replaced with) an instance of the subclass.
I am aware that this is probably a classic problem (error?). After some searching I haven't found a suitable solution though.
I came up with the following solution myself;
I added a dictionary of possible identifiers as keys for their baseclass-instances to the init-method of the parent class.
Then assigned the class-attribute of the corresponding subclass to the current instances class-attribute.
I required the argument of the init-method not to be the default value to prevent infinite looping.
Following is an example of what the code looks like in practice;
class SpecialRule:
    """"""
    name="Special Rule"
    description="This is a Special Rule."
    def __init__(self, name=None):
        """"""
        print "SpecialInit"
        if name!=None:
            SPECIAL_RULES={
                "Fly" : FlyRule(),
                "Skirmish" : SkirmishRule()
                } #dictionary coupling names to SpecialRuleclasses
            self.__class__= SPECIAL_RULES[name].__class__

    def __str__(self):
        """"""
        return self.name

class FlyRule(SpecialRule):
    """"""
    name="Fly"
    description="Flies."
    def __init__(self):
        """"""
        print "FlyInit"+self.name
        SpecialRule.__init__(self)
    def addtocontainer(self, container):
        """this instance messes with the attributes of its containing class when added to some sort of list"""

class SkirmishRule(SpecialRule):
    """"""
    name="Skirmish"
    description="Skirmishes."
    def __init__(self):
        """"""
        SpecialRule.__init__(self)
    def addtocontainer(self, container):
        """this instance messes with the attributes of its containing class when added to some sort of list"""

test=SpecialRule("Fly")
print "evaluating resulting class"
print test.description
print test.__class__
</pre></code>

output:

    >
    SpecialInit
    FlyInitFly
    SpecialInit
    evaluating resulting class
    Flies.
    main.FlyRule
    >

Is there a more pythonic solution and are there foresee-able problems with mine?
(And am I mistaken that its a good programming practice to explicitly call the .__init__(self) of the parent class in .__init__ of the subclass?).
My solution feels a bit ... wrong ...
Quick recap so far;
Thanks for the quick answers
@ Mark Tolonen's solution
I've been looking into the __new__-method, but when I try to make A, B and C in Mark Tolonen's example subclasses of Z, I get the error that class Z isn't defined yet. Also I'm not sure if instantiating class A the normal way ( with variable=A() outside of Z's scope ) is possible, unless you already have an instance of a subclass made and call the class as an attribute of an instance of a subclass of Z ... which doesn't seem very straightforward. __new__ is quite interesting so I'll fool around with it a bit more, your example is easier to grasp than what I got from the pythondocs.
@ Greg Hewgill's solution
I tried the staticmethod-solution and it seems to work fine. I looked into using a seperate function as a factory before but I guessed it would get hard to manage a large program with a list of loose strands of constructor code in the main block, so I'm very happy to integrate it in the class.
I did experiment a bit seeing if I could turn the create-method into a decorated .__call__() but it got quite messy so I'll leave it at that.

A: I would solve this by using a function that encapsulates the choice of object:
class SpecialRule:
    """"""
    name="Special Rule"
    description="This is a Special Rule."
    @staticmethod
    def create(name=None):
        """"""
        print "SpecialCreate"
        if name!=None:
            SPECIAL_RULES={
                "Fly" : FlyRule,
                "Skirmish" : SkirmishRule
                } #dictionary coupling names to SpecialRuleclasses
            return SPECIAL_RULES[name]()
        else:
            return SpecialRule()

I have used the @staticmethod decorator to allow you to call the create() method without already having an instance of the object. You would call this like:
SpecialRule.create("Fly")

A: Look up the __new__ method.  It is the correct way to override how a class is created vs. initialized.
Here's a quick hack:
class Z(object):
    class A(object):
        def name(self):
            return "I'm A!"
    class B(object):
        def name(self):
            return "I'm B!"
    class C(object):
        def name(self):
            return "I'm C!"

    D = {'A':A,'B':B,'C':C}

    def __new__(cls,t):
        return cls.D[t]()