text:
Q: blocked UI in MVVM i am trying to build an application, following MVVM strategy. unfortunately my primitive example (please see below) is blocking the UI, although i specifically called for dispatcher. not sure why.. any suggestions?
class ViewModel : INotifyPropertyChanged
{
    private readonly Dispatcher _dispatcher;

    private string _name;

    public ViewModel()
    {
        _dispatcher = Dispatcher.CurrentDispatcher;
    }

    public string Name
    {

        get { return _name; }
        set
        {
            _name = value;
            InvokePropertyChanged("Name");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void InvokePropertyChanged(string propertyName)
    {
        var e = new PropertyChangedEventArgs(propertyName);
        PropertyChangedEventHandler changed = PropertyChanged;
        if (changed != null)
            changed(this, e);
    }

    public void send()
    {
        Action dispAc = () => NameAsync();
        _dispatcher.BeginInvoke(dispAc);
    }

    private void NameAsync()
    {
        Name = "name1";
        Thread.Sleep(5000);
    }
}

ps.
the first reply clarified a problem, thanks. for those of you, who does not use 4.5, i use
Task.Factory.StartNew(dispatchAction);

rest is the same.

A: Don't use Dispatcher.CurrentDispatcher for this task. Dispatcher.CurrentDispatcher bring you current executing thread which likely is the UI thread. That means, NameAsync() function is invoked in the UI thread, and of course still block the UI. You can use Task.Run() to execute your method asynchronously to avoid blocking UI :
Action dispAc = () => NameAsync();
Task.Run(dispAc);

A: You're dispatching the work on... the UI thread.  Do your work on a different thread, then, when you're done, dispatch the UI updates onto the UI thread.
Except you don't even have to.
As long as you're not on 3.0 of the framework, bindings will automatically marshal INPC PropertyChanged events onto the UI thread.  So you can dispense with any dispatching when touching these properties from a worker thread.
Using your example...
public void send()
{
    // We're on the UI thread here
    Task.Run(() => NameAsync());
}

private void NameAsync()
{
    // we're on some anonymous threadpool thread right now
    Name = "name1";
    // the event is fired on the threadpool, but bindings automatically marshall
    // UI update code onto the UI thread, so it returns directly before UI is
    // changed
    Thread.Sleep(5000);
    // and now our threadpool thread is sleeping.  Good night, sweet prince.
}

A: Change this,
public void send()
{
    Action dispAc = () => NameAsync();
    _dispatcher.BeginInvoke(dispAc);
}

to this
public void send()
{
 Action dispAc = () => NameAsync();
  _dispatcher.BeginInvoke(dispAc, DispatcherPriority.Background);
}

If you don't really need the UI thread to execute a method that requires the Dispatcher then just use TPL.
By default if you did not specify the DispatcherPriority it will use the Normal so it will use whatever the current thread is which is possible to hog the UI Thread e.g., while it tries to do some Render for other controls.
By the way, if you are using .NET 4.5 might just consider using the await and async keyword. If not, then like others suggest just spawn a different thread to update the UI. WPF's Dispatcher is smart enough to marshall the UI update to the main thread compared to Silverlight or WinRT.


text:
Q: How to get InstallR to download latest version of R? I just ran InstallR and it installed an incredibly old version of R from year 2011.
Needs["RLink`"];
InstallR[];
REvaluate["R.version.string"]

{"R version 2.14.0 (2011-10-31)"}

Is there anyway to make InstallR download a more recent version?  I know I can install R outside of Mathematica and use the "RHomeLocation" option but I am hoping this is not necessary.

redpajama_set_name: RedPajamaStackExchange


text:
Q: invalid conversion from 'char' to 'int* in C I have the following arrays:
int A[] = {0,1,1,1,1, 1,0,1,0,0, 0,1,1,1,1};
int B[] = {1,1,1,1,1, 1,0,1,0,1, 0,1,0,1,0};
int C[] = {0,1,1,1,0, 1,0,0,0,1, 1,0,0,0,1};
//etc... for all letters of the alphabet

And a function that prints the letters on a 5x3 LED matrix:
void printLetter(int letter[])

I have a string of letters:
char word[] = "STACKOVERFLOW";

and I want to pass each character of the string to the printLetter function.
I tried:
int n = sizeof(word);

for (int i = 0; i < n-1; i++) {
    printLetter(word[i]);
}

But I get the following error:  invalid conversion from 'char' to 'int*'
What should i be doing?
Thanks!!

A: Behind the parameter type error there is a deeper issue: you lack the mapping between a char and the corresponding int[].
Redefining printLetter as
void printLetter(char letter)

satisfies the compiler, but doesn't solve your problem per se. Whether inside or outside printLetter, you need to get the corresponding int[] for a given char.
A simple brute-force way to achieve this would be to use a switch, but a better way is to use a second array, i.e. something like this:
void printLetter(char letter) {
  static int* charToMatrix[] = { A, B, C, ... };
  int* matrixToPrint = charToMatrix[letter - 'A'];
  // print the matrix
}

Note that this is an example - I don't have access to a C compiler right now, so I can't guarantee it works straight away, but hopefully it illustrates the point well enough. It also lacks bounds checking, so it accesses memory in strange random places, possibly resulting in a crash, if you attempt to print an "unknown" character.
This solution is supposed to work for the uppercase letters; if you need to print lowercase letters or other characters as well, you might prefer going with an array of 256 elements, where only the elements at indexes corresponding to the "known" matrices are filled, and the rest is set to NULL.

A: You cannot so easly transform the 'a' from "stackoverflow" to the A - the array of ints. You can define all the arrays that represent a letter in one single letter and get them by the convertion of your letter to int.

A: What you need to do is convert from a character to one of your arrays.  So when you have the letter 'A', you'll want to use array A.  The easiest way to do this is via lookup table.
int *lookup[256];  // assuming ASCII
memset(lookup, 0, sizeof(lookup));

lookup['A'] = A;
lookup['B'] = B;
...

Then when you have a character, you can get the proper array:
void printletter(char c);
{
    int *data = lookup((unsigned char)c);

    // In case you get a letter that you don't know how to display
    if (data != NULL)
    {
        // display with data
    }
}

Instead of building up your array at runtime, you can also build up your array at compile time although it will be a bit harder as you will need to manually put in NULL pointers.
int *lookup[256] = {
    NULL,   // you need a total of 65 NULL's
    NULL,
    ...
    A,      // so this is at the correct position
    B,
    C,
    ...
};

A: The function is declared as void printLetter(int letter[]), which means it takes a pointer to an array of ints. On the other hand, word is an array of chars, and word[i] is a char, which is not at all the right type. If printLetter() is really just supposed to print a single character, you should change its argument to be a char.

A: void printLetter(int letter[])

should be
    void printLetter(char letter)
Because: word is a char[] word[i] is a character.


text:
Q: How to fetch the inbox from email agent in swift/objective c using mailcore framework or Any framework? Step 1: Link (https://github.com/MailCore/MailCore2)
Step 2: I have added mailcore-framework in my project
Step 3: pod install for UICKeyChainStore in my project done
Step 4: Send mail successfully using MCOSMTPSession, MCOMessageBuilder.
Step 5: My problem is that I am not able to fetch using mailcore. Is there any other framework for fetching mail (inbox)?

A: Sorry for late answer. I have two apps in the App Store, both of them use MailCore2, so I can explain you a thing or two about that.
Of course you can fetch the emails with MailCore2, this is the code. If you have any other doubt with MailCore2 write about that, I will try to find the answer.
var imapsession:MCOIMAPSession = MCOIMAPSession()

func prepareImapSession()
{
    // CONFIGURE THAT DEPENDING OF YOUR NEEDS
    imapsession.hostname = imapHostname // String
    imapsession.username = userName // String
    imapsession.password = password // String
    imapsession.port = portIMAP // UInt32 number
    imapsession.authType = MCOAuthType.saslLogin
    imapsession.connectionType = MCOConnectionType.TLS
}

func useImapWithUIDS()
{
    // There is more than one option here, explore depending of your needs
    let requestKind : MCOIMAPMessagesRequestKind =  .headers

    let folder : String = "INBOX"

    // HERE ALSO EXPLORE DEPENDING OF YOUR NEEDS, RANGE IT IS THE RANGE OF THE UIDS THAT YOU WANT TO FETCH, I SUGGEST TO YOU TO CHANGE THE  // NUMBER ONE IF YOU HAVE A LOWER BOUND TO FETCH EMAIL
    let uids : MCOIndexSet = MCOIndexSet(range: MCORangeMake(1, UINT64_MAX))

    let fetchOperation  = imapsession.fetchMessagesOperation(withFolder: folder, requestKind: requestKind, uids: uids)

    fetchOperation?.start
        { (err, msg, vanished) -> Void in

            if (err != nil)
            {
                error = err
                NSLog((err?.localizedDescription)!)
            }
            else
            {

                guard let msgs = msg as? [MCOIMAPMessage]
                    else
                {
                    print("ERROR GETTING THE MAILS")
                    return
                }

                for i in 0..<msgs.count
                {
                    // THE SUBJECT
                    let subject = msgs[i].header.subject

                    // THE uid for this email. The uid is unique for one email
                    let uid = msgs[i].uid

                    // The sequenceNumber like the nomber say it is the sequence for the emails in the INBOX from the first one                                     // (sequenceNumber = 1) to the last one , it not represent always the same email. Because if you delete one email then                              //next one will get the sequence number of that email that was deleted
                    let sequenceNumber = msgs[i].sequenceNumber

                }
            }
     }

 // MARK: - EXTRACT THE CONTENT OF ONE EMAIL, IN THIS FUNCTION YOU NEED THE uid, THE UNIQUE NUMBER FOR ONE EMAIL
func useImapFetchContent(uidToFetch uid: UInt32)
{

    let operation: MCOIMAPFetchContentOperation = imapsession.fetchMessageOperation(withFolder: "INBOX", uid: uid)
    operation.start { (Error, data) in
        if (Error != nil)
        {
            NSLog("ERROR")
            return
        }

        let messageParser: MCOMessageParser = MCOMessageParser(data: data)

        // IF YOU HAVE ATTACHMENTS USE THIS
        let attachments = messageParser.attachments() as? [MCOAttachment]

        // THEN YOU NEED THIS PROPERTIE, IN THIS EXAMPLE I TAKE THI FIRST, USE WHAT EVER YOU WANT
        let attachData = attachments?.first?.data

        // FOR THE MESSAGEPARSER YOU CAN EPLORE MORE THAN ONE OPTION TO OBTAIN THE TEXT
        let msgPlainBody = messageParser.plainTextBodyRendering()

   }

A: You can give https://github.com/snipsco/Postal a try. This is a framework which aims to provide simple access to common email providers.


text:
Q: IL Emit for invoking a delegate instance? Basically, I'm accepting an event name as a string, to get the EventInfo. Then, I'm discovering the event handler type and event argument type using reflection, creating a new delegate of that type (myEventHandler), and hooking it up with the event. When ever myEventHandler is invoked, I need to downcast and pass the arguments to the handler.
My code is as below. The 'handler' needs to be invoked via myEventHandler, when ever 'd' is invoked. I need to have some Reflection emit code there where I put ???. Any thoughts?
EventHandler handler = delegate(object sender, EventArgs eventArgs)
{
    //something will happen here
};

Type[] typeArgs = { typeof(object), derivedEventArgsType };

DynamicMethod myEventHandler = new DynamicMethod("", typeof(void), typeArgs);
var ilgen = myEventHandler.GetILGenerator();

//What should be the IL code here to
//cast derviedEventArgs to EventArgs and
//invoke the 'handler' above??????
ilgen.Emit(OpCodes.Pop);
ilgen.Emit(OpCodes.Ret);

Delegate d = dynamic.CreateDelegate(derviedEventHandlerType);

//addMethod is the add MethodInfo for an Event
addMethod.Invoke(target, new object[] { d });

Edit: Based on observations via Reflector.
The reflector generated code for a manually coded scenario is
.method public hidebysig instance void <Main>b__1(object sender, class ConsoleApplication2.MyEventArgs e) cil managed
{
    .maxstack 8
    L_0000: nop
    L_0001: ldarg.0
    L_0002: ldfld class [mscorlib]System.EventHandler ConsoleApplication2.Program/<>c__DisplayClass3::handler
    L_0007: ldarg.1
    L_0008: ldarg.2
    L_0009: callvirt instance void [mscorlib]System.EventHandler::Invoke(object, class [mscorlib]System.EventArgs)
    L_000e: nop
    L_000f: ret
}

And this is what I tried based on that.
ilgen.Emit(OpCodes.Nop);
ilgen.Emit(OpCodes.Ldarg_0);
ilgen.Emit(OpCodes.Ldfld,eh.GetType().GetField("handler"));
ilgen.Emit(OpCodes.Ldarg_1);
ilgen.Emit(OpCodes.Ldarg_2);
ilgen.EmitCall(OpCodes.Callvirt,eh.handler.Method,
               new Type[]{ typeof(object), typeof(EventArgs) });
ilgen.Emit(OpCodes.Nop);
ilgen.Emit(OpCodes.Ret);

But this is causing a run time error:

'Calling convention must be varargs'

Probably I'm missing something, need to have a better look into IL.

A: OK - this might help; it generates the IL to switch between delegate types, as long as they match the standard pattern. It adds a castclass only when necessary (so if you are going from a MouseEventArgs to an EventArgs it isn't necessary, but in the reverse direction it is). Since you are clearly working with reflection, I haven't used generics (which would make things harder).
The cheeky bit is that instead of using a capture class, it pretends the method belongs to the data I would capture, and uses the state as arg0. I can't decide if that makes it evil or clever, so I'll go with "clevil".
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;
using System.Windows.Forms;

class Program {
    static ParameterInfo[] VerifyStandardHandler(Type type) {
        if (type == null) throw new ArgumentNullException("type");
        if (!typeof(Delegate).IsAssignableFrom(type)) throw new InvalidOperationException();
        MethodInfo sig = type.GetMethod("Invoke");
        if (sig.ReturnType != typeof(void)) throw new InvalidOperationException();
        ParameterInfo[] args = sig.GetParameters();
        if (args.Length != 2 || args[0].ParameterType != typeof(object)) throw new InvalidOperationException();
        if (!typeof(EventArgs).IsAssignableFrom(args[1].ParameterType)) throw new InvalidOperationException();
        return args;
    }
    static int methodIndex;
    static Delegate Wrap(Delegate value, Type type) {
        ParameterInfo[] destArgs = VerifyStandardHandler(type);
        if (value == null) return null; // trivial
        if (value.GetType() == type) return value; // already OK
        ParameterInfo[] sourceArgs = VerifyStandardHandler(value.GetType());
        string name = "_wrap" + Interlocked.Increment(ref methodIndex);
        Type[] paramTypes = new Type[destArgs.Length + 1];
        paramTypes[0] = value.GetType();
        for (int i = 0; i < destArgs.Length; i++) {
            paramTypes[i + 1] = destArgs[i].ParameterType;
        }
        DynamicMethod dyn = new DynamicMethod(name, null, paramTypes);
        MethodInfo invoker = paramTypes[0].GetMethod("Invoke");
        ILGenerator il = dyn.GetILGenerator();
        il.Emit(OpCodes.Ldarg_0);
        il.Emit(OpCodes.Ldarg_1);
        il.Emit(OpCodes.Ldarg_2);
        if (!sourceArgs[1].ParameterType.IsAssignableFrom(destArgs[1].ParameterType)) {
            il.Emit(OpCodes.Castclass, sourceArgs[1].ParameterType);
        }
        il.Emit(OpCodes.Call, invoker);
        il.Emit(OpCodes.Ret);
        return dyn.CreateDelegate(type, value);
    }
    static void Main() {
        EventHandler handler = delegate(object sender, EventArgs eventArgs) {
            Console.WriteLine(eventArgs.GetType().Name);
        };
        MouseEventHandler wrapper = (MouseEventHandler)Wrap(handler, typeof(MouseEventHandler));
        MouseEventArgs ma = new MouseEventArgs(MouseButtons.Left, 1, 1, 1, 1);
        wrapper(new object(), ma);

        EventHandler backAgain = (EventHandler)Wrap(wrapper, typeof(EventHandler));
        backAgain(new object(), ma);
    }
}

Obviously you still need to generate a delegate to the event using regular methods (Delegate.CreateDelegate etc), but you can then wrap it to an EventHandler, or the reverse.

A: It turns out I was vastly over-complicating things! Barry Kelly had the right idea:
static T CastDelegate<T>(Delegate src)
    where T : class
{
    return (T)(object)Delegate.CreateDelegate(
        typeof(T),
        src.Target,
        src.Method,
        true); // throw on fail
}

That works for my test cases.


text:
Q: How to stop Windows Form program execution until text box input is given? I'm building a windows form application that stores employee information records in a database, including SSN. Next to the textbox where the SSN is input is requested, I have a checkbox that when clicked, shows me the full SSN instead of the last four digits. To ensure that only an administrator is accessing this information, I created a prompt form connected to a MS SQL DB that stores an admin password and would like to ask the user for a password for security purposes. Also, i'd like to be able to call this form whenever needed. I successfully implemented it but would like to add a feature that allows for 3 tries. Is there a way to stop the program execution and keep prompting the user for input in a textBox?
output is a variable that stores the result of the 'SELECT' query that gets the password.
confirmation is the Accept Button.
The only option i could think of forcing input was calling a new form. Only problem is, this code is inside the form and my gut tells me that's not the answer to this problem. I must be missing something.
     confirmation.Click += (sender, e) => {

            //If Password is correct.
            if (textBox.Text == output)
            {
                isCorrect = true;
                Pprompt.Close();
            }
            else
            {
                isCorrect = false;
                //While the password is incorrect.
                while (isCorrect == false)
                {
                    //textBox.Text = "";
                    if (textBox.Text == output)
                    {
                        isCorrect = true;
                        Pprompt.Close();
                        break;
                    }

                    tryCount++;

                    if (tryCount == 3)
                    {
                        MessageBox.Show("Access Denied.");
                        break;
                    }
                }
            }
         }

What I'd like to happen is for the form to keep asking me for input until the try limit is exceeded.

A: You cannot have the loop inside the click handler, because the UI freezes while it is running and the user does not get the opportunity make any entries.
Process only one entry and process the next when the user clicks the button again.
confirmation.Click += (sender, e) => {
    if (textBox.Text == output) // Password is correct.
    {
        isCorrect = true;
        Pprompt.Close();
    }
    else
    {
        isCorrect = false;
        textBox.Text = "";
        tryCount++;
        if (tryCount == 3)
        {
            MessageBox.Show("Access Denied.");
            Pprompt.Close();
        }
    }
}

Unless you are using multi-threading or async/await, the following is true:

*

*Winforms is event based. I.e., if no event handler is running, no code is running.

*If code (i.e. an event handler) is running, the user interface (UI) is frozen and the user cannot make any input. He cannot enter text or click any buttons, cannot scroll lists and cannot resize or move the window.

*While an event handler is running, no other event handler will ever be called. I.e., an event handler will never be interrupted by another one. This prevents you from having to deal with multi-threading issues unless you are using multi-threading explicitly.

*If an event should be fired (e.g. a timer tick) while an event handler (e.g. a button click handler) is running, the execution of the event handler associated to this new event will be deferred until after the first event handler returns.


text:
Q: DocumentRoot does not exist when SSLEngine on I have a Virtual Host Setup on an Apache2 Server on a Debian VM, I've created an SSL certificate from GoDaddy and downloaded the crt files (certificate and chain)
Before adding SSL, The DocumentRoot  was pointing to :

*

*/var/www/html/websitename/public_html/loader.php
and it was working just fine.
But, as I added SSLEngineOn, SSLCertificationFile, and SSLCertificationChainFile in the Virtual Host, the Apache2 Server refuses to start, here's the server log:
May 07 20:05:05 ns507219 systemd[1]: Starting The Apache HTTP Server...
May 07 20:05:05 ns507219 apachectl[2228]: AH00112: Warning: DocumentRoot [/var/www/html/websitename/public_html/loader.php] does not exist
May 07 20:05:05 ns507219 apachectl[2228]: AH00112: Warning: DocumentRoot [/var/www/html/websitename/public_html/loader.php] does not exist
May 07 20:05:05 ns507219 apachectl[2228]: AH00112: Warning: DocumentRoot [/var/www/html/websitename/public_html/loader.php] does not exist
May 07 20:05:05 ns507219 apachectl[2228]: Action 'start' failed.

Here's my config :
<VirtualHost websitename.ca:80>
    ServerAdmin admin@websitename.ca
    #SSLEngine on
    #SSLCertificateFile /etc/ssl/certs/mycertificate.crt
    #SSLCertificateChainFile /etc/ssl/certs/mychain.crt
    DocumentRoot /var/www/html/websitename/public_html/loader.php
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

        <FilesMatch "\.php$">
            SetHandler "proxy:fcgi://127.0.0.1:9000/"
        </FilesMatch>
</VirtualHost>
<IfModule mod_ssl.c>
    <VirtualHost websitename.ca:443>
        ServerAdmin admin@websitename.ca

        DocumentRoot /var/www/html/websitename/public_html/loader.php
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        SSLEngine on

        SSLCertificateFile /etc/ssl/certs/mycertificate.crt
        SSLCertificateChainFile /etc/ssl/certs/mychain.crt

        <FilesMatch "\.(cgi|shtml|phtml|php)$">
                SSLOptions +StdEnvVars
        </FilesMatch>
        <Directory /usr/lib/cgi-bin>
                SSLOptions +StdEnvVars
        </Directory>
    </VirtualHost>
</IfModule>

If I remove the if condition, the settings work normally, but SSL doesn't.


text:
Q: how to retrieve any Firebird database data type with just Delphi XE2 and Indy10 TIdTCPClient and TIdCmdTCPServer My program's TIdTCPClient can request and receive string data from my TIdCmdTCPServer, but I need my TIdCmdTCPServer to return any data type from a Firebird database.  How to do this?

A: You can cast any type from and to a string. So just add a prefix indicating what type of data you are sending on each transmission.
Something like :
send string: "s[Hello World]"
send integer: "i[97]"
send float: 'f[14.25]"
send date: "d[2016-11-02]"
...
...

A: I'd say first get your table structure
SELECT RDB$FIELD_NAME
 FROM RDB$RELATION_FIELDS
 WHERE RDB$RELATION_NAME='TABLENAME'
Write the result to a stringlist
Fields : Tstringlist;
Fields.add(fielddef);
And then send the result back via your tcpserver tcpserver.writestream(fields.tostream,0,1)


text:
Q: react-player not playing  tag from html I have create a static web page with golang
package main

import (
  "log"
  "net/http"
  "html/template"
)

func ex(w http.ResponseWriter, r *http.Request) {
    t, _ := template.ParseFiles("static/example.html")
    t.Execute(w, nil)
}

func main() {
  fs := http.FileServer(http.Dir("static"))
  http.Handle("/", fs)
  imagesHandler := http.FileServer(http.Dir("./video/"))
  http.Handle("/video/", http.StripPrefix("/video/", imagesHandler))
    http.HandleFunc("/ex", ex)

  log.Println("Listening...")
  http.ListenAndServe(":8080", nil)
}

example.html:
<!doctype html>
<video width="320" height="240" controls>
  <source src="/video/87.mp4" type="video/mp4">
</video>

So if I go to localhost:8080/ex on my browser I can see the video playing and everything
in my react app I am doing the following (I am using import ReactPlayer from 'react-player')
render() {
        return (
            <ReactPlayer url='http://localhost:8080/ex' playing controls height='400'/>
        )
    }

The video is not working - if I change the url with a youtube video it is working fine. Could you assist me on that
Thanks


text:
Q: Run Node.js project on Android non rooted device Please, help me, to run this Node.js github project https://github.com/sjitech/tunnel.js on Android 4.2+ non rooted device.
I can run it with termux, but how can I run it from Android Studio?
Is it possible to run it without terminal?
I can pay for the working solution.

A: Finally, I have done it with https://github.com/jxcore/jxcore.


text:
Q: How to take values from a column and assign them to other columns Here's what I have:
DECLARE @keyString2 nvarchar(500)
SET @keyString2 =
    (SELECT TOP (1) Key_analysis
    FROM  testing.dbo.[nameWIthoutSpecialChars])
IF CHARINDEX('Limit of Insurance Relativity Factors' , @keyString2) > 0
   EXEC sp_rename 'testing.dbo.nameWIthoutSpecialChars.Key2',
                  'Limit of Insurance Relativity Factors',
                  'COLUMN';

Basically what I'm doing with that code is renaming column names
with values that are from a different column. Though, if you see, there's a hardcoded string in CHARINDEX, I'd have to already know what's inside of that variable which makes it a real manual process. I could essentially just hardcode the EXEC and run it over and over without even needing the IF statement.
What I'm trying to accomplish is to rename columns based off of values inside of another.
To make it more clear I have a table like this:
+--------------------------------+---------+---------+
| Description                    | Column2 | Column3 |
+--------------------------------+---------+---------+
| string value 1, string value2  |         |         |
+--------------------------------+---------+---------+
| string value 1, string value2  |         |         |
+--------------------------------+---------+---------+
| string value 1, string value 2 |         |         |
+--------------------------------+---------+---------+

The values in the "Description" column will be the same throughout the table. What I want to have happen is that those values replace the other columns like so
+--------------------------------+----------------+----------------+
| Description                    | string value 1 | string value 2 |
+--------------------------------+----------------+----------------+
| string value 1, string value2  |                |                |
+--------------------------------+----------------+----------------+
| string value 1, string value2  |                |                |
+--------------------------------+----------------+----------------+
| string value 1, string value 2 |                |                |
+--------------------------------+----------------+----------------+

The only other caveat here is that there may be more or less string values than the 2 shown, I want to run this through multiple tables. Every table has 10 columns that are just like "Column1" and "Column2" in the example, meaning 10 potential columns that need to be renamed considering how many values are in the "Description" column

A: Experimental table,I didn't use #temporary table or table variable.
create TABLE bbbb  (
   Description VARCHAR(30) NOT NULL
  ,column2     VARCHAR(30)
  ,column3     VARCHAR(30)
);
INSERT INTO bbbb(Description,column2,column3) VALUES
('string value 1,string value2',NULL,NULL),
('string value 1,string value2',NULL,NULL),
('string value 1,string value2',NULL,NULL);

final query
declare @a varchar(100);
declare @b varchar(100);
set @a=(select distinct PARSENAME(REPLACE(Description,',','.'),1) from bbbb)
set @b=(select distinct PARSENAME(REPLACE(Description,',','.'),2) from bbbb)
EXEC sp_rename '[bbbb].[column2]', @a, 'COLUMN';
EXEC sp_rename '[bbbb].[column3]', @b, 'COLUMN';

select  * from bbbb


text:
Q: How to delete a bunch of NSData in NSUserDefault I stored some setting for the peripheral that connected to the iOS device, but I want to add a button for the user to delete this peripheral, this means I must delete all setting related to this peripheral.
The store for this is simple using NSData:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:self.appDelegate.defaultBTServer.selectPeripheralInfo];
[defaults setObject:encodedObject forKey:self.appDelegate.defaultBTServer.selectPeripheralInfo.uuid];
[defaults synchronize];

But how to delete the setting related to this selectPeripheralInfo.uuid?
I found the
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults removeObjectForKey:application.defaultBTServer.selectPeripheralInfo.uuid];

cannot work.

A: It looks like you might not be using the same key to add and remove the data. To add, you used:
self.appDelegate.defaultBTServer.selectPeripheralInfo.uuid

but to remove the data you used:
application.defaultBTServer.selectPeripheralInfo.uuid

If the values of those expressions aren't exactly the same, you won't be able to remove the data that you added because, obviously, the key will be wrong. So, check that.
Also, make sure that you call [defaults synchronize] after removing to update the defaults in storage.


text:
Q: How to prevent SIGPIPE in multi-thread program? I wrote a tiny httpd. But if I send many request to httpd in a short period of time, httpd will exit because of SIGPIPE.
After searching on Google, I add
signal(SIGPIPE, SIG_IGN);
sigset_t signal_mask;
sigemptyset(&signal_mask);
sigaddset(&signal_mask, SIGPIPE);
if(pthread_sigmask(SIG_BLOCK, &signal_mask, NULL) == -1)
perror("SIGPIPE");

and
send(fd, buf, strlen(buf), MSG_NOSIGNAL);

in my code to prevent SIGPIPE.
But httpd still exit because of SIGPIPE.
Can anyone help me solve the problem?
my code:
httpd.c
threadpool.c

A: The usual way is just ignore SIGPIPE (signal(SIGPIPE, SIG_IGN); -- which you say you've done), and then CAREFULLY check EVERY write and send call to ensure you are checking the return value properly and dealing with any EPIPE (or other) errors you get.
The danger of ignoring SIGPIPE is that it's easy to get a program that runs off writing to a closed connection, ignoring errors, and never terminates.
Once you ignore SIGPIPE, your program will never exit due to a SIGPIPE.


text:
Q: How to extract key value pairs from array of dictionaries? Swift 2.0 I have an arrayOfDictionaries that has been passed to a Table View Controller from a prepareForSegue.
I want to extract the key, value pairs and hold them in a new arrayToDisplay object.
I have initialized my collection data model in my viewWillAppear but I could use some help with my loadData function and how to put data into new arrayToDisplay
Table View Controller:
// data model
var collection: Collection!
var arrayToDisplay = [String: AnyObject]()

// data from previous controller, data is there
var arrayOfDictionaries = [[String: AnyObject]]()

viewWillAppear()
collection = Collection(id: "", photo: "", one: 0, two: 0, three: 0)
loadData()

func loadData() {

   for dict in arrayOfDictionaries {

        for (key, value) in dict {

             if key == "photo" {
                 self.collection!.photo = value as! String
                 arrayToDisplay += [key: value]
             }

             else if key == "id" {
                 self.collection!.id = value as! String
                 arrayToDisplay += [key: value]
             }

             else if key == "one" {
                    ...

One problem I have encountered is that the "key" does not change when it changes from one dictionary to the next.
Any help?
Thanks

A: I was able to solve this with a switch clause
func loadData() {

    for dict in arrayofDict {

          for (key, value) in dict {

                switch key {

                case "photo":
                ...
                case "id""
                ...
          }

Hope this helps someone!

A: I made a little tester class to try this out. Seems to be working fine. Maybe I don't understand what you expect it to do.
class ArrayDictTest {
    // data from previous controller, data is there
    var arrayOfDictionaries = [[String: AnyObject]]()
    var arrayToDisplay = [String: AnyObject]()

    func setup() {
        arrayOfDictionaries.append(["photo" : "some photo 1", "id" : "199"])
        arrayOfDictionaries.append(["photo" : "some photo 2", "id" : "299"])
        arrayOfDictionaries.append(["photo" : "some photo 3", "id" : "399"])
    }

    func loadData() -> [String]
    {
        // capture what happened
        var toReturn = [String]()
        for dict in arrayOfDictionaries {

            for (key, value) in dict {
                print(key)
                toReturn.append(key)
                if key == "photo" {
    //                self.collection!.photo = value as! String
                    arrayToDisplay[key] = value
                }

                else if key == "id" {
    //                self.collection!.id = value as! String
                    arrayToDisplay[key] = value
                }
            }
        }
        return toReturn
    }
}

let mytest = ArrayDictTest()
mytest.setup()
mytest.loadData()

What is the collection for?

A: remove else
if key == "photo" {
    self.collection!.photo = value as! String
    arrayToDisplay += [key: value]
}

if key == "id" {
    self.collection!.id = value as! String
    arrayToDisplay += [key: value]
}


text:
Q: Swaping pointers, deleting second object and create new pointer to second I'm trying to swap a pointer but all I get is access errors, are there any way to do this?
void Swap(someObject *first, someObject *next)
{
     delete first;
     first = next;
     // I'm guessing this delete first pointer as well ?
     delete next;
     next = new someObject();
};

Clarification on the method:
It should just swap first with second and create a new instance of "someObject" on second, it shouldn't swap like = FIRST = SECOND, SECOND = FIRST. Just first becomes second, and second becomes a new object or a new pointer to an object.
Second = Next.
SOLUTION
void Swap(someObject*& first, someObject*& next)
{
    std::swap(first, next);
    next = new someObject();
};

A: Yes, there is, but you are missing something. When you pass someObject *first, what happens is that in your function, there is a copy of the pointer that you passed, named first. Therefore if you change the value of first, you change the value of the local variable and it will not propagate to the original variable.
What you need to do is pass a reference to the pointer, in this way:
void Swap(someObject*& first, someObject*& second)
{
     delete first;    // Will delete whatever first points to
     first = second;
     delete second;   // first will now point to a deallocated object, you'd better set first = nullptr
     second = new someObject();    // Will really set second to something new
};

If you need just to swap two pointers, you can also use the standard library utility function std::swap.
I hope that helps.

A: There shouldn't be any access errors in that particular snippet, but you are indeed deleting both memory locations.
Note that outside your function, both pointers will be dangling because you're not modifying them, but copies.
To make the modifications persistent outside the functions, you'll need to pass the pointers by reference.
void Swap(someObject*& first, someObject*& second)

After calling this version, second will point to a valid location, first will not (because you delete the memory and never re-assigned the pointer).
Also, to swap, you can just use std::swap. Don't reinvent the wheel.

A: This for sure will result in access error since you're, at best, swapping local copies of the pointers. The arguments passed in must be references to pointers:
void Swap(someObject*& first, someObject*& second)
{
   someObject* temp = first;
   first = second;
   second = temp;
};

And btw, do not change the meaning of a well known name like 'swap' to mean some arbitrary exchange involving delete and new. swap means what it means. If you want a fancy operation that does your fancy assignment/delete/new, name it something else.

it should just swap first with second and create a new instance of
  "someObject" on second,

This is no Swap no matter how you slice it. I would call it 'Shift', but lets just call it MyOperation:
void MyOperation(someObject*& first, someObject*& second)
{
   someObject* temp = new someObject;
   delete first;
   first = second;
   second = temp;
};

Note how temp is preallocated since is the most likely to throw and you want to leave things in a coherent state in case of exception. The delete and the simple pointer assignments cannot throw.

A: Try this swap idiom instead.  Yours modifies the parameters (and deletes both objects) but does not actually swap the pointer values at the call site.
template <typename T>
void Swap(T & a, T & b)
{
    T x = a;

    a = b;
    b = x;
}

However, you could just as easily use std::swap for this; it will effectively do the same thing this template function does.


text:
Q: Mapproxy tms config reveals no layers I have configured MapProxy to reveal a wms service and tms service. Problem is, the tms don't show anything. (WMS works excellent)
Opening the demopage I cannot se any layers (as one can do in for example ORKa.MV)
I have preseeded the cache at C:\Pythonenv\mapproxy\cache\topo_color\sjobo_ruta\0\0\0.png and the file is there and looks good but when trying to access the seeded tile through http://127.0.0.1:8081/tms/1.0.0/topo_color/sjobo_ruta/0/0/0.png gives me a 404 error.
What am I missing?
globals:
  srs:
    axis_order_ne: ['EPSG:3008']
  cache:
    base_dir: C:\\Pythonenv\\mapproxy\\cache
    lock_dir: C:\\Pythonenv\\mapproxy\\cache\\locks
    tile_lock_dir: C:\\Pythonenv\\mapproxy\\cache\\tile_locks
    meta_size: [2, 2]
    meta_buffer: 80

services:
  demo:
  tms:
    use_grid_names: true
    origin: 'nw'
  wms:
    srs: ['EPSG:3008']
    versions: ['1.1.1', '1.3.0']
    image_formats: ['image/png']

sources:
  lm_wms1:
    type: wms
    req:
      url: http://user:password@maps.lantmateriet.se/topowebb/wms/v1?
      layers: topowebbkartan
    coverage:
      bbox: [149981, 6152974, 181706, 6184699]
      srs: 'EPSG:3008'

layers:
  - name: topowebbkartan
    title: Lantmateriet Topowebb - www.lm.se
    sources: [lm_wms1]

caches:
  topo_color:
    grids: [sjobo_ruta]
    sources: [lm_wms1]
    cache:
      type: file
      directory_layout: tms
      use_grid_names: true

grids:
  sjobo_ruta:
    srs: EPSG:3008
    bbox: [149981, 6152974, 181706, 6184699]
    bbox_srs: EPSG:3008
    origin: nw
    tile_size: [1024, 1024]
    res: [
        64.0000000000,
        32.0000000000,
        16.0000000000,
         8.0000000000,
         4.0000000000,
         2.0000000000,
         1.0000000000,
         0.5000000000,
         0.2500000000,
         0.1250000000,
   ]

I use MapProxy 1.12.0 with Python 3 and GDAL on Windows Server 2012

A: I solved my own problem. I forgot to add the cached tiles to the layers list. The above configuration holds another error in the grid section as I have set the origin to nw rather than sw.


text:
Q: How to get values from query result in slick I tried to use the Slick(3.0.2) to operate database in my project with scala.
Here is my part of code
val query = table.filter(_.username === "LeoAshin").map { user => (user.username, user.password, user.role, user.delFlg) }

val f = db.run(query.result)

How can I read the data from "f"
I have tried google the solution many times, but no answer can solved my confuse
Thanks a lot

A: f is a Future and there are several things you can do to get at the value, depending on just how urgently you need it. If there's nothing else you can do while you're waiting then you will just have to wait for it to complete and then get the value. Perhaps the easiest is along the following lines (from the Slick documentation):
val q = for (c <- coffees) yield c.name
val a = q.result
val f: Future[Seq[String]] = db.run(a)
f.onSuccess { case s => println(s"Result: $s") }

You could then go on to do other things that don't depend on the result of f and the result of the query will be printed on the console asynchronously.
However, most of the time you'll want to use the value for some other operation, perhaps another database query. In that case, the easiest thing to do is to use a for comprehension. Something like the following:
for (r <- f) yield db.run(q(r))

where q is a function/method that will take the result of your first query and build another one. The result of this for comprehension will also be a Future, of course.
One thing to be aware of is that if you are running this in a program that will do an exit after all the code has been run, you will need to use Await (see the Scala API) to prevent the program exiting while one of your db queries is still working.

A: Type of query.result is DBIO. When you call db.run, it turns into Future.
If you want to print the data, use
import scala.concurrent.ExecutionContext.Implicits.global
f.foreach(println)

To continue working with data, use f.map { case (username, password, role, delFlg) ⇒ ... }
If you want to block on the Future and get the result (if you're playing around in REPL for example), use something like
import scala.concurrent.Await
import scala.concurrent.duration._
Await.result(f, 1.second)

Bear in mind, this is not what you want to do in production code — blocking on Futures is a bad practice.
I generally recommend learning about Scala core types and Futures specifically. Slick "responsibility" ends when you call db.run.


text:
Q: Memory allocation counter for Linux I am looking for a counter provided by the Linux kernel counting the number of memory allocations performed by tasks on the system. I want to watch for high velocity changes in this counter, using Prometheus, in order to detect when some task on the machine does something stupid like allocating memory in loops.
I have found a bunch of different metrics that seem to be gauges, that is numbers representing the current state of the machine. Examples include nr_free_pages and kbhugused. These measure the current amount of something being available or used, but since one task allocating for example 1 page and then deallocating it again will result in an unchanged gauge these are of little use to me.
One thought I came across on IRC was if there was a counter for the number of times brk(2) was called, but I soon found that it was not the only system call used to allocate memory.
Right now I'm looking at pgalloc_normal in /proc/vmstat, but have yet to figure out exactly what it is a measure of.
Why do we want to look for huge rates of memory allocation you ask? Because memory allocation is costly. Not only do you have to switch into kernel space and back, the kernel also has a number of locks that can bring a system from having 2 CPUs with 80 execution threads processing data in parallel to just 1 thread allocating memory. This is a real world scenario we have encountered and want to watch for.

A: There's no such counter ready-made for you as far as I'm aware, but there are a number of ways to track system calls. I think the most straightforward is to use perf:
sudo perf stat -e syscalls:sys_enter_mmap -e syscalls:sys_enter_brk -I 1000 -a

This will show the number of mmap and brk calls per second, every second.
You can track all system calls with this variant:
sudo perf stat -e 'syscalls:sys_enter_*' -I 1000 -a

You can also monitor specific processes, using -p and the relevant pid, instead of -a.


text:
Q: javascript onchange in form html? its working fine until i put the  tag on select category can someone help me a bit , after i put the tag  its just not working..

function category(s1, s2) {
  var s1 = document.getElementById(s1);
  var s2 = document.getElementById(s2);
  s2.innerHTML = "";
  if (s1.value == "letters") {
    var optionArray = ["a|a", "b|b"];
  } else if (s1.value == "numbers") {
    var optionArray = ["1|1", "2|2"];
  } else if (s1.value == "soon") {
    var optionArray = ["|", "|", "|"];
  }
  for (var option in optionArray) {
    var pair = optionArray[option].split("|");
    var newOption = document.createElement("option");
    newOption.value = pair[0];
    newOption.innerHTML = pair[1];
    s2.options.add(newOption);
  }
}
<form>
  <select id="category" onchange="category('category','subcategory')">
    <option value=""></option>
    <option value="letters">Letters</option>
    <option value="numbers">Numbers</option>
  </select>

  <select id="subcategory"> </select>

</form>

A: To be compatible with older browsers, whenever you give an ID to some HTML element it's registered in a global scope under window so your category doesn't refer to the function but to the select element. Just name the function differently


text:
Q: Modifying switching power supply to produce any voltage(s) I have few units of 24V 3A output smps power bricks. I'm planning to mod one of this to generate 12V at least at 5A for my LED strips.
My idea is to tap two wires from the secondary winding of the 24V unit chopper transformer. This should give me high frequency AC which I can feed into another self made transformer, wound on ferrite toroid. The secondary of this transformer should have half number of turns but at least doubled wire diameter (compared to the primary) to generate 12V at 5 Amps.
After rectify and smoothed the 12V, regulation loop can be closed by sending the correct DC portion to the controller of the 24V smps brick so that it remain stable.
This scheme, if viable, will give me the freedom to wind required turns for any voltage I need for all my other projects.
My question is, how do I determine the wire diameter and number of turns for the primary of the toroidal transformer which I intend to built?

A: 12 LED style SMPS supplies are abundant and cheap.  You will save time and money to just buy one.
If you are looking to modify your 24 Volt supply for fun and education, that's a different story.


text:
Q: Analyze BSOD WHEA_UNCORRECTABLE_ERROR WIN8 Driver I have a new Computer for 3 Weeks now and i get a lot of WHEA_UNCORRECTABLE_ERROR BSODs.
I get These Bluescreens random every 30 - 50 minutes.
Here is the dump from WinDbg:

Microsoft (R) Windows Debugger Version 6.2.9200.20512 AMD64
Copyright (c) Microsoft Corporation. All rights reserved.
Loading Dump File [C:\Windows\Minidump\050913-7984-01.dmp]
Mini Kernel Dump File: Only registers and stack trace are available
Symbol search path is: SRV*c:\Symbole*http://msdl.microsoft.com/download/symbols
Executable search path is:
Windows 8 Kernel Version 9200 MP (4 procs) Free x64
Product: WinNt, suite: TerminalServer SingleUserTS
Built by: 9200.16551.amd64fre.win8_gdr.130306-1502
Machine Name:
Kernel base = 0xfffff80104018000 PsLoadedModuleList = 0xfffff801042e4b00
Debug session time: Thu May  9 17:12:45.597 2013 (UTC + 2:00)
System Uptime: 0 days 0:00:25.246
Loading Kernel Symbols
...............................................................
................................................................
..................
Loading User Symbols
Loading unloaded module list
.......

*

**

*Bugcheck Analysis                                    *

**

Use !analyze -v to get detailed debugging information.
BugCheck 124, {0, fffffa8008c87028, be200000, 2110a}
Probably caused by : GenuineIntel
Followup: MachineOwner
1: kd> !analyze -v

*

**

*Bugcheck Analysis                                    *

**

WHEA_UNCORRECTABLE_ERROR (124)
A fatal hardware error has occurred. Parameter 1 identifies the type of error
source that reported the error. Parameter 2 holds the address of the
WHEA_ERROR_RECORD structure that describes the error conditon.
Arguments:
Arg1: 0000000000000000, Machine Check Exception
Arg2: fffffa8008c87028, Address of the WHEA_ERROR_RECORD structure.
Arg3: 00000000be200000, High order 32-bits of the MCi_STATUS value.
Arg4: 000000000002110a, Low order 32-bits of the MCi_STATUS value.
Debugging Details:
BUGCHECK_STR:  0x124_GenuineIntel
CUSTOMER_CRASH_COUNT:  1
DEFAULT_BUCKET_ID:  WIN8_DRIVER_FAULT
PROCESS_NAME:  System
CURRENT_IRQL:  f
STACK_TEXT:
fffff880009f9868 fffff8010479193d : 0000000000000124 0000000000000000 fffffa8008c87028 00000000be200000 : nt!KeBugCheckEx
fffff880009f9870 fffff80104178969 : 0000000000000001 fffffa80066d7320 0000000000000000 fffffa8008c87028 : hal!HalBugCheckSystem+0xf9
fffff880009f98b0 fffff801047916e3 : 0000000000000728 0000000000000001 fffff880009f9a10 fffffa80066d7320 : nt!WheaReportHwError+0x249
fffff880009f9910 fffff8010479100c : 0000000000000010 fffffa80066d7320 fffff880009f9ac8 fffffa80066d7320 : hal!HalpMcaReportError+0x53
fffff880009f9a70 fffff80104790f07 : fffffa800678b760 0000000000000001 0000000000000001 0000000000000000 : hal!HalpMceHandlerCore+0xd4
fffff880009f9ac0 fffff80104790d64 : 0000000000000004 0000000000000001 0000000000000000 0000000000000000 : hal!HalpMceHandler+0xe3
fffff880009f9b00 fffff80104791edb : fffffa800678b760 fffff880009f9d30 0000000000000000 0000000000000000 : hal!HalpMceHandlerWithRendezvous+0xd4
fffff880009f9b30 fffff8010407057b : 0000000000000000 0000000000000000 0000000000000000 0000000000000000 : hal!HalHandleMcheck+0x40
fffff880009f9b60 fffff8010407032e : 0000000000000000 0000000000000000 0000000000000000 0000000000000000 : nt!KxMcheckAbort+0x7b
fffff880009f9ca0 fffff8800158e984 : 0000000000000000 0000000000000000 0000000000000000 0000000000000000 : nt!KiMcheckAbort+0x16e
fffff88002e1b888 0000000000000000 : 0000000000000000 0000000000000000 0000000000000000 0000000000000000 : intelppm!MWaitIdle+0x18
STACK_COMMAND:  kb
FOLLOWUP_NAME:  MachineOwner
MODULE_NAME: GenuineIntel
IMAGE_NAME:  GenuineIntel
DEBUG_FLR_IMAGE_TIMESTAMP:  0
FAILURE_BUCKET_ID:  0x124_GenuineIntel_PROCESSOR_CACHE
BUCKET_ID:  0x124_GenuineIntel_PROCESSOR_CACHE
Followup: MachineOwner

I have also reinstalled Windows 3 times now but every time i get These Errors.
Can anyone tell me whats the Problem is?
Greets

A: This might cause by INTEL CPU driver, for energy management or etc. try not to install intel cpu driver(might delivered with motherboard).


text:
Q: Domain of two different functions and combined functions equation I want to ask a question about the domain of two different functions in relation to an equation.
I was provided with two different functions:
$$f(x) = \frac{1}{x+1}, x > 3$$
$$f^{-1}(x) = \frac{1-x}{x}, 0 < x < \frac{1}{4}$$
$$g(x) = 2x^2 - 3, x \in \mathbb{R}$$
Now, I was asked to solve the equation:
$$fg(x) = \frac{1}{8}$$
This is what I did.
$$g(x) = f^{-1}(\frac{1}{8})$$
$$2x^2 - 3 = 7$$
$$2x^2 = 10$$
$$x^2 = 5$$
$$x = ±\sqrt{5}$$
This is what is given in the marking scheme, but I thought as $f(x)$ had domain $x>3$ I thought only $\sqrt{5}$ would be accepted.
Why are both values accepted?

A: Since we are dealing with the composite function $f\circ g$, the initial restriction (i.e. the domain of your equation) is: $$x\in D_g=\mathbb{R}, \\ g(x)\in D_f\Leftrightarrow g(x)\geq3\Leftrightarrow 2x^2-3\geq3\Leftrightarrow x^2\geq3$$
i.e.: $$x\in(-\infty,-\sqrt{3})\cup(\sqrt{3},+\infty)$$
This is why both solutions are accepted.


text:
Q: Windows phone and Sqlite. Making a select /*
List<BD.Usuario> items = null;
items = App.db.Query<BD.Usuario>("select Nome from Usuario");
lista.ItemsSource = items;
*/

string Email;
Email = App.db.Query<BD.Usuario>("select Email from Usuario").ToString();

MessageBox.Show(Email);

What's in the comment works to connect to a listbox.
Now I want to select a single record from the database to a variable!
The example code does not work. How would I do this select?
Look image in my Onedrive:
http://1drv.ms/1lIL44L
Open link. please.
var returnedCollection = App.db.Query<BD.Usuario>("select Email from Usuario");
        for (int i = 0; i < returnedCollection.Count(); i++)
        {
            string email = (returnedCollection[i]).ToString();
            MessageBox.Show(email);
        }

        return;

Would the button code (the code above). I have the value in the variable, but does not show the value in messagebox.

A: the Query method returns an IEnumerable<T> (in your case IEnumerable<BD.Usuario>), which can't be casted correctly to string unless you've overridden the base ToString() method. Consider that there could be several items in the return value of the query and not just one.
If you want to access all the elements present in the returned collection you should iterate on them:
var returnedCollection=App.db.Query<BD.Usuario>("select Email from Usuario");
foreach(var item in returnedCollection){
    string email=item.ToString();
    //Do Stuffs...
    }

Since it seems OP doesn't know the foreach construct, here's a version with a for...
var returnedCollection=App.db.Query<BD.Usuario>("select Email from Usuario");
    for(int i=0; i < returnedCollection.Count(); i++){
        string email=(returnedCollection[i]).ToString();
        //Do Stuffs...
        }

A: worked:
var returnedCollection = App.db.Query("select Email from Usuario");
for (int i = 0; i < returnedCollection.Count(); i++)
{
MessageBox.Show(returnedCollection[0].Email.ToString());
}

Thanks for the help.


text:
Q: Create Scratch Org with specific Territory2Settings I am trying to create a scratch org with Territory2 enabled, as we have this in our production org and I want to mimic it as good as possible.
The full documentation for this metadata can be found here.
I have set up the scratch org definition to enable Territory2, however I am unsure what values to add to the other parameters. I am referring to:

*

*defaultAccountAccessLevel

*defaultCaseAccessLevel

*defaultContactAccessLevel

*defaultOpportunityAccessLevel

*t2ForecastAccessLevel
According to the page referenced above, the field type is "string", however I cannot find any information about what string would related to which value in the settings. For example, for Account we have the following options:

Users in a territory can:

*

*View accounts assigned to

*the territory   View and edit accounts assigned to the territory

*View, edit, transfer, and delete accounts assigned to the territory

What string value would relate to each of these options?
Reference scratch org json below:
{
  "orgName": "Sample Org",
  "edition": "Enterprise",
  "language": "en_US",
  "hasSampleData": true,
  "settings": {
      "territory2Settings": {
        "enableTerritoryManagement2": true,
        "defaultAccountAccessLevel": ????,
        "defaultCaseAccessLevel": ????,
        etc...
    }
  }
}

A: Based on the comment by @sfdxfox I retried the data from an org where I manually set the different values in the GUI.
For future reference for anyone having this issue, here are the possible values (separated by a comma, in top-to-bottom order of possible alternatives in the GUI):
"territory2Settings": {
        "enableTerritoryManagement2": true,false
        "defaultAccountAccessLevel": "Read","Edit","All",
        "defaultCaseAccessLevel": "None","Read","Edit",
        "defaultContactAccessLevel": "Edit",????,
        "defaultOpportunityAccessLevel": "None","Read","Edit",
        "t2ForecastAccessLevel": "Read","Edit"
    }

Interestingly, I found no way of changing defaultContactAccessLevel in the GUI so I do not know the other possible values to this option (if there are any)
I found the full list of values: Here

A: There is a further bit of documentation, just in a different place.
However, it seems to also be incomplete. Your best option is to retrieve these settings from an existing org, then use those values in the JSON configuration file:
sfdx force:source:retrieve -m Settings:Territory2 -u production

Using the values from the mdapi output is your best option to make sure the values are correct. The two in the documentation appear to be Read and Edit, the others are not so clear, and I don't have an org set up with this to test.


text:
Q: Why does R behavior on adding to lists depend on order of assignment Adding to a sublist depends on list structure.  Adding an atomic element to a sublist as the first operation does not form a sublist.
Have simple test case
tl <- list()
tl[['a']][['aa']] <- list(1,2,3)
tl[['a']][['bb']] <- 'b'
tl[['a']][['cc']] <- list('a','b','c','d')

bl <- list()
bl[['bb']] <- 'b'
bl[['aa']] <- list(1,2,3)
bl[['cc']] <- list('a','b','c','d')

cl <- list()
cl[['a']][['bb']] <- 'b'
cl[['a']][['aa']] <- list(1,2,3)
cl[['a']][['cc']] <- list('a','b','c','d')

dl <- list()
dl[['bb']] <- 'b'
dl[['aa']] <- list(1,2,3)
dl[['cc']] <- list('a','b','c','d')
nl <- list()
nl[['a']] <- dl

The lists tl, bl, and nl are as I expect.  However list cl gives the following error:  Error in cl[["b"]][["aa"]] <- list(1, 2, 3) :
  more elements supplied than there are to replace.
R is constructing different a different type of list when it is assigned an atomic sublist before attempting to assign a list() sublist.

A: The "problem" is the default behavior of [[<-. This is a generic operator that does different things depending on what type of object you use it on. It's not exclusively used for lists. Consider this example
x <- NULL
x[["b"]] <- 'c'
# str(x)
#   Named chr "c"
#  - attr(*, "names")= chr "b"

Here x is defined as NULL. In this case, x[["b"]] turns x into a named vector (not a list). That's because R had no idea you wanted x to be a list so it just chose the most simple data type it could.
Assigning to a named slot and expecting a container to be automatically instantiation is called autovivification and languages like Perl really love that, it's not really a core concept in R. If you need a list where never there was a list before, be sure to explicitly created it.
cl <- list()
cl[['a']] <- list()
cl[['a']][['bb']] <- 'b'
cl[['a']][['aa']] <- list(1,2,3)
cl[['a']][['cc']] <- list('a','b','c','d')


text:
Q: Beginners question in dealing with drawables for Samsung Galaxy tab
In a curious to code my first app for Samsung tablet I got struck without knowing how to deal in naming drawable folders, I am using Android 3.0 ,to start with, I browsed through websites to learn its specification, i found Samsung Galaxy Tab 2 is of 7-inch display screen with 2048×1200 pixel resolution running on android 3.0 and other site pointed to Samsung Galaxy Tab 10.1 runs on same android 3.0 with resolution of 1280 x 800 pixels and 10.10 size ,My fist question, do Samsung have 2 different models running on same version of android ,Second  question is that if i need my app to run on this both tablet where should i place the images when my supports-screens tag points to android:anyDensity="true", what could be the layout and drawables, i need my app to run in tablets that supports 2.3 versions also
  drawable-hpi and layout-long
  drawable-large and layout
  drawable-xlarge and layout-long

if you feel that i have missed to understand the basic concept somewhere on the line please point out references to to elevate my  ignorance.

A: In general, these 10 inch Gingerbread tablets should have an xlarge screen size and a mdpi pixel density.


text:
Q: Trouble with exporting data with rows and columns switched I am trying to export a non-rectangular nested list of data as an xlsx spreadsheet. If I export an un-nested list, it shows up as a single column. However when I go to export the nested list, it makes each sublist a row where I would like each sublist to be a column. My datasets are large and XLSX has a limit on the number of columns, so Mathematica will not even attempt the export and instead throws error Export::toomany3. This means I cannot swap the rows for columns in Excel. Furthermore, Mathematica won't let me transpose before exporting since the list is not rectangular. I can export the data as a CSV then use an online tool to transpose it, but it just seems like there's got to be a simple way to get Mathematica to do it. Any help would be appreciated.
data = Table[Range[i], {i, {51125, 26336, 10932, 3834, 1579}}];(*Example data*)
Export["data.xlsx", data[[1]]] (* Gives me a spreadsheet with 1 column *)
Export["data.xlsx", data] (* Tries to export data[[i]] as row instead of column *)
(* throws error because exceeds column number limit for xlsx *)

Solution
provided by george2079:
Export["data.xlsx", Function[{cols}, Transpose[PadRight[#, Max[Length /@ cols], ""] & /@ cols]]@data]

Thanks for your help!

A: First, you must convert your rows to columns. For instance:
data1 = {#} & /@ RandomReal[{0, 1}, 51125];
data2 =  {#} & /@ RandomReal[{0, 1}, 26336];

then, export:
Export["data.xlsx", "Sheets" -> {"random 1" -> data1, "random 2" -> data2}, "Rules"]

A: following my comment here is how to use PadRight
c1 = {1, 2}
c2 = {3, 4, 5}
Export["test.xls",
  Function[{cols},
    Transpose[PadRight[#, Max[Length /@ cols], ""] & /@ cols]]@{c1,c2}]

( verified the "" pad gives an empty cell in excel )
also if you don't mind padding with zeros even more simply:
Export["test.xls", Transpose@PadRight@{c1, c2}]

unfortunately you can't specify the pad element with the array form of PadRight


text:
Q: Symfony/PHPUnit mock services I'm writing functional tests for Symfony w/ PHPUnit, and my mocks aren't working. It's possible I misunderstood how they work though.
In my unit test's setUp() method I have this code:
...
// Create a stub
$stub = $this->getMockBuilder('\\ApiBundle\\Util\\WordPressBridge')
    ->disableOriginalConstructor()
    ->getMock();

// Configure the stub.
$user = new WordPressUser();
$user->setUsername('dummy');
$stub->expects($this->any())
     ->method('checkCredentials')
     ->will($this->returnValue(true));
$stub->expects($this->any())
     ->method('getUser')
     ->will($this->returnValue($user));
...

In my Symfony application, I have a service defined:
services:
    api.wp_bridge:
        class: ApiBundle\Util\WordPressBridge
        arguments: [@service_container]

It's my understanding that the mock should be replace the real WordPressBridge, but that isn't what's happening. My original is still being used. Am I missing something?

A:
It's my understanding that the mock should be replace the real WordPressBridge, but that isn't what's happening. My original is still being used. Am I missing something?

Basically you have to replace your service somehow in the Symfony Container.
If you doing "functional testing" then probably you should create test "dummy" service for "test" env which will overwrote original one. You can do something like that:
in src/YourBundle/Resources/config/services.yml
services:
    api.wp_bridge:
        class: %api.wp_bridge.class%
        arguments: [@service_container]

in app/config/config.yml
parameters:
    api.wp_bridge.class: "ApiBundle\Util\WordPressBridge"

in app/config/config_test.yml
parameters:
    api.wp_bridge.class: "ApiBundle\Util\TestWordPressBridge"

Then functional test will use "ApiBundle\Util\TestWordPressBridge" - cause it is executed in "test" env.
You can try to mock container and pass it to test kernel but this can be painfull without some other mocking lib (in pure PHPUnit).
Personally I am using phpspec2 for "unit" testing where mocking is just easy :) and for some "acceptance criteria" stuff I am using behat and mink


text:
Q: Firebase Authentication Javascript: setCookie for pending Credential for redirect I am trying to get the multiples auth to link using singinwithredirect. I grab the error .credential and use JSON.stringify to pass it through a cookie.
From there, I convert it back to an object by using JSON.parse, but when I tried to pass the credential object into result.user.link(credential), it's giving me an error stating:
firebase.js:74 Uncaught Error: link failed: First argument "credential" must be a valid credential

Do I have to convert JSON object into a Firebase object in order to pass it in the credential? What the object originally looks like:
Ef {accessToken: "EAAQmrlAUQpEBAL4oiPWEJy.......", provider: "facebook.com"}

What the object looks like after converting back to JSON from cookie ('string'):
Object {accessToken: "EAAQmrlAUQpEBAL4oiPWEJy.......", provider: "facebook.com"}

A: First I recommend that you use sessionStorage instead of cookies as this contains an OAuth access token which you don't want to leak on page close.
After you parse the json object.
Check the provider field. Based on that you can figure out what type of credential it is. For example if provider is facbeook.com:
var cred = firebase.auth.FacebookAuthProvider.credential(obj['accessToken');
In that case you would initialize the credential with the accessToken in the parsed object.

A: You should be careful to remove cached accessToken and secret after you are done with them.
The parsed JSON is possibly not a valid firebase object to link the pending credentials. You must pass it into the firebase auth provider object first before linking.
// Read cookie
var pendingCred = document.cookie;

// Parse
var pendingCredObj = JSON.parse(pendingCred);

// Delete cookie
document.cookie ="pendingCred=" + null + "; expires=0";

// Link with appropriate auth provider object
if (pendingCredObj.provider == "twitter.com"){
    var pendingCredObjProv = firebase.auth.TwitterAuthProvider.credential(pendingCredObj.accessToken, pendingCredObj.secret);
} else if (pendingCredObj.provider == "facebook.com"){
    var pendingCredObjProv = firebase.auth.FacebookAuthProvider.credential(pendingCredObj);
} else if (pendingCredObj.provider == "google.com"){
    var pendingCredObjProv = firebase.auth.GoogleAuthProvider.credential(pendingCredObj);
} else if (pendingCredObj.provider == "password"){
    var pendingCredObjProv = firebase.auth.EmailAuthProvider.credential(pendingCredObj);
}

// Link pending credentials to original user account
auth.currentUser.link(pendingCredObjProv).then(function(user) {
    console.log("Account linking success", user);
}, function(error) {
    console.log("Account linking error", error);
});


text:
Q: Java: when serializing an object, I get NotSerializableException from classes I'm not trying to serialize I have three packages inside src: model, view, and controller.
view has a couple of JFrames, model has a couple of classes that deal with the logic of the program, and controller has one class containing instances of the JFrames from view, and only one object from model, called 'board'.
I should mention that in model there is a class called Saver that only has a static method to load and a static method to save this object 'board'.
When I try to serialize the object 'board' (board and all of the classes in model are Serializable), I get in the stack trace NotSerializableException from all of the classes in view, and all of the inner classes in the controller class, when I am only trying to serialize 'board', which belongs to model, and all of board's variables are Serializable.
Here are the methods to save and load from the Saver class:
public class Saver {

public static void saveBoard(Board board) throws IOException{
    FileOutputStream fileOutputStream = new FileOutputStream("gosavefile.gsf");
    ObjectOutputStream obout = new ObjectOutputStream(fileOutputStream);

    obout.writeObject(board);

    fileOutputStream.close();
    obout.close();
}

public static Board loadBoard() throws IOException, ClassNotFoundException{
    FileInputStream fileInputStream = new FileInputStream("gosavefile.gsf");
    ObjectInputStream obin = new ObjectInputStream(fileInputStream);

    Board board = (Board) obin.readObject();

    fileInputStream.close();
    obin.close();

    return board;
}

}
And this is where I call the saveBoard() method from the controller class:
public void save(){
    try{
        Saver.saveBoard(board);
    } catch (IOException e) {
        new SaveErrorWindow(mainMenuWindow.getLanguageManager());
        e.printStackTrace();
    }
}

I have done it this way once before, with another program using the same exact scheme and it worked perfectly. So I really can't figure out why it is trying to serialize everything else when I'm only serializing 'board'.
If any other part of the code is needed, just ask.
Thank you in advance!

A: In order to be serialized, an object must:

*

*Implement Serializable

*All non-transient and non-static fields must
be primitive or serializable. Arrays are consider serializable, but its elements must be serializable

A: It's not enough that the classes implement java.io.Serializable. You also have to guarantee that all fields are serializable as well (either primitives or classes that implement Serializable), and so on. If any class has a non-serializable field which is not declared as transient, serialization will fail. Your stack trace should point which class caused the problem.


text:
Q: Get probabilities from distribution function. The question is

$F$ is a distribution function.  Show that
  $$P\{X = x\} = F(x) - \lim_{y \uparrow x}F(y)$$

This is trivial.  But how can we prove it in a formal way?

A: $F(y) = \Pr (X \le y)$ so $$\lim_{y \uparrow x}F(y) =\lim_{y \uparrow x} \Pr (X \le y) =  \Pr (X \lt x) $$ and thus $$F(x) - \lim_{y \uparrow x}F(y)=  \Pr (X \le x)- \Pr (X \lt x)= \Pr (X = x).$$


text:
Q: Proper Grammar of Degree Abbreviations I have seen plenty of abbreviation options to write Postgraduate Diploma.
Just to mention the easiest finding on the web: "A postgraduate diploma (PgD, PgDip, PGDip, PG Dip., PGD, Dipl. PG, PDE) is a postgraduate qualification awarded after a university degree." (Wikipedia)
After checking multiple University pages and forums, I have discovered that the most frequent way of mentioning the Post Graduate Diploma in the U.S.A. is PGD (or PG Diploma); however I have never seen it written with dots (PG.D or something like this).
I find it strange because most of these abbreviations are written with dots in it in the U.S.A., e.g., B.Sc., M.Sc., Ph.D.
I know this is a very insignificant question but I want to write a document with consistency in it. I have already mentioned B.Sc. and M.Sc. multiple times in this doc.
Would someone be able to guide me on this? (The U.S. way of writing should be applied.)
Thank you.


text:
Q: UIAlertView has scrollable title and message on iOS7 I have a UIAlertView with text in it that can be displayed on iOS6 without any problem.
However in iOS7 the title and message of this alert are in a scrollview.
I'm creating the alert with following code
self.newCategoryAlertView = [[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"MessageTitleNewCategory", nil)
                                                            message:NSLocalizedString(@"MessageTextNewCategory", nil)
                                                           delegate:self
                                                  cancelButtonTitle:NSLocalizedString(@"ButtonCancel", nil)
                                                  otherButtonTitles:NSLocalizedString(@"ButtonOK", nil), nil] autorelease];

self.newCategoryAlertView.tag = alertViewTypeNewCategory;
self.newCategoryAlertView.alertViewStyle = UIAlertViewStylePlainTextInput;
[self.newCategoryAlertView textFieldAtIndex:0].delegate = self;
[self.newCategoryAlertView textFieldAtIndex:0].autocapitalizationType = UITextAutocapitalizationTypeSentences;
[[self.newCategoryAlertView textFieldAtIndex:0] setReturnKeyType:UIReturnKeyDone];
[[self.newCategoryAlertView textFieldAtIndex:0] setKeyboardAppearance:UIKeyboardAppearanceDefault];
[self.newCategoryAlertView textFieldAtIndex:0].enablesReturnKeyAutomatically = YES;

[self.newCategoryAlertView show];

The result on iOS7 is this:
I tried to make the the text shorter with no success and the documentation of UIAlertView didn't give me a hint.
How do I workaround this behavior?
EDIT:
This is how it looks when scrolled down. As you can see the complete message is visible.

A: In my opinion that's a good behaviour, as there's no space in the screen to show the keyboard and also de UIAlert. I'm almost sure that if you make the app work in portrait orientation, the alert will show ok with no scrollable title and message.
If the app only runs in landscape orientation, and you don't want to have a scrollable view, I guess the best solution will be maybe to keep the UIAlert message, but taking away the UIAlert tilte.
I hope this helped!

A: I have used a custom control URBAlertView. I found a similar problem with this & I have reported that to the author on the github here.
There was a fix provided by the author under the commit here. However you can also refer the top three commits on the repo here.
I hope that may help you all to figure out a solution


text:
Q: union two data class into one in kotlin How can i union two data class into one in Kotlin like in JavaScript
const a = {name: "test A", age: 20};
const b = {...a, ...{city: "City Test"}}

Now i receive data from api like this
data class Explosive(
    val id: Long,
    val name: String,
    val code: String?,
    val decelerationCharge: Boolean
)

But in local db i use this class
data class ExplosiveDB(
    @PrimaryKey(autoGenerate = true) var id: Long = 0L,
    @ColumnInfo(name = "explosive_id") val explosiveId: Long,
    @ColumnInfo(name = "name") val name: String,
    @ColumnInfo(name = "code") val code: String?,
    @ColumnInfo(name = "decelerationCharge") val decelerationCharge: Boolean
)

And my problem is this code, because I have to rewrite almost everything
ExplosiveDB(
        id = 0,
        explosiveId = explosive.id,
        name = explosive.name,
        code = explosive.code,
        decelerationCharge = explosive.decelerationCharge
    )

How can I avoid this?
Any links, explanations or comments will help me

A: You can create a simple extension function to simplify conversion of one class to another.
fun Explosive.toDatabaseModel() = ExplosiveDB(0, id, name, code, decelerationCharge)

Try it yourself
(You can also use named arguments here if you like to)


text:
Q: Data caching security concerns in asp.net well caching is a perfect way to speed up access to data which are public ( all users of website ) and frequently used. but what about data that are supposed to be accessed by a specific role ( e.g just Administrators ) .
is this sort of caching safe ? is there any security related actions to do when using Data caching ?

A: The security issues for accessing sensitive data from the Cache are exactly the same as those when accessing sensitive data from any other source, e.g. a database.
You just need to implement the appropriate authorization before exposing it to the user.


text:
Q: Removing the URL and @REPLIES from a tweet enter code

for($i=0;$ientry);$i++)
{
//get the id from entry
$id = $xml->entry[$i]->id;

//explode the $id by ":"
$id_parts = explode(":",$id);

//the last part is the tweet id
$tweet_id = array_pop($id_parts);

//get the account link
$account_link = $xml->entry[$i]->author->uri;

//get the image link
$image_link = $xml->entry[$i]->link[1]->attributes()->href;

//get name from entry and trim the last ")"
$name = trim($xml->entry[$i]->author->name, ")");

//explode $name by the rest "(" inside it
$name_parts = explode("(", $name);

//get the real name of user from the last part
$real_name = trim(array_pop($name_parts));

//the rest part is the screen name
$screen_name = trim(array_pop($name_parts));

//get the published time, replace T & Z with " " and trim the last " "
$published_time = trim(str_replace(array("T","Z")," ",$xml->entry[$i]->published));

//get the status link
$status_link = $xml->entry[$i]->link[0]->attributes()->href;

//get the tweet
$tweet = $xml->entry[$i]->content;

//remove  and  from the tweet. If you want to show bold keyword then you can comment this line
$tweet = str_replace(array("", ""),array("
<big><big>",""), $tweet);

//get the source link
$source = $xml->entry[$i]->source;

//the result div that holds the information
echo '

                 '. $tweet .'

';

}echo "";
in the code .$tweet variable contains the tweet text but also contains the url's that have been tweeted,#hashtags and @replies.
i want to remove them from the tweet and only thing remaining should be the text content.
How do i do that?
any help will be appreciated.
thnx ya'll

A: A simple regex will do it:
$cleanText = preg_replace("/[#@]\\S+/", "", $tweetText);


text:
Q: ElasticSearch handling for max shard size I learnt that, an ES Shard is nothing but a lucene index and that Max items in Lucene Index can be INT.MAX -128 (Approx 2Billion), but I could not find anywhere on ES reference how is this scenario handled? Does ES fail or assign another shard to documents with same route?
or is it something that we need to plan in advance, while designing the indexing strategies?


text:
Q: C#: How to use CategoryAttribute.Appearance Property I have read a bit about Design-Time Attributes for Components. There I found an attribute called CategoryAttribute. On that page it says that

The CategoryAttribute class defines the following common categories:

And then lists up a number of common categories. One of them are for example Appearance. I thought, brilliant! Then I can use [Category.Appearance] instead of [Category("Appearance")]! But apparently I couldn't? Tried to write it, but Intellisense wouldn't pick it up and it wouldn't compile. Am I missing something here? Was it maybe not this those properties were for? If not, what are they for? If they are, how do I use them?
And yes, I do have the correct using to have access to the CategoryAttribute, cause [Category("Whatever")] do work. I'm just wondering how I use those defined common categories.

A: As you can see on MSDN it's only a getter property, not a setter.
public static CategoryAttribute Appearance { get; }

In fact, here's what the code looks like using Reflector:
 public static CategoryAttribute Appearance
    {
        get
        {
            if (appearance == null)
            {
                appearance = new CategoryAttribute("Appearance");
            }
            return appearance;
        }
    }

So it doesn't do a heck of a lot.
The only use I can see for it, is something like this:
            foreach (CategoryAttribute attrib in prop.GetCustomAttributes(typeof(CategoryAttribute), false))
            {
                bool result = attrib.Equals(CategoryAttribute.Appearance);
            }

Basically, when using reflection to look at the class, you can easily check which category this belongs to without having to do a String comparison. But you can't use it in the manner you're trying to unfortunately.

A: The static property is accessed via CategoryAttribute.Appearance. But the attribute system does not allow you to invoke code in an attribute declaration and I guess that is why it wont compile for you. You will probably have to settle for [Category("Appearance")].

A: Starting from C# 6 there is finally a better alternative: [Category(nameof(CategoryAttribute.Appearance))].


text:
Q: Export to excel, Column header display error in ColdFusion I am trying to get account numbers by a query and displaying those account numbers as column header after exporting into excel.
The following code is working fine but displaying wrongly:
<cfset variables.setHeader = "">
<cfoutput query="myLoop">
    <cfset variables.setHeader = variables.setHeader & ", C_#myLoop.acc#>
</cfoutput>

The above code is displaying column header (just one sample data I am showing here) but it is showing as 'C_000391'. Which is wrong! For display, 'C_' should not be with account number, it is the account number which should create the column header alone. However, as soon as I am taking off 'C_' from infront of #myLoop.acc# it is giving the following error:
The column name 000391 is invalid.

Please let me know what will be the best solution(s) to resolve this toughest problem on earth :)
Thanks

A: Seems you are trying a form a comma separated list , try below , no looping required.
< cfset variables.setHeader = ValueList(myLoop.acc) >


text:
Q: Unicode-math: Stylistic setting fails for super/sub-scripts I am using XeLaTeX to compile a document with usage of the package unicode-math in order to make my document looks satisfying. However the target stylistic setting fails for super/subscripts as the following MWE shows:
% !TEX Program = xelatex
\documentclass{minimal}
\usepackage{amsmath}
\usepackage{unicode-math}
\setmainfont{STIX Two Text}
\setmathfont[StylisticSet = {02,08}, mathit = sym]{STIX Two Math}
\begin{document}
    \[
          g, u, v, w, z, \int_{g,u,v,w,z}^{z,w,v,u,g}, \int_\int^\int
    \]
\end{document}

It produces

and the Stylistic Sets are as shown in the font table document:

Obviously, Stylistic Set 02, 08 didn't apply to super/subscripts, so my questions is:

Is it a drawback of this unicode-math package or I used the package incorrectly? Any workarounds to keep the consistency of font styles of both regular math text and super/subscripts [i.e. these stylistic settings applies to both regular math and super/subscript characters]?

Any help would be appreciated.

A: running it with lualatex and an up-to-date TexLive I get:

so it looks more a problem with xelatex ...


text:
Q: Eclipse - How to disable "direction" on find/replace dialog In eclipse, when using the CTRL+F dialog, it is a bit annoying to search for some word in a file and having to select the direction you want to search (forward or backward) or having to put the cursor focus at the top of the file to search forward.
Is it possible to disable this direction option and search for words just like Chrome does? (when searching in Chrome, if you reach the last coincidence and press next again, it will go back to the first one immediately).

A: In the Find/Replace dialog in the section Options there is the checkbox Wrap search for that.
The Wrap search option of the Find/Replace dialog is also applied to the Find Next (Ctrl+K) command.
Alternatively, you can use Incremental Find (Ctrl+J) which is a Find without a dialog: in the Incremental Find mode the entered search string is displayed in the status bar and by hitting Ctrl+J again you go to the next match. On the last match you have to hit Ctrl+J twice to go to the first match.


text:
Q: python logging in django I am using the basic python logger in django and it seems to be workng well. I have the logging setup in my setting.py as;
logging.baseConfig(level = logging.NOTSET,
                   format='a format',
                   datemt=' a datefmt',
                   filename='path to log',
                   filemode = 'a')
logging.getLogger('').setLevel(logging.NOTSET)

My question is with regard to propagating exceptions. In my code if I have a try/except clause and catch the exception so I can log it, what is the best way to then propagate that error so that I can redirect to my 500 page. I have been using
try:
    do stuff
except Exception, e:
    logging.error(e)
    raise

but I find that this causes the exeption to be logged twice. Is there another way to do this or am I doing something wrong?
Regards
Andrew

A: There's no need to catch the exception just so you can log it. You can log it and handle it, or else let it bubble up to some higher level which will log it and handle it. If you want to log exceptions which occur in some view, which you don't want to handle, then you can install some exception middleware which logs the exception and either returns a custom response which you determine, or None (to return whatever response Django would normally return).
There's an example of extensible exception middleware here, which doesn't actually use logging but whose log_exception() method you could subclass to log the exception, or just use that snippet as a guide to provide your own exception middleware - it's basically just a class with a method called process_exception:
class MyExceptionMiddleware:

    def process_exception(self, request, exception):
        #Do your logging here

Also, note that loggers have an exception() method which works like error() but includes traceback information in the log.

A: There's a recipe: http://code.activestate.com/recipes/466332/

In any somewhat complex application, you likely want to log and handle most exceptions. The recipe shows a way to separate logging from handling, so that it is not necessary to explicitly invoke the logging mechanism in each try-except clause.


text:
Q: MaterializeCSS .container suddenly not working My .container in materialize CSS always took up the entire screen.
            .container {
                width: 100%;
            }

but suddenly I opened it and it looks as though its back to the 70% container.
I thought maybe I accidentally deleted some code, but when I opened my back up of my website it too appeared as though the container was only 70% of the screen.  It's weird because it wasn't like that and now every page has a tiny container.  I tried making the container width bigger and it cuts things off my screen.  I also tried making all the rows wider but it just made my content stretch too much.

A: MaterializeCSS specifically defines the class container to be a max-width of 1280px and a width of 90%
Therefore, if you wish to still use this class but want it altered, you would either edit the materialize.css or in a separate .css file, declared UNDER the materialize.css:
.container{
    max-width: 100%;
    width:100%;
}

You could also define these inline, however that is not recommended


text:
Q: Rails API POST (XML) - does not work I am trying to make a post request to remote API (external website), which accepts post parameters in XML form. I have the following code:
def advertiser_exists
      uri = URI.parse(@api_url)
      request = Net::HTTP::Post.new(uri.path)
      xml_string = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><request><key>#{@api_key}</key><method>GetCampaigns</method><partner_id>#{@account_id}</partner_id></request>"
      request.body = xml_string
      request.content_type = 'text/xml'
      response = Net::HTTP.new(uri.host, uri.port).start { |http| http.request request }
end

But the response is not, what I would expect:
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\t\t\t<response>\n\t\t\t\t<status>ERROR</status>\n\t\t\t\t<reason>No Data</reason>\n\t\t\t</response>"

Here is the PHP version (supplied by the provider, which should work):
<?php
    // url api
    $url = "http://YOUR_URL/api/";

    // request
    $xml = '<?xml version="1.0" encoding="UTF-8"?>
    <request>
        <key>abcdefghijklm</key>
        <method>AddConversion</method>
        <partner_id>1</partner_id>
        <campaign_id>1</campaign_id>
        <conversion_id>1</conversion_id>
        <value>100</value>
    </request>';

    // sending request
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, "data=".$xml);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($ch);
    curl_close($ch);

    // response
    echo $output;
?>

Any idea, what is wrong with my code above (the parameters are correct and there should be data on response)?
Thanks, Miroslav


text:
Q: Posting empty results Hello i am trying to make a trade script were users can trade each others monsters.
So i have a script were it shows there monsters and the users monsters that they type in so if the user types in nick it will shows the pokemon nick monsters and the user who typed it in monster.
All of whic works fine it displays what i want.
Now i want to store the monsters they want and are offering in the db.  And that is were we come to the problem. For some resosn its storing the username and the username of the trader ok but not the monsters. Its storing
{"pokemon":[""]}
For the trade_pokeid   and the trade_mypokeid
Here is how i display there monsters and the users monsters which works fine
Trade with

   <?php

$username_trade = $_POST['username_trade'];

$_SESSION['username_trade'] = $username_trade ;

echo "You put in id  ". $username_trade . ".
";

?>

  <?php
                        // get and display userbox
                        $q = "SELECT id,pokemon,exp,level FROM user_pokemon WHERE belongsto='". $_SESSION['username_trade']."'";
                        $r = mysql_query($q);

                        if (mysql_num_rows($r) <= 0) {
                            echo "You have no current pokemon stored";

                        }
                    ?>

  <?php
 echo "<form action='test_process.php' method='POST'>";
while ( $v = mysql_fetch_object( $r ) )
{
    echo "<input type='checkbox' name='pokemon[]' value='$v->dbid'/> They have a $v->pokemon
";
        echo " Level $v->level
";
}
echo "<input type='hidden' name='user' value='$username_trade'/>";
echo "<input type='submit' value='Check!!'/>";
?>

Pick what you want two offer for the pokemon

  <?php
                        // get and display userbox
                        $q = "SELECT id,pokemon,exp,level FROM user_pokemon WHERE belongsto='". $_SESSION['username']."'";
                        $t = mysql_query($q);

                        if (mysql_num_rows($t) <= 0) {
                            echo "You have no current pokemon stored";

                        }
                    ?>

  <?php
 echo "<form action='test_process.php' method='POST'>";
while ( $v = mysql_fetch_object( $t ) )
{
    echo "<input type='checkbox' name='pokemonin[]' value='$v->dbid'/> I have a $v->pokemon
";
    echo " Level $v->level
";
}
echo "<input type='hidden' name='userin' value='$username'/>";
echo "</form>";
?>

Now here is how i try and store them.
<?php
include 'config.php';

$pokemon = $_POST['pokemon'];
$pokemonin = $_POST['pokemonin'];
$meid = $_SESSION['username'];
$toid = $_POST['user'];
$dbid = array();
$dbid2 = array();

foreach ( $pokemon as $poke )
{   $dbid['pokemon'][] = $poke;

}

foreach ( $pokemonin as $poke2 )
{   $dbid2['pokemonin'][] = $poke2;

}

srand ((double) microtime( )*1000000);
$random_number = rand( );
echo "$random_number";

    mysql_query("INSERT INTO trade (trade_id, trade_to, trade_from, trade_pokeid, trade_mypokeid)
                            VALUES ('$random_number','$toid', '$meid', '"$dbid."', '".$dbid2."');") or die("Error: ". mysql_error());

?>

What am i doing wrong ? why are the results not being stored ? or carried over the db connect and session start are in the config.php page

A: In your last MySQL query, you're trying to insert a PHP array as a string into a query, that won't work. If I'm guessing correctly, you'll want to use something like implode(",",$dbid['pokemon']) instead of $dbid.
Also, it's definitely a good idea to run mysql_real_escape_string on anything that comes from the user and/or the URL before you put it in a query!

A: Your code is open for sql injection !
You shuld aviod passing parameters (without escaping) to sql query => for start check:
http://php.net/manual/en/function.mysql-real-escape-string.php

A: You have an error (not enough - or too many dots) in your MYSQL statement...
VALUES ('$random_number','$toid', '$meid', '"$dbid."', '".$dbid2."')

Should read
VALUES ('$random_number','$toid', '$meid', '$dbid', '$dbid2')


text:
Q: how to copy a list to a new list, or retrieve list by value in c# I noticed in c# there is a method for Lists:
CopyTo -> that copies to arrays, is there a nicer way to copy to a new list? problem is, I want to retrieve the list by value to be able to remove items before displaying them, i dont want the original list to be modified, that too doesnt seem to be easily attainable, any ideas?

A:
I want to retrieve the list by value to be able to remove items before displaying them,

var newlist = oldList.Where(<specify condition here>).ToList();

A: List<MyType> copy = new List<MyType>(original);

A: If you are using .NET 3.5, the resulting array can have ToList() called on it.

A: Just create a new List and use the appropriate constructor:
IList<Obj> newList = new List<Obj>(oldList);

A: I think this will work.  Passing a list to the constructor of a new list.
    List<string> list1 = new List<string>();
    List<string> list2 = new List<string>(list1);

A: Have you tried Cloning (Clone()) each item and adding the clone to a new collection?

A: It seems if you have a list of references, the list
List<Object> list2 = new List<Object>(list1);

does not work.
This should solve your problem:
How do I clone a generic list in C#?


text:
Q: How can I use the append function to make a list of dictionaries in a list of dictionaries I have a dictionary consisting of four parameters: teacher, day, time, and subject. When I write them to a JSON file, they look like this:
[
    {"day": "Monday",
    "lesson": "Math",
    "teacher": "Mr John",
    "time": "8:00"},
    {"day": "Monday",
     "lesson": "Math",
     teacher": "Mr John",
     "time": "9:00"},
    ...
    ]

But I need to make a dictionary list in the dictionary list so that the JSON file looks like this:
[
    {"teacher": "Mr John",
    lessons:[
    {"day": "Monday",
    "time": "8:00",
    "lesson: "Math"},
    {"day": "Monday",
    "time": "9:00",
    "lesson: "Math"},
    ...
    ]}]

I tried the following code:
 lst = []
    my_list = []
    my_dict = {"teacher": "Mr John",
    "lessons":
    my_list.append(
    {"day": "Monday",
    "time": "8:00",
    "lesson": "Math"},
    {"day": "Monday",
    "time": "9:00",
    "lesson": "Math"},
    )
    }
    lst.append(my_dict)
    lst.append(my_list)
    with open("schedule.json", "w", encoding='utf-8') as json_file:
        json.dump(lst, json_file, indent=4, sort_keys=True, ensure_ascii=False)

That's what I get:
[
    {"lessons": null,
    "teacher": "Mr John"},
    [
    {"day": "Monday",
    "lesson": "Math",
    "time": "8:00"}
    ],
    {"lessons": null,
    "teacher": "Mr John"},
    [
    {"day": "Monday",
    "lesson": "Math",
    "time": "9:00"}
    ]

The teacher is constantly being written again instead of once, the value lessons are empty, and each lesson is written to a new array.
How do I fix/write the code so that I get the JSON file I need? I'm sorry if there was such a question already; I'm super new to this site and Python. Thank you in advance for your answers!

A: You will need to update this portion, like so
lst = []
my_dict = {"teacher": "Mr John", "lessons": []}
my_dict["lessons"].append({"day": "Monday", "time": "8:00", "lesson": "Math"})
my_dict["lessons"].append({"day": "Monday", "time": "9:00", "lesson": "Math"})
lst.append(my_dict)

with open("schedule.json", "w", encoding='utf-8') as json_file:
    json.dump(lst, json_file, indent=4, sort_keys=True, ensure_ascii=False)


text:
Q: Extract certain parts of nested lists of a list to create a dataframe Below I apply shapiro test on the first 4 columns of iris dataset. I would like to create a dataframe out of this with the column name, the p value and the w score.
apply(iris,2,shapiro.test)

A: You can do this:
df <- apply(iris[,1:4], 2, function(x) {
  sh <- shapiro.test(x)
  c(p = sh$p.value, sh$statistic)})

  Sepal.Length Sepal.Width Petal.Length  Petal.Width
p   0.01018116   0.1011543 7.412263e-10 1.680465e-08
W   0.97609027   0.9849179 8.762681e-01 9.018349e-01

You can make it tidy dataframe as follow:
library(tidyverse)
as.data.frame(df) %>%
  rownames_to_column(var = "stats") %>%
  pivot_longer(cols = -stats)

# A tibble: 8 x 3
  stats name            value
  <chr> <chr>           <dbl>
1 p     Sepal.Length 1.02e- 2
2 p     Sepal.Width  1.01e- 1
3 p     Petal.Length 7.41e-10
4 p     Petal.Width  1.68e- 8
5 W     Sepal.Length 9.76e- 1
6 W     Sepal.Width  9.85e- 1
7 W     Petal.Length 8.76e- 1
8 W     Petal.Width  9.02e- 1

A: Using sapply.
sapply(iris[-5], \(x) shapiro.test(x)[1:2])
#           Sepal.Length Sepal.Width Petal.Length Petal.Width
# statistic 0.9760903    0.9849179   0.8762681    0.9018349
# p.value   0.01018116   0.1011543   7.412263e-10 1.680465e-08

A: tidyverse
library(tidyverse)
map(iris[-5], shapiro.test) %>%
  map_df(broom::glance, .id = "vars")
#> # A tibble: 4 x 4
#>   vars         statistic  p.value method
#>   <chr>            <dbl>    <dbl> <chr>
#> 1 Sepal.Length     0.976 1.02e- 2 Shapiro-Wilk normality test
#> 2 Sepal.Width      0.985 1.01e- 1 Shapiro-Wilk normality test
#> 3 Petal.Length     0.876 7.41e-10 Shapiro-Wilk normality test
#> 4 Petal.Width      0.902 1.68e- 8 Shapiro-Wilk normality test

Created on 2022-01-17 by the reprex package (v2.0.1)