text:
Q: Does data race happen when using cgo? Goroutines runs in different stack for cgo and go:

C doesn't know anything about Go's calling convention or growable stacks, so a call down to C code must record all the details of the goroutine stack, switch to the C stack, and run C code which has no knowledge of how it was invoked, or the larger Go runtime in charge of the program.

Is there any possiblities to  trigger data race for variables or types shared between them?
Recently, I got errors when initialize slices like:
package controlcan

import "C"

cReceive := make([]C.struct__CAN_OBJ, 2500)

or
package main

import "controlcan"

pReceive := make([]controlcan.CanObj, 2500)

Both of them complains "unexpected fault address" errors randomly:
unexpected fault address 0xffffffffffffffff
fatal error: fault
[signal 0xc0000005 code=0x0 addr=0xffffffffffffffff pc=0x41c65d]

goroutine 41 [running]:
runtime.throw(0xcc969a, 0x5)
        /usr/local/go/src/runtime/panic.go:619 +0x88 fp=0xc0428ffb38 sp=0xc0428ffb18 pc=0x42d0b8
runtime.sigpanic()
        /usr/local/go/src/runtime/signal_windows.go:170 +0x13a fp=0xc0428ffb68 sp=0xc0428ffb38 pc=0x43fcca
runtime.gcMarkRootPrepare()
        /usr/local/go/src/runtime/mgcmark.go:72 +0x5d fp=0xc0428ffb70 sp=0xc0428ffb68 pc=0x41c65d
runtime.gcStart(0x0, 0x1, 0x0, 0x0)
        /usr/local/go/src/runtime/mgc.go:1350 +0x30f fp=0xc0428ffba0 sp=0xc0428ffb70 pc=0x419b6f
runtime.mallocgc(0x10000, 0xc54660, 0xc0422ee001, 0xc0423ded60)
        /usr/local/go/src/runtime/malloc.go:803 +0x448 fp=0xc0428ffc40 sp=0xc0428ffba0 pc=0x411c48
runtime.makeslice(0xc54660, 0x9c4, 0x9c4, 0xc04202ce00, 0xc04202c000, 0x411b23)
        /usr/local/go/src/runtime/slice.go:61 +0x7e fp=0xc0428ffc70 sp=0xc0428ffc40 pc=0x43fffe
controlcan.Receive(0x4, 0x0, 0x0, 0xc04267e000, 0x9c4, 0x9c4, 0x64, 0x0, 0x0, 0x0)
        /media/sf_GOPATH0/src/controlcan/controlcan.go:262 +0x75 fp=0xc0428ffd70 sp=0xc0428ffc70 pc=0xa0d795
posam/protocol/usbcan.(*Channel).receive(0xc04229d490)
        /media/sf_GOPATH0/src/posam/protocol/usbcan/usbcan.go:469 +0x536 fp=0xc0428fffd8 sp=0xc0428ffd70 pc=0xa10926
runtime.goexit()
        /usr/local/go/src/runtime/asm_amd64.s:2361 +0x1 fp=0xc0428fffe0 sp=0xc0428fffd8 pc=0x457531
created by posam/protocol/usbcan.(*Channel).Start
        /media/sf_GOPATH0/src/posam/protocol/usbcan/usbcan.go:242 +0x3aa

Update
controlcan is a wrapper package that encapsulates functions defined in .dll or .so libraries to the ones that Golang-friendly, e.g., sending messages to, or receiving messages from CAN devices. IMO, it's really weird that data race on the statement of slice initialization, within the controlcan package and other packages imported it.
In the Receive function, the first line declares a slice called cReceive and I got the errors randomly as mentioned above. I think the reason of unexpected fault address is data race rather than memory corruption, but the resource required here is only the type C.struct__VCI_CAN_OBJ, not any variables. I hope I was wrong.
What's worse, the type CanObj, which is used in othe packages like usbcan.go, still possibly triggers that errors, e.g., the statement of pReceive. Previously, I suspected that the reason might be the constant of 2500, since the original statement is cReceive := make([]C.struct__VCI_CAN_OBJ, FRAME_LENGTH_OF_RECEPTION). But when I changed it to 2500 directly, the error occurs all the same.
controlcan.go
package controlcan

import "C"
import (
    "fmt"
    "runtime"
    "unsafe"
)

const (
    FRAME_LENGTH_OF_RECEPTION = 2500
)

type CanObj struct { // <- accessable for other packages/goroutines
    ID         int
    TimeStamp  int
    TimeFlag   int
    SendType   byte
    RemoteFlag byte
    ExternFlag byte
    DataLen    byte
    Data       [8]byte
    Reserved   [3]byte
}

func Receive(
    devType int,
    devIndex int,
    canIndex int,
    pReceive []CanObj,
    waitTime int,
) (count int, err error) {
    cReceive := make([]C.struct__VCI_CAN_OBJ, 2500) // unexpected fault address
    cCount := C.VCI_Receive(
        C.uint(devType),
        C.uint(devIndex),
        C.uint(canIndex),
        (*C.struct__VCI_CAN_OBJ)(unsafe.Pointer(&cReceive)),
        C.uint(FRAME_LENGTH_OF_RECEPTION),
        C.int(waitTime),
    )

    // ...
}

usbcan.go
package usbcan

import "controlcan"

func (c *Channel) receive() {
    ticker := time.NewTicker(100 * time.Millisecond)
    defer ticker.Stop()
    for _ = range ticker.C {
        pReceive := make([]controlcan.CanObj, 2500) // unexpected fault address
        count, err := controlcan.Receive(
            c.DevType,
            c.DevIndex,
            c.CanIndex,
            pReceive,
            100,
        )
    // ...

Update 2:
I move the cReceive creation from Go to Cgo, stolen from Kenny Grant, and the make-slice error of cReceive line is solved.
package controlcan

// static VCI_CAN_OBJ** makeCanObjArray(){
//     return calloc(sizeof(VCI_CAN_OBJ*), 2500);
// }
// static void freeCanObjArray(VCI_CAN_OBJ **canObjArray){
//     int i;
//     for (i=0; i<2500;i++)
//         free(canObjArray[i]);
//     free(canObjArray);
// }
import "C"

func Receive(
    devType int,
    devIndex int,
    canIndex int,
    pReceive []CanObj,
    waitTime int,
) (count int, err error) {
    cReceive := C.makeCanObjArray()
    defer C.freeCanObjArray(cReceive)
// ...

And I still can't figure out what happens when creating pReceive:
pReceive := make([]controlcan.CanObj, 2500)

unexpected fault address 0xffffffffffffffff
fatal error: fault
[signal 0xc0000005 code=0x0 addr=0xffffffffffffffff pc=0x41c65d]

goroutine 28 [running]:
runtime.throw(0xcc969a, 0x5)
        /usr/local/go/src/runtime/panic.go:619 +0x88 fp=0xc04275bc38 sp=0xc04275bc18 pc=0x42d0b8
runtime.sigpanic()
        /usr/local/go/src/runtime/signal_windows.go:170 +0x13a fp=0xc04275bc68 sp=0xc04275bc38 pc=0x43fcca
runtime.gcMarkRootPrepare()
        /usr/local/go/src/runtime/mgcmark.go:72 +0x5d fp=0xc04275bc70 sp=0xc04275bc68 pc=0x41c65d
runtime.gcStart(0x0, 0x1, 0x0, 0x0)
        /usr/local/go/src/runtime/mgc.go:1350 +0x30f fp=0xc04275bca0 sp=0xc04275bc70 pc=0x419b6f
runtime.mallocgc(0x1a000, 0xc54520, 0x1, 0xa10101)
        /usr/local/go/src/runtime/malloc.go:803 +0x448 fp=0xc04275bd40 sp=0xc04275bca0 pc=0x411c48
runtime.makeslice(0xc54520, 0x9c4, 0x9c4, 0xc0420162a0, 0x8, 0x8)
        /usr/local/go/src/runtime/slice.go:61 +0x7e fp=0xc04275bd70 sp=0xc04275bd40 pc=0x43fffe
posam/protocol/usbcan.(*Channel).receive(0xc04213fdc0)
        /media/sf_GOPATH0/src/posam/protocol/usbcan/usbcan.go:464 +0x4f0 fp=0xc04275bfd8 sp=0xc04275bd70 pc=0xa108e0
runtime.goexit()
        /usr/local/go/src/runtime/asm_amd64.s:2361 +0x1 fp=0xc04275bfe0 sp=0xc04275bfd8 pc=0x457531
created by posam/protocol/usbcan.(*Channel).Start
        /media/sf_GOPATH0/src/posam/protocol/usbcan/usbcan.go:242 +0x3aa


text:
Q: What do you do to make compiler lines shorter? Often when I'm working on a project with others, the amount of library paths and include paths that get sourced by the compiler in the Makefile get more numerous as time goes by. Also the paths can get very long as well.
Here's an example:
g++ -c -pipe -O2 -Wall -W -DQT_BOOTSTRAPPED -DQT_MOC -DQT_NO_CODECS
-DQT_LITE_UNICODE -DQT_NO_LIBRARY -DQT_NO_STL -DQT_NO_COMPRESS
-DQT_NO_DATASTREAM -DQT_NO_TEXTSTREAM -DQT_NO_TEXTCODEC -DQT_NO_UNICODETABLES
-DQT_NO_THREAD -DQT_NO_REGEXP -DQT_NO_QOBJECT -DQT_NO_SYSTEMLOCALE
-DQT_NO_GEOM_VARIANT -DQT_NO_USING_NAMESPACE -D_LARGEFILE64_SOURCE
-D_LARGEFILE_SOURCE -I../../../mkspecs/qws/linux-generic-g++ -I.
-I../../corelib/arch/generic -I../../../include -I. -I../../../include/QtCore
-I. -I.uic/release-shared -o release-shared/moc.o moc.cpp

I'm wondering what kind of recipes you use to make compiler lines much shorter, while still giving the user the option to display the raw lines if they really need that information later.
Are there tools that do this automatically?

A: Not only can you make your compiler output shorter, you can colorcode it, and add a verbose flag. The output will look something like this:
alt text http://img526.imageshack.us/img526/9572/sconsf.png
Here's how (color theme stolen from the SCons Wiki):
import os,sys
colors = {}
colors['cyan']   = '\033[96m'
colors['purple'] = '\033[95m'
colors['blue']   = '\033[94m'
colors['green']  = '\033[92m'
colors['yellow'] = '\033[93m'
colors['red']    = '\033[91m'
colors['end']    = '\033[0m'

#If the output is not a terminal, remove the colors
if not sys.stdout.isatty():
   for key, value in colors.iteritems():
      colors[key] = ''

compile_source_message = '%s\nCompiling %s==> %s$SOURCE%s' % \
   (colors['blue'], colors['purple'], colors['yellow'], colors['end'])

compile_shared_source_message = '%s\nCompiling shared %s==> %s$SOURCE%s' % \
   (colors['blue'], colors['purple'], colors['yellow'], colors['end'])

link_program_message = '%s\nLinking Program %s==> %s$TARGET%s' % \
   (colors['red'], colors['purple'], colors['yellow'], colors['end'])

link_library_message = '%s\nLinking Static Library %s==> %s$TARGET%s' % \
   (colors['red'], colors['purple'], colors['yellow'], colors['end'])

ranlib_library_message = '%s\nRanlib Library %s==> %s$TARGET%s' % \
   (colors['red'], colors['purple'], colors['yellow'], colors['end'])

link_shared_library_message = '%s\nLinking Shared Library %s==> %s$TARGET%s' % \
   (colors['red'], colors['purple'], colors['yellow'], colors['end'])

java_compile_source_message = '%s\nCompiling %s==> %s$SOURCE%s' % \
   (colors['blue'], colors['purple'], colors['yellow'], colors['end'])

java_library_message = '%s\nCreating Java Archive %s==> %s$TARGET%s' % \
   (colors['red'], colors['purple'], colors['yellow'], colors['end'])

env = Environment()
AddOption("--verbose",action="store_true", dest="verbose_flag",default=False,help="verbose output")
if not GetOption("verbose_flag"):
  env["CXXCOMSTR"] = compile_source_message,
  env["CCCOMSTR"] = compile_source_message,
  env["SHCCCOMSTR"] = compile_shared_source_message,
  env["SHCXXCOMSTR"] = compile_shared_source_message,
  env["ARCOMSTR"] = link_library_message,
  env["RANLIBCOMSTR"] = ranlib_library_message,
  env["SHLINKCOMSTR"] = link_shared_library_message,
  env["LINKCOMSTR"] = link_program_message,
  env["JARCOMSTR"] = java_library_message,
  env["JAVACCOMSTR"] = java_compile_source_message,

Compile with "scons --verbose" to see the normal bulky gcc output.

A: If it's mostly the spewing of huge lines during 'make' that causes the annoyance, you can also change your Makefile to not echo the compiler line, but to instead have something like:
     .cpp.o:
          @echo $(CC) $<
          @$(CC) $(FLAGS) -c -o $@ $<

The '@' suppresses the echo of the command line

A: How about using environment variables?
export LONGPATH=/usr/local/projects/include/foo/system/v1
gcc foo.c -o foo -I$LONGPATH

For more complex scenarios, one can use wrappers to invoke the compiler, so that the actual commands and their parameters only show up on errors or warnings.
Using cmake for example, much of the conventional output is already downstripped heavily.
Similarly, there's the possibility to use spec files with gcc.

A: In scons, I insert newlines into my command generators to make long commands more readable:
e.g.
tool \
    -opt1 bar1 \
    -opt2 bar2 \
    -opt3 bar3 \
    -opt4 bar4

then I create a local method when constructing the command string to reduce the clutter.
cmds = []
def l(line,indent=1):
    cmds.append(indent*'    '+line)
l('tool',0)
l('-opt1 bar1')
l('-opt2 bar2')
l('-opt3 bar3')
l('-opt4 bar4')

return '\\\n'.join(cmds)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Lucene.Net Search List I'm using Sitecore and have a multilist field I'd like to use Lucene to search on.  The problem I have is that the field is a pipe-delimited list of actual values and there could be between 0 and an infinite (theoretically speaking, actually there's probably only a thousand or two possibilities) number of items in this list.  I haven't been able to successfully use a wildcard query and I can't envision how to break this field up into multiple fields since there's an unknown number of items in the list.

A: I've used a similar technique in searches to search within a category heirarchy. I use the following method to build the query, leaving the hard work to the QueryParser class.  I usually add this query to a BooleanQuery.
The QueryParser usually does a great job, I often use it for building most of my Lucene queries - it seems to do a better job than me when building a specific query a lot of the time!!
Another thing you can do is to use the QueryParser to build it, then set a breakpoint and have a look at how the query has been created, then update your code with the specific query type.
private Query GetQuery(Sitecore.Data.ID id)
{
    string categoryId = id.Guid.ToString(); //turn ID to string
    StandardAnalyzer analyzer = new StandardAnalyzer(); //use standard analyzer
    QueryParser parser = new QueryParser("categories", analyzer); //search inside category field
    Query query = parser.Parse(categoryId); //get the query
    return query;
}


text:
Q: Из списка стран открыть список соответствующих городов Как реализовать следующее в UITableView
В первом окне дожен быть список стран, при клике на любую  страну должно открываться список соответствующих этой стране городов. Какую модель использовать NSArray  или NSDictionary для Страна-Города, что должно быть реализовано в
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

и что должно передаваться в
 (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

A: Вот тут нагуглил видос
Вот тут тутор
Сам запрос может что еще найдете
UPD
Ааа ну это как удобно, вот мы в своем проекте имели простую таблицу с иерархическими индексами: т.е.

|индекс города/области/страны | индекс родительского элемента | Название города |
ну как то-так примерно. Потом получали все индексы из базы родительский индекс, которых равен 0 т.е. рутовые объекты ( у нас это были страны)
данный список грузим в TableView по делегату
(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

получаем индекс нажатой ячейки, ну и берем по индексу из массива сосоответствующую модель. Теперь у нас есть индекс рутового объекта.
вызываем новый экземляр данного контроллера и передаем в конструктор индекс рутового объекта:
CityViewController *cityViewController = [[CityViewController alloc]initWithRootIndex:13];
[self.navigationController pushViewController:cityViewController animated:YES];

Ну и по аналогии рекурсивно пока не дойдете до улицы


text:
Q: Changes in Model .NET asp.net MVC4 i've created a project using this steps
Create Model;
Create Controller from Model and scaffolding Views;
I've tried to access, and it works fine, but I've made some changes in Model rebuilt and tried to run one more time, and now i got this error:

{"The model backing the 'CodingContext' context has changed since the
  database was created. Consider using Code First Migrations to update
  the database (http://go.microsoft.com/fwlink/?LinkId=238269)."}

This error brings a null inner exception
and this is the stack:

at System.Data.Entity.CreateDatabaseIfNotExists1.InitializeDatabase(TContext context)
     at System.Data.Entity.Internal.InternalContext.<>c__DisplayClass8.<PerformDatabaseInitialization>b__6()
     at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
     at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
     at System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c)
     at System.Data.Entity.Internal.RetryAction1.PerformAction(TInput input)
     at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action1 action)
     at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
     at System.Data.Entity.Internal.InternalContext.Initialize()
     at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
     at System.Data.Entity.Internal.Linq.InternalSet1.Initialize()
     at System.Data.Entity.Internal.Linq.InternalSet1.GetEnumerator()
     at System.Data.Entity.Infrastructure.DbQuery1.System.Collections.Generic.IEnumerable.GetEnumerator()
     at System.Collections.Generic.List1..ctor(IEnumerable1 collection)
     at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source)
     at Coding.Controllers.CorController.Index() in c:\Users\Guilherme\Documents\Visual Studio 2012\Projects\Coding\Coding\Controllers\CorController.cs:line 19
     at lambda_method(Closure , ControllerBase , Object[] )
     at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
     at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters)
     at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters)
     at System.Web.Mvc.Async.AsyncControllerActionInvoker.InvokeSynchronousActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters)
     at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c_DisplayClass42.b_41()
     at System.Web.Mvc.Async.AsyncResultWrapper.<>c_DisplayClass81.<BeginSynchronous>b__7(IAsyncResult _)
     at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult1.End()
     at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
     at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
     at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c_DisplayClass37.<>c_DisplayClass39.b_33()
     at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c_DisplayClass4f.b_49()

I think the problem is about refresing the database using this new Model, but i can't found any command that solve this problem.
Thanks in advance!

A: If Someone got the same problem, I got this answer with some friend help, you must to follow these steps to update your database:
Open The package manager console: Tools –> Library Package Manager –> Package Manager Console
Install Entity Framework: Install-Package EntityFramework
Run: Enable-Migrations
At this point I'd got problems, but the Visual Studio show me the answer, is just a problem of multiple Contexts
Run: Add-Migration
Then: Update-Database
And it's done, every change in you model, require to run these commands!


text:
Q: Do-while being skipped over or If statement not working After running through the two functions once, the do while loop keeps skipping over to the while condition and goes straight to the getInt function, which then gets stuck in the
scanf("%d,%c", &Value, &NL)
until a character (or word like office) is inputted. This will happen another 3 times, until the fourth "invalid INTEGER" message, which the "OUT OF RANGE" message will then show, only for the who process to happen all over again. Not sure if it's the do-while loop which is not working, or if the if statements are not functioning.
When testing the function(s) with a word (i.e. office) it getInt will declare the values an "invalid INTEGER", and when testing with the values 99 or 501, getIntInRange should declare the value "OUT OF RANGE", however, the function getIntInRange will only show "OUT OF RANGE" message after 5 iterations (if alternating between a value and character, the "OUT OF RANGE" message will display after the fourth attempt of inputting a value
// getInt function definition goes here:
int getInt(void) {
    int Value = 0;
    char NL = "";

    do {
        scanf("%d%c", &Value, &NL);
        if (NL != '\n') {
            clearKeyboard();
            printf("*** INVALID INTEGER *** <Please enter an integer>: ");
        } else {
        };
    } while (NL != '\n');

    return Value;
}

// getIntInRange function definition goes here:
int getIntInRange(int lowerBound, int upperBound) {
    do {
        //getInt();
        if (getInt() < lowerBound | getInt() > upperBound) {
            printf("*** OUT OF RANGE *** <Enter a number between %d and %d>: ", lowerBound, upperBound);
        } else {
            continue;
        };
    } while (getInt() < lowerBound | getInt() > upperBound);

    return getInt();
}

My getIntInRange function is suppose to receive a value from the getInt function (getInt checks if the value entered is an integer) and compares the values with the lowerBound (set as 100 in a different source code) and the upperBound (set as 500 in a different source code). If the value is out of the range, then an error message will be displayed.

A: Your code has multiple errors:

*

*char NL = ""; is incorrect: char is a character, "" is a string.

*scanf("%d%c", &Value, &NL); is not a way to reliably test for correct input, you should instead test the return value of scanf(): if (scanf("%d", &Value) != 1) { /* invalid input */ }

*you should not call getInt() multiple times, the value must be stored into a variable and the variable should be tested, otherwise the value input is lost.

*you should consume the offending input before calling scanf() again.

*you should check for end of file to avoid an infinite loop.

*you should use || or && for logical tests, | is for bit manipulations.

*avoid do / while loops, they are notoriously confusing and prone to programming errors.

Here is a corrected version:
#include <stdio.h>
#include <stdlib.h>

int clearInput(void) {
    int c;
    while ((c = getchar() != EOF && c != '\n')
        continue;
    return c;
}

int getInt(void) {
    int value = 0;

    while (scanf("%d", &value) != 1) {
         if (clearInput() == EOF) {
             printf("unexpected end of file\n");
             exit(1);
         }
         printf("not an integer, try again\n");
    }
    return value;
}

int getIntInRange(int lowerBound, int upperBound) {
    for (;;) {
        int value = getInt();
        if (value >= lowerBound && value <= upperBound)
            return value;
        printf("*** OUT OF RANGE *** <Enter a number between %d and %d>: ", lowerBound, upperBound);
    }
}


text:
Q: aws coldbuild failed: ebcli.objects.exceptions.NotFoundError: Environment "flask-daniel-test" not Found I have github repo here https://github.com/DanielWu1978/flaskbeanstalk
And then configured a codebuild for it. When I run the following command from command line locally, it is ok, but when call the same code from codebuild, it raises the error of "ebcli.objects.exceptions.NotFoundError: Environment "flask-daniel-test" not Found.". Why this happens?

eb deploy flask-daniel-test --verbose

WARNING: Beanstalk configuration header 'eb_codebuild_settings' is missing from Buildspec file; will not use Beanstalk Code Build integration
INFO: Deploying code to flask-daniel-test in region us-west-2
INFO: Getting version label from git with git-describe
Creating application version archive "app-38c0-220705_182941662302".
INFO: creating zip using git archive HEAD
INFO: git archive output: .elasticbeanstalk/
.elasticbeanstalk/config.yml
.gitignore
Makefile
README.md
application.py
buildspec.yml
requirements.txt
INFO: Uploading archive to s3 location: flask-daniel/app-38c0-220705_182941662302.zip
Uploading flask-daniel/app-38c0-220705_182941662302.zip to S3. This may take a while.
Upload Complete.
INFO: Creating AppVersion app-38c0-220705_182941662302
2022-07-05 10:29:47    INFO    Environment update is starting.
2022-07-05 10:29:51    INFO    Deploying new version to instance(s).
2022-07-05 10:29:55    INFO    Instance deployment successfully generated a 'Procfile'.
2022-07-05 10:30:04    INFO    Instance deployment completed successfully.
2022-07-05 10:30:09    INFO    New application version was deployed to running EC2 instances.
2022-07-05 10:30:09    INFO    Environment update completed successfully.

But when run from codebuild. it has the following:


text:
Q: Generalized power rule for derivatives Background
This background is not really necessary to answer my question, but I included it here to provide context.
This question has some programming aspects to it as well, but since my question is mainly about math, I decided to ask it here.
I'm trying to extend the implementation of automatic differentiation found here. This implementation, assuming I read it properly, does not work for functions of the form $F(x)=f(x)^{g(x)}$. I'm trying to modify it so that it does work for such functions.
Question
I'm trying to find a derivative for functions of the form $F(x)=f(x)^{g(x)}$. I specifically only care about the "normal" cases where $g(x)$ is an integral constant, or $f(x)$ is positive. Wikipedia has provided me with a "Generalized Power Rule":
$$(f^g)^\prime = f^g\left(f^\prime\frac{g}{f}+g^\prime\ln f\right)$$
The generalized rule however does not work for $f\leq 0$. In my implementation it is difficult to tell which of the two cases I'm working with, so I would rather not need to implement this generalized rule for the latter case, and the basic power rule for the former.
Is there a rule that works for both cases?

A: You have two conflicting goals here. If $y$ is arbitrary, then $x^y$ only
makes sense for $x>0$. Imagine, for example, that $y = \frac{1}{2}$.
Then $x^y = \sqrt{x}$ - what does that mean for negative $x$?
Note that switching to complex numbers doesn't help much - negative numbers do have
square roots then, but those are non-unique, and what's worse, the number
of solutions is highly dependent on $y$! E.g., $y^n = x$ has $n$ solutions in
$\mathbb{C}$. Which is $x^\frac{1}{n}$ supposed to be?
So you'll have to distinguish between two cases. One is $f(x)^{g(x)}$ for
positive $f$, and the other is $f(x)^k$ for constants $k \in \mathbb{Z}$
(i.e., no fractional exponents). You could generalize the second case to
$f(x)^{g(x)}$ for functions $g$ which take only integral values, but since
such functions are either constant or non-continuous, that case isn't really
interesting for purposes of differentiation, I think.
BTW, a far more interesting (and maybe solvable!) question is how to deal with
non-negative $f$, which nevertheless may take the value zero. $f(x)^{g(x)}$ is perfectly well-defined for those, but you'll still run into problems with the logarithm. Now, in some cases these problems are due to the fact that the derivative does, in fact, not exists at these points. But not in al cases! For example, $f(x) = x^2$ has derivative $0$ at $x=0$. The reason is, basically, that since $g$ is constant in this case, then  $g' ln f$ doesn't matter, because $g' = 0$, and similarly for $f'\frac{g}{f}$. But you can't just cancel things that way in all cases - that will produce wrong answers sometimes, because it actually depends on how fast things go to zero respectively infinity.

You might ask, then, why the non-uniqueness mentioned above doesn't prevent us from sensibly defining $\sqrt[x]{x}$ - after all, $y^n = x$ has two solutions for positive $x$ even in \mathbb{R}$. The reason is twofold

*

*The number of solutions doesn't explode as badly. We have one solution of $y^n = x$ for odd $n$, and two for even $n$.

*There's an order on $\mathbb{R}$, which makes the definition of $\sqrt[n]{x}$ as the (unique!) positive solution of $y^n = x$ quite natural.
The effect of (1) and (2) is, for example, that while it's not true that $\sqrt[n]{x^n} = x$, we do get at least that $\sqrt[n]{x^n} = |x|$. Trying to do the same over the complex numbers fails horribly. We could attempt to define $\sqrt[n]{x}$ as the solution of $y^n =x$ with the smallest angle (assuming we agree to measure angles counter-clockwise from the real axis). But then an $n$-th root always has an angle smaller than $\frac{2\pi}{n}$, so $\sqrt[n]{x^n}$ and $x$ would have very little in common except that their $n$-th power is $x^n$.

A: I think the problem here is stemming from confusion of the logarithm rule $$\ln a^r=r\ln a$$ This is only valid if we have $a>0$. Otherwise it does not hold. For example, $\ln((-1)^2)=\ln 1=0$ whereas $2\ln(-1)$ is not defined over the reals.
Instead, we can write $$\ln a^r=r\ln |a|,\;\;\;a^r>0$$ So in your case, let $y=x^2$. Then $\ln y=2\ln|x|$ so $$\frac{y'}{y}={2\over x}\implies y'=\frac{2y}{x}=2x$$ as desired. This holds for all $x\ne 0$.
In general, let $y=f(x)^{g(x)}$ and suppose that $f(x)^{g(x)}>0$ is defined and positive for all relevant $x$. Then we have $$\ln y=g(x)\ln |f(x)|,\;\;\;\frac{y'}{y}=g'\ln|f(x)|+g\frac{f'}{f}$$ so that
$$(f^g)'=f^g\left(g'\ln|f|+f'\frac{g}{f}\right)$$ We must have $f(x)\ne 0$ as expected.
NOTE: If a function satisfies the requirement that $f^g\ge 0$ for all $x$ in the domain, then at an anomalous point where f(x)=0 (such as the origin on the parabola $y=x^2$) the derivative there must be $0$ because it will be a minimum of the function (assuming it is differentiable at all).


text:
Q: Format JSON as XML I am struggling with creating a generic function that will convert a JSON object to XML
Note: the number of columns in the headers and body may vary. Additionally, I am not interested in values in the footer
I Have the following JSON structure:
{
    "header": [ "Room", "Maximum Capacity" ],
    "footer": null,
    "body": [
        [ "Game Room", "0" ],
        [ "gymnasium", "" ],
        [ "Library", "200" ]
    ]
}

I would like to format:
<root>
  <row>
    <Room>Game Room</Room>
    <MaximumCapacity>0</MaximumCapacity>
  </row>
  <row>
    <Room>gymnasium</Room>
    <MaximumCapacity></MaximumCapacity>
  </row>
 <row>
    <Room>Library</Room>
    <MaximumCapacity>200</MaximumCapacity>
  </row>
</root>

A: First of all, I'll assume you've already turned that JSON to a JavaScript object.
You should convert the header values to tag names. This will involve removing spaces, but in general you may need to do more, so to avoid invalid tag names. I will just focus on the space removal here.
Then use the DOMParser API to create an XML document. That way you avoid the traps of invalid characters in your XML tag contents.
Iterate the body data and create XML nodes dynamically, based on the tag names collected from the header data.
Here is how that works:

let obj = {
    "header": [ "Room", "Maximum Capacity" ],
    "footer": null,
    "body": [
        [ "Game Room", "0" ],
        [ "gymnasium", "" ],
        [ "Library", "200" ]
    ]
};

let tagNames = obj.header.map(name => name.replace(/\s*/g, ""));
let parser = new DOMParser();
let xmlDoc = parser.parseFromString("<root></root>", "text/xml");
let root = xmlDoc.getElementsByTagName("root")[0];
for (let data of obj.body) {
    let row = xmlDoc.createElement("row");
    for (let i = 0; i < tagNames.length; i++) {
        let cell = xmlDoc.createElement(tagNames[i]);
        cell.textContent = data[i];
        row.appendChild(cell);
    }
    root.appendChild(row);
}
var xmlString = new XMLSerializer().serializeToString(xmlDoc);
console.log(xmlString);

A: I think this is a good challenge for you to do, so I'm not giving you a solution but just pointing out a couple of hints:

*

*You can parse a JSON from string with JSON.parse

*You can iterate over the JSON key/value pairs by using Object.entries, e.g. Object.entries(json).forEach(([key, value]) => <do the magic>);

*You need a recursive function, because the nesting of a json (and xml) can have multiple levels. So you will probably have something like this:

function jsonToXml(json) {
  return Object.entries(json).map(([key, value]) => {
    if(isArray(value) || isObject(value)) { // TODO: Find out how to check if a variable is an array or object!
      return jsonToXml(value); // TODO: Think about on how wrap the value in the xml tag!
    }
    return value // TODO: Think about on how wrap the value in the xml tag!
  });
}


text:
Q: 'sudo apt-get update' failure Below is the o/p for sudo apt-get update:
/etc/apt$ sudo apt-get update
Get:1 http://01.archive.ubuntu.com/ubuntu bionic InRelease [242 kB]
Err:1 http://01.archive.ubuntu.com/ubuntu bionic InRelease
  The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 3B4FE6ACC0B21F32
Get:2 http://01.archive.ubuntu.com/ubuntu bionic-security InRelease [83.2 kB]
Err:2 http://01.archive.ubuntu.com/ubuntu bionic-security InRelease
  The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 3B4FE6ACC0B21F32
Get:3 http://01.archive.ubuntu.com/ubuntu bionic-updates InRelease [88.7 kB]
Err:3 http://01.archive.ubuntu.com/ubuntu bionic-updates InRelease
  The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 3B4FE6ACC0B21F32
Reading package lists... Done
W: GPG error: http://01.archive.ubuntu.com/ubuntu bionic InRelease: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 3B4FE6ACC0B21F32
E: The repository 'http://01.archive.ubuntu.com/ubuntu bionic InRelease' is not signed.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.
W: GPG error: http://01.archive.ubuntu.com/ubuntu bionic-security InRelease: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 3B4FE6ACC0B21F32
E: The repository 'http://01.archive.ubuntu.com/ubuntu bionic-security InRelease' is not signed.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.
W: GPG error: http://01.archive.ubuntu.com/ubuntu bionic-updates InRelease: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY <Pub_key_here>
E: The repository 'http://01.archive.ubuntu.com/ubuntu bionic-updates InRelease' is not signed.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.

All install commands failing because of this I believe.
I would just like to reset things back to normal as I messed this while uninstalling virtualbox,kubectl. I was just getting familiar with that. Experiment back fired.
I've tried replacing sources.list using this among other things I tried.
Any help is appreciated.

A: Add a public key to your keyring with the command like this:
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 3B4FE6ACC0B21F32

Then you should run sudo apt-get update normally.


text:
Q: how to build a custom lookup for my dictionary App I need to add a look-up for my dictionary app.All the other function of the app is working fine but i want to add a lookup function so that when the user tap a word in textview ,the word and its definition should appear on the lookup.
I had tried the motion sensor and other technique but could  solve my problem.
Any help or suggestion,i am stuck with this problem.

A: UITapGestureRecognizer is your friend here. Please take a look at following threads for implementation:

*

*Thread 1

*Thread 2

*Thread 3
BTW... Are you doing something different than Define action given by UITextView?


text:
Q: Executing multiple statements in a single roundtrip with Informix Is it possible to run multiple DML statements in a single roundtrip using Informix and .Net?
Example (of course this doesn't work):
var cmd = someIfxConnection.CreateCommand();
cmd.CommandText = @"
    insert into Foo(Bar, Baz) values (1, 2);
    insert into Foo(Bar, Baz) values (3, 4);";
cmd.ExecuteNonQuery();

A: As far as I'm aware, Informix allows you to perform multiple INSERT/UPDATE statements as you have in your example. What you CANNOT do is perform multiple statements that contain a SELECT.
For example, in SQL Server it is common to see code as follows:
INSERT INTO Foo(Bar, Baz) VALUES (1, 2); SELECT @@IDENTITY AS Id

This can be performed in a single command and would return the auto-incrementing primary key value from the newly inserted record.
This does not work within Informix however. You have to perform two distinct SQL commands. One to insert the record and one to retrieve the Id from the systables table:
SELECT DBINFO('sqlca.sqlerrd1') FROM systables WHERE tabid = 1


text:
Q: Preconditions and postconditions in interfaces and abstract methods I'm trying to implement my own programming language, and i'm currently doing lexing and parsing. I'm nearly done and want to add native support for class invariants, preconditions and postconditions.
public withdraw (d64 amount) : this {

    require amount > 0;
    require this.balance - amount > this.overdraft;

    # method code

    d64 newBalance = this.balance - amount;
    ensure this.balance == newBalance;
}

You would also be able to define class invariance at the top of the class.
class BankAccount {
    invariant this.balance > this.overdraft;
    # class body
}

These are my questions:

*

*Would it make sense to include class invariance in abstract classes, or interfaces.

*Would it make sense to include preconditions in abstract methods and interface methods.

*Would it make sense to include postconditions in abstract methods, or interface methods.

Thinking about it myself, i don't think it makes sense to include invariance or postconditions in interfaces, but i don't really see a problem with preconditions.
It would be possible to include pre- and postconditions in abstract and interface methods like below.
public interface BankAccount {
    public withdraw (d64 amount) : this {

        require amount > 0;
        require this.balance - amount > this.overdraft;

        # no other statements (implementation)

        d64 newBalance = this.balance - amount;
        ensure this.balance == newBalance;
    }
}

A: It really depends on whether your interface is stateful or stateless. It can be perfectly fine to include pre and/or post conditions for interface methods. In fact, we do this all the time. Any time you create a piece of javadoc (or any other tool), you are creating a contract. Otherwise, how could you test anything? It's important to realize that test-driven-development and design-by-contract have much in common. Defining a contract is essential to proper tdd - you first design an interface and create an informal contract for it (using human-readable language). Then, you write a test to ensure contract is satisfied. If we follow tdd classicists (https://www.thoughtworks.com/insights/blog/mockists-are-dead-long-live-classicists), we always write tests against contracts.
Now, to be more specific. If interface is stateful, we can easily express its invariants according to other methods. Let's take a java List interface as an example:
If you read the javadoc carefully, you will see there are a lot of invariants. For instance, the add method has the following contract:

*

*Preconditions: element cannot be null (if list doesn't support it -
it's a design smell btw in my opinion, but let's set it aside for
now)

*Postconditions: ordering is preserved, i.e. the ordering of other
elements cannot be changed
Since List interface is definitely stateful, we can reason about the state of the list using query method, like get, sublist etc. Therefore, you can express all the invariants based on interface's methods.
In case of an interface which is stateless, such as Calculator, we also define a contract, but its invariants do not include any state. So, for example, the sum method can have the following contract:
int sum(int a, int b)
Preconditions: a and b are integers (which is automatically guaranteed by static type checking in Java)
Postconditions: the result is an integer (again - type safety) which is equal to a + b

Our Calculator is a stateless interface, therefore we don't include any state in our invariants.
Now, let's get back to your BankAccount example:
The way you describe it, BankAccount is definitely a stateful interface. In fact, it's a model example of what we call an Entity (in terms of domain-driven-design). Therefore, BankAccount has it's lifecycle, it's state and can (and will) change during its lifetime. Therefore, it's perfectly fine to express your contracts based on the state methods of your class. All you need to do, is to move your amount, balance and overdraft to the top of the interface, either as properties (if your language supports it) or methods - it doesn't really matter. What's important is that amount, balance and overdraft are now part of your interface, and form the ubiquitous language of your interface. These methods/properties are integral part of your entire BankAccount interface - which means, they can be used as part of your interface's contract.
Some time ago I've implemented a very simple prototype of Java contracts, implemented as set of annotations supported by Aspect Oriented Programming. I tried to achieve similar goal to yours - to integrate contracts with language and make them more formal. It was just a very simple prototype, but I think it expressed the idea quite well. If you are interested - I should probably upload it to the github soon (I've been using bitbucket for most of the time so far).


text:
Q: PHP SPL RecursiveDirectoryIterator - getPath and ltrim path n00b here, be patient:)
I need to get a list of jpgs from my images directory and have it's subdirectory names appear as the CSS div class for a given image. I can get this to work, but I can't figure out how to get just the enclosing directory name as the div class without any of the path leading up to it. i.e
path to image is: images2/food/hotdog.jpg
I need:

The below works but doesn't create the array, I only get one image. If I remove my $path and $folder attempt, and have $thelist .= 'getPath().'   it works but I get
 and my javascript doesn't like that.
Here is my code:
<?php
$it = new RecursiveDirectoryIterator('images2');
$display = Array ( 'jpeg', 'jpg' );
foreach(new RecursiveIteratorIterator($it) as $file)

if ( In_Array ( SubStr ( $file, StrrPos ( $file, '.' ) + 1 ), $display ) == true )

$path = $file->getPath();
$folder = ltrim($path, "/images2");

$thelist .= '
getPath().'/'.$file->getFilename().'"rel="shadowbox['.$file->getPath().']">'.'getPath().'/'.$file->getFilename().'" />
';

?>

<?=$thelist?>

A: You just seem to be missing some curly brackets. You should put everything you want to happen in the foreach loop inside curly brackets. The same thing with the if statement. Without the curly brackets, only the next line applies to that previous statement.
Also, I think your parameter for your ltrim statement should be "images2/".
<?php
$it = new RecursiveDirectoryIterator('images2');
$display = Array ( 'jpeg', 'jpg' );
foreach(new RecursiveIteratorIterator($it) as $file)
{
    if ( In_Array ( SubStr ( $file, StrrPos ( $file, '.' ) + 1 ), $display ) == true )
    {
        $path = $file->getPath();
        $folder = ltrim($path, "images2/");

        $thelist .= '
getPath().'/'.$file->getFilename().'"rel="shadowbox['.$file->getPath().']">'.'getPath().'/'.$file->getFilename().'" />
';
    }
}

?>

<?=$thelist?>

A: AndrewR already presented a solution you can use. It doesn't handle two edge-cases though. What if your file's extension is "JPG"? What if your file doesn't have an extension at all?
<?php
$theList = ''; // initialize the variables you're using!
$allowed = array("jpg" => true, "jpeg" => true);
$it = new RecursiveDirectoryIterator('images2');
$rit = new RecursiveIteratorIterator($it);
foreach ($rit as $file) {
  $pos = strrpos($file, '.');
  if ($pos === false) {
    // file doesn't contain a . (has no extension)
    continue;
  }
  // file might be named foo.JPG (sadly quite common for windows / certain cameras)
  $extension = strtolower(substr($file, $pos+1));
  if (!isset($allowed[$extension])) { // this is a bit faster than in_array()
    // $extension is not allowed
    continue;
  }

  // what happens with your class, when you encounter a sub-directory like images2/my-images/easter-holidays/foo.jpg
  // that won't be accessible from CSS (without major escaping action)
  // try to keep classNames alphanumeric (like-this-class-name)
  $path = $file->getPath();
  $folder = ltrim($path, "images2/");

  // always, ALWAYS, respect the context!
  // htmlspecialchars() go around any non-literal output you make!
  $thelist .= '
getPath()) . '/' . htmlspecialchars($file->getFilename())
    . '"rel="shadowbox[' . htmlspecialchars($file->getPath()) . ']">'
    . 'getPath())
    . '/' . htmlspecialchars($file->getFilename()) . '" />
';
}

A: Protip : file extensions are as easy as :
end(explode(".", $path));
So lets :
$ite = new RecursiveDirectoryIterator("/mnt/shared/Media/Music/");
// Here are some extensions I want to keep
$keepers = array('ogg', 'mp3', 'wav', 'flac');
foreach (new RecursiveIteratorIterator($ite) as $filename => $cur) {
    // This bit of magic lowercases the file extension by grabbing everything past the last
    // '.' and checking whether said string is within the $keepers array, otherwise we just
    // skip this iteration and go on to the next.
    if (!in_array(end(explode(".", strtolower($filename))), $keepers)) { continue; }
    // Every $filename past here is fine as wine
    doit($filename); // :D
}


text:
Q: apollo-link-state update cache and return async resolver How to update cache and return async resolver with apollo-link-state.
Example:
import {
    LOGIN_FORM_QC as query
} from '../../querys'

import axios from 'axios'
import axiosError from '../axiosError'
import {URL} from '../../config'

const newState = (cache, object) => {
    const state = cache.readQuery({query})
    const data = {
        ...state,
        ...{loginForm: {
            ...state.loginForm,
            ...object
        }}
    }
    cache.writeQuery({query, data})
    return null
}

export default (_, input, {cache}) => {
    newState(cache, {loading: true, error: null}) //<-- this is not updating

    const state = cache.readQuery({query})
    const {uid, password} = state.loginForm

    return axios.post(`${URL}/login`, {uid, password})
        .then(res => {
            console.log(res)
            console.log(res.message)
        })
        .catch(err => newState(cache, {
            error: axiosError(err),
            loading: false
        }))
}

Basically, I want to set loading: true, and then execute promise. And promise will update state again.
As I understand, to update state I need to do return first. How to do it properly?

A: As of 22.03.2018:
This can't be done properly. To fix this issue you have to import apollo client and call writeQuery on it. Then it works.
GitHub issue tread: https://github.com/apollographql/apollo-link-state/issues/200


text:
Q: Override of protocol default implementation in a subsubclass doesn't participate in dynamic dispatch Consider following playground:
protocol A {
    func f() -> String
}

extension A {
    func f() -> String { return "AAAA" }
}

class B: A {}

class C: B {
    func f() -> String { return "CCCC" }
}

let a: A = C()
let b: B = C()
let c: C = C()

a.f() // "AAAA" - why?
b.f() // "AAAA" - why?
c.f() // "CCCC"

I don't get why a.f() and b.f() return "AAAA" - they are supposed to return "CCCC" because func f() -> String should be dynamically dispatched (as it declared in protocol).
If I change class B to look like this:
class B: A {
    func f() -> String { return "BBBB" }
}

then all three calls to .f() return "CCCC" as expected.
I feel like it is a bug in Swift compiler, I checked in Xcode 7.3.1 and 8.0-beta3, this behavior is reproducible in both.
Is this actually an expected behavior?

A: Thee are several rules involved here.
Sometimes Static Dispatch is used (in this case we must look at the type of the var/let to find out the implementation that will be used).
Other times Dynamic Dispatch is used instead (this means the implementation of the object inside the variable is used).
Let's consider the general example
let foo: SomeType1 = SomeType2()
foo.f()

I'll use the following definitions

*

*classic implementation of f() to indicate when f() is defined outside of a protocol extension (so inside a struct/class).

*default implementation of f() to indicate when f() is defined inside a protocol extension.

Dynamic Dispatch
If SomeType1 is a struct/class with it's own "classic" implementation of f() then polymorphism is applied.
It means that if SomeType2 doesn't have a classic implementation of f() then SomeType1.f() is used. Otherwise SomeType2.f() wins.
Static Dispatch
If SomeType1 doesn't have a classic implementation of f() but has a default implementation, then polymorphism is turned off.
In this case default implementation of the type of the let/var wins.
a.
Let's look at your first example
let a: A = C()
a.f() // "AAAA"

In this A doesn't have it's own classic implementation (because it's not a struct/class) but has a default implementation. So polymorphism is turned off and A.f() is used.
b.
Same rule for your second example
let b: B = C()
b.f() // "AAAA"

B doesn't have classic implementation of f(), but has a default implementation of f(). So polymorphism is turned off and B.f() (from the protocol extension) is used.
c.
Finally the object of type C is inside a constant of type C.
var c:C
c.f() // "CCCC"

Here C has a classic implementation of f(). In this case the protocol implementation is ignored and C.f() is used.
More
Let's see another example
protocol Alpha { }
extension Alpha { func f() -> String { return "Alpha"} }
protocol Beta { }
extension Beta { func f() -> String { return "Beta"} }

class Foo: Alpha, Beta { }

let alpha: Alpha = Foo()
alpha.f() // "Alpha"

let beta: Beta = Foo()
beta.f() // "Beta"

As you can see, again, the type of the constant containing the value wins. And if you put the Foo object inside a Foo constant you get a compile error
let foo: Foo = Foo()
foo.f() //

error: ambiguous use of 'f()'
foo.f()
^
Swift 2.playground:2:23: note: found this candidate
extension Beta { func f() -> String { return "Beta"} }
                      ^
Swift 2.playground:6:24: note: found this candidate
extension Alpha { func f() -> String { return "Alpha"} }


text:
Q: how to scanf a string until a specific string is entered in C I have been trying to write a code and a part of it is to scan multiple strings until it gets the 'Q' string. In this case the scanf should stop.
How should I do it?
I have tried several ways, but none of them worked.
char array[100]={0};

while (flag == 1)
{
    scanf("%s", array);
    if(array == 'Q') {
       flag=0;
    }

}

A: You could do it using the strcmp() function in the string.h library.
#include <stdio.h>
#include <string.h>

int main() {
    char array[100] = {0};
    int flag = 1;

    while (flag == 1) {
        scanf("%s", array);

        if (!strcmp(array, "Q"))
                flag = 0;
    }
    return 0;
}

A: you can do this with this code
ch= getchar();
while( (ch != 'q' || ch !='Q') {
ch  = getchar();
 putc(ch, fp);
   }

your mistake is herescanf("%s", array); it reads string and if condition you are checking without index of array variable
 you can check also by reading value with `scanf("%s", array); by looping value of array to find q in array
char a[100];
int i;
scanf("%c",&a[0]);
i=1;
while(a[i]!='q'&& a[i]='Q')
{

scanf("%c",&a[i]);
i++;
}

A: array[0] == 'Q'
#include <stdio.h>

int main(){
    int flag = 1;
    char array[100]={0};

    while (flag == 1)
    {
        scanf("%s", array);
        if(array[0] == 'Q') {
           flag=0;
        }

    }
}

A: This is what I would do, if you have to use scanf() (Notice the %99s to prevent buffer overflow -> 99 + '\0' == you buffer length)
#include <stdio.h>

int main()
{
    char array[100]={0};
    do
    {
        scanf("%99s", array);
    } while (!(strlen(array) == 1 && array[0] == 'Q'));
}

Online C Compiler


text:
Q: Getting resources Image path from Picturebox I have six pictureboxes and images with names 1 to 6. When form load, randomly six images appeared in pictureboxes. I click on any picturebox it should show me the image name, but it shows only the last randomly generated image name when I click any picturebox. I tried this How do you access the name of the image in a picturebox in Visual Studio using C#, but not get my job done. I don't want to use tag property.
     {
   ........
   for (i = 0; i < box.Count; i++)
        {
            int rand = r.Next(1, 7);
            int randM1 = rand - 1;

            imgname = name[randM1];
            box[i].Image = (Bitmap)rm.GetObject(imgname);
            box[i].Click += new EventHandler(Pop_Up);
        }

        }

    private void Pop_Up(object sender, EventArgs e)
    {
        var pb = sender as PictureBox;
        if (pb != null)
            MessageBox.Show(imgname);
    }


text:
Q: Git, heroku, pre-receive hook declined So I was trying to host a simple python script on Heroku.com, but encountered this error. After a little googling, I found this on the Heroku's website: git, Heroku: pre-receive hook declined, Make sure you are pushing a repo that contains a proper supported app ( Rails, Django etc.) and you are not just pushing some random repo to test it out.
Problem is I have no idea how these work, and few tutorials I looked up were for more detailed use of those frameworks. What I need to know is how can i use them with a simple 1 file python script. Thanks in advance.

A: Okay I got it. It was about some unused modules in requirements.txt, I'm an idiot for not reading the output properly ♂


text:
Q: JDBC, spring: How to bulk update using JdbcTemplate I'm trying to update one Column data with the value. CARD Table Example likes below.
| id | column_for_update |
| 1 | 10 |
| 2 | 11 |
| 3 | 12 |
| 4 | 13 |
| 5 | 14 |
...
Using jdbcTemplate(or other possible templates), I wanted to update column_for_update to 1000 * n(n = 1, 2, 3 ..), and result will be like ['10, 11, 12 ...'] -> ['1000, 2000, 3000'].
It is possible importing all objects into the application level and update them, but importing a large number of objects causes outOfMemory exceptions. How can I update this columns efficiently?

A: You can try changing your query to use a UPDATE/SELECT to multiply your id column by 1000:
UPDATE card a
INNER JOIN card b ON a.id = b.id
SET a.column_for_update = (b.id * 1000)

id
column for update

1
1000

2
2000

3
3000

4
4000

5
5000

See Fiddle.


text:
Q: Adding default hyphenation for transliterated Sanskrit I would like to be able to select, via polyglossia, Sanskrit in Roman script, and thus get some reasonable default hyphenation rules, as there are, in order of priority:

*

*ai, au, kh, gh, ch, jh, ṭh, ḍh, th, dh, ph, bh are to be considered as single letters and should never be hyphenated.

*Hyphenation is permissible after each vowel (a, ā, i, ī, u, ū, ṛ, ṝ, ḷ, ḹ, e, ai, o, au), if not followed by Anusvāra (ṃ) or Visarga (ḥ), in which case hyphenation is permissible after these two modifiers only.

*One could think of an expandable list of strings after which hyphenation also after a consonant would be o.k., coming to mind are prefixes such as sam, nir, abhy, maybe twenty of them, but also words appearing in compounds (a typical feature of Sanskrit), at the inclusion of which the task of building up such a list becomes endless.
Already the first two of these would ease the work of countless Sanskritists working with transliterated Sanskrit, so far needing to take care of hyphenation manually via discretionary hyphens. I would not mind starting this work, but I would need some pointers, and I would also like to hear ideas of other Indologists regarding this.
Update: Trying to get the existing pattern to load:
\documentclass{article}
\usepackage{fontspec}
\usepackage{polyglossia}
\setdefaultlanguage{english}
\setotherlanguage{sanskrit}
\newfontfamily\devanagarifont{FreeSerif}
\begin{document}
something

\begin{sanskrit}
kiṃcit
\end{sanskrit}

\end{document}

I get the following relevant lines in my log:
(/usr/local/texlive/2015/texmf-dist/tex/latex/polyglossia/gloss-english.ldf)
(/usr/local/texlive/2015/texmf-dist/tex/latex/polyglossia/gloss-sanskrit.ldf
(/usr/local/texlive/2015/texmf-dist/tex/latex/polyglossia/devanagaridigits.sty)

Package polyglossia Warning: No hyphenation patterns were loaded for `Sanskrit'

(polyglossia)                I will use \language=\l@nohyphenation instead on input line 11.

Package polyglossia Warning: \setlocalhyphenmin useless for unhyphenated language sanskrit on input line 11.

EDIT:
My laptop doesn't have a full TeX Live install, but tlmgr install hyphen-sanskrit does the necessary changes in (I believe) language.dat and language.def, and then a fmtutil --all will regenerate the format file. After that it seems to work.

A: As has been pointed out in the comments to the question, the hyphenation pattern for Sanskrit can also deal with transliteration. The following is an example, avoiding the devanagari font warning:
\documentclass{article}
\usepackage{fontspec}
\usepackage{polyglossia}
\setdefaultlanguage{english}
\setotherlanguage{sanskrit}
\newfontfamily\sanskritfont{Latin Modern Roman}
\begin{document}
something

\begin{sanskrit}
kiṃcit

\end{sanskrit}

\end{document}

It would be nice however if one would not need the
\newfontfamily\sanskritfont{Latin Modern Roman}
line, as for switching, e.g. between English and German one doesn't need to deal with fonts.


text:
Q: Local Notifications for Corona SDK (Android) Is there a way to implement local notifications while using the Corona SDK? This is android specific, as we have already found the iOS directions.
Cheers!

A: Local notification for now is iOS only on Corona... The Android version is not done yet.
When it gets done I will see to edit this with the directions of the android version.

A: Local notifications are done for iOS and Android: http://docs.coronalabs.com/api/library/system/scheduleNotification.html
It doesn't appear there is a way to set the icon for these notifications, but I'm sure they will add it at some point.
As of now (2012.12.07),  push (remote) notifications are available on iOS, but NOT Android.


text:
Q: How to get the uploaders for a class using carrierwave Given a Ruby class
Class Profile

  mount_uploader :avatar, MyUploader
  mount_uploader :cover_page, MyUploader
  mount_uploader :fav_cat_pic, MyUploader

end

How can I extract the "methods" (i.e. avatar, cover_page and fav_cat_pic) bound to the MyUploader at runtime?
Where MyUploader inherits from CarrierWave::Uploader::Base

A: Use the uploaders method
E.g.
Profile.uploaders


text:
Q: Android studio not executing latest code I have done some modifications to my code which upon running, Android studio behaves exactly the way it was before my changes.
As I place debug points on those new lines, I get a weird error message stating "No executable code found at line xx"
Following is a snapshot of the same. How do I resolve this issue ?

Edit: I have already tried Invalidate caches and restart, still stands unresolved.

A: I faced the same problem. It possible caused by AndroidStudio's new feature Instant Run. Try to stop current app, hit build->rebuild project then run app again.


text:
Q: How to set array values to a constructor c# I got the program running guys thanks alot i just deleted everything and started again from scratch! Now I am having problems with :
// The constructor
public Grade ( string cname , int Studentident , int [] homework , int [] classwork ,      int [] midexam , int [] finalexam)
{
    coursename = cname ;
    Studentid = Studentident ;
    hwgrade = homework ;
    cwgrade = classwork ;
    midegrade = midexam ;
    finalegrade = finalexam ;
}

// trying to set the values
Grade grade = new Grade('m',1,1,1,1,1);

it is giving me an error cannot convert from int to int[]

A: You must pass in arrays, not single values:
Grade grade = new Grade('m',
                        new int[] {1},
                        new int[] {1},
                        new int[] {1},
                        new int[] {1},
                        new int[] {1});

int is not the same as int[], after all.
The above assumes that your fields (such as hwgrade) are declared as int[] and not int.
If this is not the case, and the fields are actually integers and not integer arrays, you need to change the method signature to take integers instead of arrays:
public Grade(string cname,
             int Studentident,
             int homework,
             int classwork,
             int midexam,
             int finalexam)

A: You can replace with this code - delete [] if you wish use int, and not array of int
Grade ( string cname , int Studentident , int homework , int classwork ,      int midexam , int  finalexam)
{
  ...
}

Or create array with new int[] {1} and pass in parameters


text:
Q: Calculate packet size from traffic dump I have a traffic dump in csv file containing packet arrival time, frame length and boolean values for multiple flags.
Can someone please explain how to calculate packet size from the traffic dump.
I further want to generate distribution of the packet size in python.


text:
Q: How to force PyQt5 use for QObject class? I'm developping a small graphic application using Python 3 and PyQt5.
On the first computer I use, where only PyQt5 is installed, everything in my code is fine. But when I want to run my code on my other laptop, where both PyQt4 and PyQt5 are installed, I get the following error:
RuntimeError: the PyQt5.QtCore and PyQt4.QtCore modules both wrap the QObject class

Python interpreter locates the error in the file "ViewWindow.py", called from the main file.
As I have both PyQt4 and PyQt5 on this laptop, and because I can't uninstall PyQt4 (it would be too easy...), I wonder if it's possible to force use of PyQt5.QtCore, or something else to avoid this problem.
My configuration on this laptop: Debian 8, Python3.4, PyQt4 and 5 (without special configuration, installed from Debian repos), IDE = Spyder.
I put there first lines of my files main.py and ViewWindow.py.
# main.py
import sys
import sqlite3
import ViewWindow
from DataWindow import DataWindow
from PyQt5.QtCore import QObject # I tried adding this line, but nothing changed...
from PyQt5.QtWidgets import (QApplication,
                         QWidget,
                         QGridLayout,
                         QHBoxLayout,
                         QLabel,
                         QLineEdit,
                         QPushButton,
                         QTextEdit,
                         QVBoxLayout
                         )

class MainWindow(QWidget):
    # Some cool stuff

# ViewWindow.py
import sys
import sqlite3
from PyQt5.QtCore import QObject # same thing than above, adding this line doesn't change the output.
from PyQt5.QtWidgets import (QApplication,
                         QWidget,
                         QGridLayout,
                         QLabel,
                         QPushButton,
                         QVBoxLayout
                         )

class ViewWindow(QWidget):

Does someone knows how to make this code run ?
Thanks,
Jerry M.

Edit: I tried to run that script forcing use of Python3, and it worked... It seems that problem comes from iPython3.
Thanks for your help.

A: A RuntimeError with message

the PyQt5.QtCore and PyQt4.QtCore modules both wrap the QObject class

is raised the moment you try to import PyQt5.QtCore while PyQt4.QtCore was already imported before.
This error is raised within SIP, which is used to connect to Qt. Like it states, it's only allowed to have one module claiming to wrap QObject. Thus the error just tells you, that you're using PyQt4 and PyQt5 at once.
So you need to find the module loading PyQt4 to configure it to use PyQt5 instead. Alternatively you could try to put from PyQt5.QtCore import QObject before any other import and hope, that the module, which usually imports from PyQt4, is adaptable and able to use PyQt5 as fallback.


text:
Q: Can I make a SingleActiveRegion without help from the view? I've got a region adapter for a fluent RibbonTabItem and I want it show only a single RibbonGroupBox at a time. I expected this to do the job:
    protected override IRegion CreateRegion()
    {
        return new SingleActiveRegion();
    }

but it doesn't work (i.e. whenever I navigate the region to a new view, I get an additional new view), unless I make my views implement IRegionMemberLifetime and return false from KeepAlive.
Question: what do I miss? how to create a region that always clears its ViewsCollection before adding a new view?

A: My bad. I should have observed ActiveViews (not Views) of my region... works fine now.
Here's the full code:
public class RibbonTabItemRegionAdapter : RegionAdapterBase<RibbonTabItem>
{
    public RibbonTabItemRegionAdapter( IRegionBehaviorFactory regionBehaviorFactory ) : base( regionBehaviorFactory )
    {
    }

    protected override void Adapt( IRegion region, RibbonTabItem regionTarget )
    {
        region.ActiveViews.CollectionChanged += ( s, e ) =>
                                                {
                                                    switch (e.Action)
                                                    {
                                                        case NotifyCollectionChangedAction.Add:
                                                            foreach (var newItem in e.NewItems)
                                                                regionTarget.Groups.Add( (RibbonGroupBox)newItem );
                                                            break;
                                                        case NotifyCollectionChangedAction.Remove:
                                                            foreach (var oldItem in e.OldItems)
                                                                regionTarget.Groups.Remove( (RibbonGroupBox)oldItem );
                                                            break;
                                                    }
                                                };
    }

    protected override IRegion CreateRegion()
    {
        return new SingleActiveRegion();
    }
}


text:
Q: Spring Security method rules: returned value contains a Collection In Spring Security I want to secure a method incorporating returned values and using @PostAuthorize.
I want to add a constraing that will not allow one user to access to resources they are not owners. The problem I face is that I want to check principal id against one collection of values.
Scenario:
Domain objects:
public class Car implements Serializable {
    private Integer id;
    private Collection<Driver> drivers;
    ...
}

public class Driver implements Serializable {
    private Integer id;
    ...
}

Service:
@PostAuthorize("hasRole('ROLE_ADMIN') or principal.id == returnObject.drivers.driver.id")
public Car getCar(int id) throws DAOException {
    ...
    return carDAO.get(id);
}

Of course this Spel expression does not works.
SEVERE: El Servlet.service() para el servlet [dispatcher] en el contexto con ruta [] lanzó la excepción [Request processing failed; nested exception is java.lang.IllegalArgumentException: Failed to evaluate expression 'hasRole('ROLE_ADMIN') or principal.id == returnObject.drivers.driver.id'] con causa raíz
org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 42): Field or property 'driver' cannot be found on object of type 'org.eclipse.persistence.indirection.IndirectList'

I haven't seen any example that works over a Collection.
This unsolved question is similar but I don't know if matches my particular scenario.
Is possible to do something like that?
It is another way to do what I am trying to do?

A: Try to rewrite your expression as follows:
@PostAuthorize("hasRole('ROLE_ADMIN') or returnObject.hasDriverWithId(principal.id)")

and then add corresponding hasDriverWithId method to your Car class

A: Trying to access the property driver on a List doesn't really make sense.  Are you wanting the first item in the list?  What about returnObject.drivers[0].id?


text:
Q: Ubuntu14.04 boot error I am getting this message, while booting Ubuntu 14.04:
Try (hd0.0): FAT32: No ANG1
Try (hd0.1): EXT2: No ang1
Try (hd0.2): Extended:
Try (hd0.3): invalid or null
Try (hd0.4): EXT2:

A: Something seem wrong with your GRUB bootloader. You should try to reinstall it, by following the guide at Ubuntu Community Wiki. You will need to use a LiveCD for this task (you can write it to a USB pendrive).

A: Seems as if none of your hard disk partition has a boot sequence installed. I would say, boot using a Live USB of Ubuntu and create a backup of everything important and then clean install Ubuntu once again.
Hope this helps. :)


text:
Q: Driving UIImagePickerController from UITabBarController Here's my goal:
I'd like to show the UIImagePickerController from a TabBarController and once the photo is taken, I want the "Use" button to take me another view controller.
My problem:
I have MainCameraTabController which inherits from UIViewController and serves as the class that orchestrates the launching of UIImagePickerController and the picker's delegate. When the picker is finished, I try to launch another a different ViewController from MainCameraTabController but I get the error,
*** Assertion failure in -[UIWindowController transition:fromViewController:toViewController:target:didEndSelector:

If I put a timed delay between when the UIImagePickerController is dismissed and when I launch the next controller, it works okay but I'd like to do this more elegantly.
Is there a better way to structure my class inheritance so that I can have MainCameraTabController display the Picker and then a 2nd view controller?
// #
// # 1. Create the tab bar and add the MainCameraTabController:
// #
// tab1Controller and tab3Controller are also created
cameraTabController = [[MainCameraTabController alloc] init];

tabBarController = [[UITabBarController alloc] init];

NSArray *tabViewControllers = [NSArray arrayWithObjects:tab1Controller,
                                            cameraTabController
                                            tab3Controller, nil];

tabBarController.viewControllers = tabViewControllers;

self.window.rootViewController = self.tabBarController;

// #
// # 2. MainCameraTabController interface & implementation
// #

@interface MainCameraTabController : UIViewController <UINavigationControllerDelegate, UIImagePickerControllerDelegate>
{
}
- (void)showCamera;

@end

@implementation MainCameraTabController

// #
// # 3. Show the camera when the view loads
// #
- (void)viewDidLoad
{
    [self startCameraController:self usingDelegate:self];
}

- (void)showNextController
{
    FollowupController *fc = [[FollowupController alloc] initWithNibName:@"SomeView" bundle:nil];

    //  THIS IS THE PROBLEM
    [self presentModalViewController:cameraPicker animated: YES];
}

- (BOOL)startCameraController:(UIViewController *)controller
                usingDelegate:(id <UIImagePickerControllerDelegate, UINavigationControllerDelegate>)pickerDelegate
{

    UIImagePickerController *cameraPicker = [[UIImagePickerController alloc] init];
    // configure the cameraPicker

    // #
    // # Apple's doc specifies that UIImagePickerController must be launched with
    // # presentModalViewController
    // #

    [controller presentModalViewController:cameraPicker animated: YES];
}

// UIImagePickerControllerDelegate method called when photo taking is finished
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    // work to handle the photo

    // Dismiss the picker
    [[picker parentViewController] dismissModalViewControllerAnimated: YES];
    [picker release];

    [self showNextController];
}

@end

And on a related note, I checked to see what the picker's parentViewController is when
imagePickerController:didFinishPickingMediaWithInfo
is invoked and the parent is not MainCameraTabController but instead UITabBarController. Not sure why this is the case.

A: Because of the animation when dismissing the view, you need delay for the animation to finish before it can execute the next animation. You can solve this by setting the animated to NO. This will cut the animation and execute the next one immediately.
For the views, i had the similar experience, what i did was to switch the sequence of the views. I launched the view that i want to show after the picker first, in the viewDidload method, i created and display the picker so after the picker is dismissed, it will show the view that i want. If you want to make them look natural you could always play with the hidden property of the view to smoothen the flow.


text:
Q: Storybook v(6.4.18) starts giving below error after migration to angular 13 ERR! Error: The .storybook/assets asset path must start with the project source root.
ERR!     at /Users/kapilmittal/workspace/dx-gui/node_modules/@angular-devkit/build-angular/src/utils/normalize-asset-patterns.js:33:23
ERR!     at Proxy.map (<anonymous>)
ERR!     at normalizeAssetPatterns (/Users/kapilmittal/workspace/dx-gui/node_modules/@angular-devkit/build-angular/src/utils/normalize-asset-patterns.js:26:26)
ERR!     at normalizeBrowserSchema (/Users/kapilmittal/workspace/dx-gui/node_modules/@angular-devkit/build-angular/src/utils/normalize-builder-schema.js:23:71)
ERR!     at generateBrowserWebpackConfigFromContext (/Users/kapilmittal/workspace/dx-gui/node_modules/@angular-devkit/build-angular/src/utils/webpack-browser-config.js:126:66)
ERR!     at async generateI18nBrowserWebpackConfigFromContext (/Users/kapilmittal/workspace/dx-gui/node_modules/@angular-devkit/build-angular/src/utils/webpack-browser-config.js:74:20)
ERR!  MissingAssetSourceRootException [Error]: The .storybook/assets asset path must start with the project source root.
ERR!     at /Users/kapilmittal/workspace/dx-gui/node_modules/@angular-devkit/build-angular/src/utils/normalize-asset-patterns.js:33:23
ERR!     at Proxy.map (<anonymous>)
ERR!     at normalizeAssetPatterns (/Users/kapilmittal/workspace/dx-gui/node_modules/@angular-devkit/build-angular/src/utils/normalize-asset-patterns.js:26:26)
ERR!     at normalizeBrowserSchema (/Users/kapilmittal/workspace/dx-gui/node_modules/@angular-devkit/build-angular/src/utils/normalize-builder-schema.js:23:71)
ERR!     at generateBrowserWebpackConfigFromContext (/Users/kapilmittal/workspace/dx-gui/node_modules/@angular-devkit/build-angular/src/utils/webpack-browser-config.js:126:66)
ERR!     at async generateI18nBrowserWebpackConfigFromContext (/Users/kapilmittal/workspace/dx-gui/node_modules/@angular-devkit/build-angular/src/utils/webpack-browser-config.js:74:20)
info => Loading presets


text:
Q: How to do this query (az --query "custom-headers host") I can't just print the (value) information.
],
"id": "/subscriptions/x/resourceGroups/x/providers/Microsoft.Network/trafficManagerProfiles/x",
"location": "global",
"maxReturn": null,
"monitorConfig": {
  "customHeaders": [
    {
      "name": "host",
      "value": "site.company.com"
    }
  ],

az network traffic-manager profile list -g X --output table --query "[].{Traffic:name, URL:id.monitorConfig.customHeaders.value}"

A: You can pull the traffic manager name, customer headers values using the below Azure CLI query in Json format:
az network traffic-manager profile list --resource-group stacklogictest  --query "[].{name:name,url:monitorConfig.customHeaders[].value}"  --output json


text:
Q: Если в проект C# WF добавить новый NuGet пакет обновит ли его ClickOnce Разрабатываю приложение на C# WinForms .Net5, возникла потребность добавить в проект еще один NuGet пакет, при этом ClickOnce обновляется через сайт. Возник вопрос, при этом обновится ли нормально приложение, как с простым добавлением кода или нужны дополнительные замены?

A: @EvgeniyZ написал:

Достаточно посмотреть на то, что вам выдает ClickOnce после публикации. Ну а увидите вы там папку, внутри которой будет ряд других папок (своя папка под каждую версию), ну а в папке версии будут все ваши файлы проекта, только с расширением .deploy, ну а также будет файл .manifest, в котором будет описана структура вашего проекта, с именем, размером и хэшем каждого файла.
Собственно, вот вам и ответ - клиент должен получить все то, что в папки версии, если там есть нужная .dll (а она у вас там будет, ибо проект после NuGet будет зависеть от нее), то и эту библиотеку он тоже получит.


text:
Q: Linq group by with parent object How do I group so that I don't loose the parent identifier.
I have the following
        var grouped = mymodel.GroupBy(l => new { l.AddressId })
            .Select(g => new
            {
                AddressId = g.Key.AddressId,
                Quotes = g.SelectMany(x => x.Quotes).ToList(),
            }).ToList();

this returns

{ AddressId1, [Quote1, Quote2, Quote3...]}
{ AddressId2, [Quote12, Quote5, Quote8...]}

Now I would like to group these by Quote.Code and Quote.Currency, So that Each address has 1 Object-Quote (that is if all 4 quotes belonging to the address have the same Code and Currency). I would like the sum of Currency in that object.
This works, but I can't get how to add Address to this result:
        var test = grouped.SelectMany(y => y.Quotes).GroupBy(x => new { x.Code, x.Currency }).Select(g => new
        {
            test = g.Key.ToString()
        });}

this gives compile error, whenever i try to add AddressId to result:
        var test1 = grouped.SelectMany(y => y.Quotes, (parent, child) => new { parent.AddressId, child }).GroupBy(x => new { x.Provider, x.Code, x.Currency, x.OriginalCurrency }).Select(g => new
        {
            test = g.Key.ToString(),
            Sum = g.Sum(x => x.Price)
        });

compiler error as well:
        var test1 = grouped.Select(x => new { x.AddressId, x.Quotes.GroupBy(y => new { y.Provider, y.Code, y.Currency, y.OriginalCurrency }).Select(g => new
        {
            addr = x.AddressId,
            test = g.Key.ToString(),
            Sum = g.Sum(q => q.Price)
        };

A: I would do that this way:
    var grouped = mymodel.GroupBy(l => new { l.AddressId })
        .Select(g => new
        {
            AddressId = g.Key.AddressId,
            QuotesByCode = g.SelectMany(x => x.Quotes)
                            .GroupBy(x=>x.Code)
                            .Select(grp=>new
                              {
                                Code = grp.Key.Code,
                                SumOfCurrency=grp.Sum(z=>z.Currency)
                              }).ToList(),
        }).ToList();


text:
Q: How to override OSX's version of numpy when I import in Python 2.7? I'd like to use numpy 1.9 without deleting the version of numpy (1.8) that came with my Mac:
>>> import numpy
>>> numpy.version.version
'1.8.0rc1'
>>> numpy.__file__
'/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/__init__.pyc'

Since that version of numpy is in System, I'd rather not delete it. That said, pip recognizes that I have numpy 1.9 installed but I don't know how to reference it in my import statement.
$ pip list
...
numpy (1.9.0)
...

Thoughts?

A: It is important to note that there are two different installations of Python on your Mac. There is the System Python (/usr/bin), and also the /usr/local/bin python.
There are also two installations of pip. For example:
$ which pip
/usr/local/bin/pip
$ ls -l /usr/local/bin/pip
lrwxr-xr-x  1 dmao  admin  30 Feb 14 19:09 /usr/local/bin/pip -> ../Cellar/python/2.7.9/bin/pip

This is the homebrew pip. I assume you have numpy installed on the homebrew version of pip.
There is no System version of pip installed by default. The usual solution is to run easy_install pip and install a system version of pip, then pip install numpy (using system pip). However, you mentioned you wanted to leave the system numpy.

If you need to leave the system numpy untouched, you can run the /usr/local Python as your default Python instead of the system Python. Here we create a symbolic link from the default python to the local python, so that the local python becomes the default.
sudo ln -s /usr/bin/python /usr/local/bin/python

Then your default Python version becomes the one which matches your default version of pip.
You can restore your default Python version anytime by replacing the symlink. /usr/bin has the links you need.
$ ls -l /usr/bin/ | grep python
lrwxr-xr-x   1 root   wheel        76 Feb 21  2014 pythonw2.5 -> ../../System/Library/Frameworks/Python.framework/Versions/2.5/bin/pythonw2.5
lrwxr-xr-x   1 root   wheel        76 Feb 21  2014 pythonw2.6 -> ../../System/Library/Frameworks/Python.framework/Versions/2.6/bin/pythonw2.6
lrwxr-xr-x   1 root   wheel        76 Feb 21  2014 pythonw2.7 -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/pythonw2.7

Alternatively, if your System Python is being used for something, and/or you need to keep switching between versions of python packages, you could use virtualenv, which makes this much easier.

There are many different ways to manage python modules on a Mac. For example, What is the most compatible way to install python modules on a Mac?

A: For anyone reaching this in 2018, the proper way to do this is to make sure your brew packages folder precedes system packages folder in PATH:

*

*Brew install <mypackage> - python or numpy in this case

*Test that your brew package is now being found instead of system package by typing which <package> in terminal. It should say /usr/local/bin/<package> instead of /usr/bin/<package>.

*Explanation: System packages are found in /usr/bin while brew packages start in /usr/local/.. e.g /usr/local/bin, /usr/local/opt/<package>/bin.

*If system package is being found instead, test your PATH order by typing echo $PATH in your terminal. Is /usr/local/.. appearing earlier than system path?

*If not, you need to make sure /usr/local/bin comes first before /usr/bin so that the brew-installed executable is found before the system executable.

*To edit PATH: Run export PATH=/usr/local/bin:$PATH in terminal and also put it in ~/.bash_profile config file to make it permanent

*Test your PATH changes worked (echo $TEST), and that your brew package is being found instead of system package (which <package>)

*General Info: Brew will install packages in /usr/local/Cellar/.. and symbolically link the binaries (executables) to /usr/local/bin files

*Troubleshooting: Note that Brew can sometimes install packages with non-standard names like Python3, gcc-7 etc. So even if you have /usr/local/bin before /usr/bin in your PATH, when you test with which python it will still point to /usr/bin/<package>. In this case you need to manually create a symlink in your /usr/local/bin with the expected executable name. E.g in /usr/local/bin do ln -s python3 python


text:
Q: Hypergeometric $\lim_{z\to 1}{}_3F_2(a,b,c;d,e;z)$ with $a+b+c-d-e=0$? Is there anything special one can say about a hypergeometric function
$$\lim_{z\to 1}{}_3F_2\left({{a,b,c}\atop{d,e}};z\right)$$
in the case when $a+b+c-d-e=0$?

A: If $a+b+c=d+e$ then ${_3F}_2(\mathbf a;\mathbf b;z)$ is said to be zero-balanced which results in a logarithmic singularity at $z=1$. Specifically, as $z\to 1$:
$$
{_3F}_2\left({a,b,c \atop d,e};z\right)\sim-\frac{\Gamma(d)\Gamma(e)}{\Gamma(a)\Gamma(b)\Gamma(c)}\log(1-z).
$$
Hence
$$
\lim_{z\to 1}{_3F}_2\left({a,b,c \atop d,e};z\right)=\infty.
$$
See here for more details.


text:
Q: Manipulating several files at once in R I have several files in .txt format that I want to import into R, sort the rows them based on a variable and export only the first 50000 rows to a new file.
I have tried as below, but it never finishes and doesnt say that it is wrong. Any help please? Thanks.
 Map(function(x, y) {
+             all_content = readLines(x)
+             skip_second = all_content[-c(1:9)]
+             df <- read.table(textConnection(skip_second), header = TRUE, stringsAsFactors = FALSE)
+             df1 = df[order(df$pvalue),]
+             df2 = df1[1:50000, c(1:3,12)]
+             write.table(df2,row.names=FALSE, quote=FALSE, file = y)
+     }, x = myfiles, y = newfiles)

A: This isn't a duplicate, but the best answer is here: Sorting csv file by 5th column using bash
Use cat to combine the files and then pipe them to sort and pass the arguments as explained to sort on a particular field (you need to know the column number rather than the name). This will complete orders of magnitude faster than trying to do it in-memory in R.
If you're using Windows, I'm sorry but I don't know the equivalent PowerShell utility.


text:
Q: Situations that require protecting files against tampering when stored on a users computer I'm making a 'Pokémon Storage System' with a Client/Server model and as part of that I was thinking of storing an inventory file on the users computer which I do not wish to be edited except by my program. An alternative to this would be to instead to store the inventory file on the server and control it's editing by sending commands to the server but I was wondering if there are any situations which require files to be stored on a users computer where editing would be undesirable and if so how do you protect the files? I was thinking AES with some sort of checksum?

A: Logically it's impossible - if the clients computer has all the information to edit the inventory then it has all the information necessary to edit the inventory.
You can make it harder by encrypting the data and hiding the key inside your program, storing parts of the key in different places and calculating parts based on some maths is popular. But ultimatly it depends on how much time/effort they are going to put into it.  If this is just a kids game then simple encryption will do - if you are doing online gambling for big $$$ then it won't!

A:
I was thinking AES with some sort of checksum?

No. If someone de-complies your Software they will get the Key and be able to modify the Check Sum. The ONLY way to secure this data from being modified is store it on your server.
If you install on a Computer you don't have control of, assume the Computers owner has access to ALL the installed source code (and can modify it).

A: It's a hacking race you can't win, but you can make the contest interesting by signing and/or encrypting the data.  If there's a remote server involved, the remote can do the signing and verifying.
Also, consider that you need to prevent other things than fabrication or alteration - "good" inventory files might be shared (or sold), stored and reused, or many other creative kinds of abuse.
Remember that the weakest link is the one that will be attacked.  If your signing and verifying methods are good enough, the hackers will just target the decrypted/unsigned form of the data that has to exist in order for it to be used.


text:
Q: Sliding contact form with push effect preserving slide down of page content with jQuery UI I was using the following to slide down a contact form using jQuery:
$("#panel").slideDown(1000);

What happens here is that the rest of the content of the page slides down to accommodate the contact form, which is what I want, but rather than 'pushing' the contact form onto the page, such that the bottom of the form shows first, it 'reveals' the form, so that the top shows first.  I would like the 'push' effect, and from searching here it seems that including jQuery UI and the following would do the trick.
$("#panel").show("slide", { direction: "up" }, 1000);

Which it does.  However, now the rest of the content of the page doesn't slide down with the form, but rather jumps suddenly to the correct position to accommodate the form.
How can I achieve both effects, i.e. 'pushing' the form down, and sliding down the page content?
HTML

*FORM*

CSS
#panel {
    display:none;
}

#contact-form {
    width: 840px;
    height:auto;
    position:relative;
    left:50%;
    margin-left:-420px;
}


text:
Q: Append URL's in a given substring from a range of integers I am trying to format the URL's of a given file.
The URL's have this format:

http://randomtext&of=randomtext&=.com

There is an init method that reads the url's from a file:
  def __init__(self,filename=None):
    if filename:
        with open('urls.txt') as f:
            self.start_urls = [url.strip() for url in f.readlines()]

I can append on the end of the url with a range of integers:
    def __init__(self,filename=None):
    if filename:
        with open('urls.txt') as f:
            self.start_urls = [url.strip() for url in f.readlines()]
            self.start_urls = [url + str(i*10) for i in range(0,25) for url in self.start_urls]

My question is how to append the string on the substring 'of=' on the above URL's with a number of integers eg:

*

*http://randomtext&of=1randomtext

*http://randomtext&of=2randomtext

*http://randomtext&of=3randomtext
Thank you in advance!

A: You could use the sub() function from pythons re-module to replace the numbers in the urls with your numbers from a given range.
So build upon your provided example, one possible solution could be this:
import re

def __init__(self,filename=None):
    if filename:
        with open('urls.txt') as f:
            self.start_urls = [url.strip() for url in f.readlines()]
            self.start_urls = [re.sub("[0-9][0-9]*", str(i*10), url) for i in range(0,25) for url in self.start_urls]

You may want to check if there are other numbers in your urls that you don't want to be substituted and change the regex accordingly.


text:
Q: How to hide the text in the textbox value? I have got a problem with my PHP. In my code, it show that the text <?php if (!empty()) { echo ; } ?> is show in the value of the textbox when I run the script. I don't want to remove the text in the value, because I need to use them when I open the pop up to input the list of strings from the variable $email_str so I can output the list of strings in the textbox.
Here is the code:
<?php

include('config.php');

if($_GET['id'] != '')
{
    $id = $_GET['id'];
    $readDateTime = date("Y-m-d h:i:s");
    mysql_query("update tracker set isRead='1', readDateTime='$readDateTime' where id='$id'");
    header('Location: http://robsite.com/phpmailer/examples/blank.jpg');
    exit;
}
else
{

    echo "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>

        <meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
    <title>Send Email</title>
    <link type='text/css' rel='stylesheet' href='style.css'  />

    <form action='pr_send.php' method='POST' id='theForm'>

            <input type='button' name='to' value='' style='height:24px; width:24px; background: url(\"addressbook.png\"); border:none;' id='popup' > To:
            <input type='text' id='theField' name='to' value='<?php if (!empty($email_str)) { echo $email_str; } ?>' style='height:15px; width:650px'> (0)

            Subject:
            <input type='text' name='subject' style='height:15px; width:650px'>

            Message:
            <textarea name='message' cols='90' rows='20'></textarea>

               <input type='submit' name='send' value='' style='height:35px; width:100px; background: url(\"send.png\"); border:none'>

    </form>

";
}

  if (!empty($_POST['message']))
  {
    $emails = explode("\n", $_POST['message']); // explode textarea on a line break into an array
    $email_str = implode(", ", $emails); // take each of the emails and implode together with the ,

    echo ''; //call javascript function
  }
?>

When I ran the code in HTML, it works fine as the text did not show in the textbox.
How I can hide the text in the value when I run the html code in PHP?

A: The problem is that you have your PHP tag inside the string that you are printing with your echo. So, with the proposed fix, you are executing the PHP code and concatening it to the HTML string you want to print.
<?php

include('config.php');

if($_GET['id'] != '')
{
    $id = $_GET['id'];
    $readDateTime = date("Y-m-d h:i:s");
    mysql_query("update tracker set isRead='1', readDateTime='$readDateTime' where id='$id'");
    header('Location: http://robsite.com/phpmailer/examples/blank.jpg');
    exit;
}
else
{

    $email = !empty($email_str) ? $email_str : "";
    $html = "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>

        <meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
    <title>Send Email</title>
    <link type='text/css' rel='stylesheet' href='style.css'  />

    <form action='pr_send.php' method='POST' id='theForm'>

            <input type='button' name='to' value='' style='height:24px; width:24px; background: url(\"addressbook.png\"); border:none;' id='popup' > To:
            <input type='text' id='theField' name='to' value='".$email."' style='height:15px; width:650px'> (0)

            Subject:
            <input type='text' name='subject' style='height:15px; width:650px'>

            Message:
            <textarea name='message' cols='90' rows='20'></textarea>

               <input type='submit' name='send' value='' style='height:35px; width:100px; background: url(\"send.png\"); border:none'>

    </form>

";

echo $html;
}

  if (!empty($_POST['message']))
  {
    $emails = explode("\n", $_POST['message']); // explode textarea on a line break into an array
    $email_str = implode(", ", $emails); // take each of the emails and implode together with the ,

    echo ''; //call javascript function
  }
?>

A: You build a page of HTML as a PHP string, but you are trying to include PHP code within that PHP string.
PHP runs on the server side, not on the client.  If you send PHP code as text to the client it will be ignored.
Also, you are not giving $email_str a value until after you've already used it.
Move the code to set $email_str to before you use it, and also give it a default value of "" if the POST data is not there.
Then for your echo, split it into 3 parts:

*

*first part of page string up to value='

*echo $email_str  (which you now set to "" if no POST)

*rest of page

code
 echo "<!DOCTYPE html PUBLIC '-//W3    ...  <input type='text' id='theField' name='to' value='";
 echo $email_str
 echo "' style='height:15px; width:65  ... ";


text:
Q: CS8509 is reported by IntelliSense but not the C# compiler C# CS8509 warning is about the switch expression not being exhaustive. My Visual Studio reports this warning as error in IntelliSense but not during the build. The build still fails with MSBuild though. What could be the reason that VS is not reporting this error?
The problem happens on both Version 17.4.4 and 17.4.0

A: The project was skipped during the build. Clean, Rebuilding, closing and restarting Visual Studio did not help.
Removing the project from the solution and adding it back fixed the problem.


text:
Q: Resolving a path to an image file I have an imageView i am trying to set an image to based on the file path of an image the user selects from their gallery. I put the path into a database and then i pass that path into another activity to set the imageView to display. The path comes back at all steps as
/external/images/media/23

I have used multiple toasts to check the path in the activity before i pass the path, after receiving the path by the called method so i know the path is being sent from activity to activity correctly. However when i use the following code to set the imageView nothing appears.
File imgFile;
//Bitmap moviePic;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_movie_view);

    Bundle income = getIntent().getExtras();

    if(income != null)
    {
        mTitle = income.getString("title");
        mYear = income.getString("year");
        id = income.getLong("id");
        mPath = income.getString("path");

    }

    Toast.makeText(this, "path: " + mPath, Toast.LENGTH_SHORT).show();

    imV = (ImageView) findViewById(R.id.movieImage);
    //moviePic = BitmapFactory.decodeFile(mPath);
    imgFile = new File(mPath);

    imV.setImageURI(Uri.fromFile(imgFile));
    //imV.setImageResource(R.drawable.top);

    mVT = (TextView) findViewById(R.id.movieViewTitle);
    mVT.setText(mTitle);

    mVY = (TextView) findViewById(R.id.movieViewYear);
    mVY.setText(mYear);

    delete = (Button) findViewById(R.id.deleteMovie);
    delete.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            Intent deleting = new Intent();
            deleting.putExtra("Id", id);
            setResult(RESULT_OK, deleting);
            finish();
        }

    });
}

My guess is that im doing something wrong with the file path. Below is the code i use to resolve the path.
imgV.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            Intent addImage = new
Intent(android.content.Intent.ACTION_PICK);
            addImage.setType("image/*");

            startActivityForResult(addImage, 1);
        }
    });

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{
    super.onActivityResult(requestCode, resultCode, intent);

    switch(requestCode)
    {
    case 1:
        if(resultCode == RESULT_OK)
        {
            Uri image = intent.getData();
            imgV.setImageURI(image);
            moviePath = image.getPath();
            Toast.makeText(this, moviePath, Toast.LENGTH_LONG).show();
        }
    }
}

}

To find the image files i used the android emulator, browsed to google images and downloaded one or two. When i look in the DDMS It placed them in the mnt\sdcar\download\ folder which is obviously different than the path they are resolving to using the image.getPath() method. Is there another way i should be resolving the path? Or is there something im missing with the way the emulator file path works.