text:
Q: Architecture design help I'm looking for some input on my current project architecture. There are three components: Server, Desktop, and Mobile Device.
I have 2 goals:
1) Send data (Approx. no more than 100 KB of text) from the Desktop (multi platform client application running on windows XP/Vista/7, and Mac OS X) to a server (Windows Server 2008, IIS 7, WCF RESTful service) to save in a database (Sql Server). The services need to be scalable because the number of desktop devices and frequency they send data is unknown.
2) A service to retrieve data from the database (Sql Server) and send to a mobile device(Iphone and Android application. Message size no more than 100 KB of text). Service needs to be scalable because number of mobile devices and frequency they connect is unknown.
My proposed solution:
Server Side (Sql Server and Windows Server 2008):
I'm looking at a WCF RESTful JSON services to communicate with Desktop App(s) and Mobile App(s). I like WCF because I am most proficient in C#, have some experience implementing WCF, after doing some research it appears all technologies used for the platforms(Windows XP/Vista/7 and Mac OS X) can easily communicate with the WCF RESTful service.

*

*Any high level fundamental issues with the WCF service in this scenario?

*I have only implemented WCF on a Windows Server 2003 machine with ~800 devices connecting every 15 minutes. The server was a physical in house server running on a private network. I need this solution to be hosted and scalable. Any recommendations for hosting a Windows Server 2008? Is there a better technology to host the service? (I'm not very familiar with how the cloud stuff works)

The services will be saving and retrieving data from a SQL server. I would like to use LINQ to SQL as my data access layer. It's my understanding there are large licensing fees tied to SQL server so I may need to go with SQL Server Express for now.

*

*I'd prefer to keep the WCF services and database hosted separately (2 diff machines). Any recommendations for hosting sql server(or express)? Is there a hosting service that can scale better for my database? Does it make sense to keep these on 2 diff machines?

Desktop (Client Side)
I am required to develop for Windows XP/Vista/7 and Mac OS X. I plan to write a .net application to run on the windows machine(s). I"m still up in the air if i'm going to write (and learn :P) XCode or try mono. Any cross-platform ideas?

*

*Should I expect to have any fundamental problems getting the desktop applications to talk to my WCF RESTful services?

Mobile Applicaitons
I am required to developer for the IPhone and Android. There are many examples of making WCF RESTful service calls using Objective C and the Android SDK. I'm considering trying a cross platform (ie. Appcelerator). From a high level it appears these mobile cross platforms have built a Java script layer that works with both IPhone and Android!

*

*Any thoughts on using the cross platform technology to write ONE mobile app to run on IPhone and Android?

*Any fundamental issues calling the WCF RESTful service in javascript?
Sorry for the somewhat long post. I have never designed a solution of this size. All feedback is appreciated.
Thank you!

A: As you are clearly wanting to use Microsoft technologies - the suggestions about Mono probably make sense to you and will certainly make things easier.
However I think you may find that you compromise elements of the user experience for Mac and iPhone users which is not ideal as these users tend to have the highest expectations for great user experiences.
I understand that we don't live in an ideal world but if we did you would develop a separate client for each platform - optimised to the needs of each platform. Unless you application is doing a lot of data manipulation the data layer is now abstracted to the server viw your JSON interface so you will not gain much from sharing the data objects across implementations.
As it seems you are implementing the project in a small team (yourself?) then I would suggest that you look at implementing a web solution with the HTML javascript communicating with the server over JSON.
The other option is that you use a flex/air client on windows and mac and flash on the android and Adobe's solution to compile flex/air into iPhone code.
Good luck though.

A: For your client side you may consider using Appclerator because it will run on all of the platforms that you need with little to no extra code, and it is designed to be used for web app type applications

A: You should consider MonoTouch for the iphone. You'll be able to share much of the desktop code. I would use Mono on the Mac for the same reason. Android is the odd man out. Eventually someone might create something like MonoTouch for Android but not soon enough to help you out.


text:
Q: Stopping EC2 instance when custom cloudwatch metric passes limit I'm trying to find a way to make an Amazon EC2 instance stop automatically when a certain custom metric on CloudWatch passes a limit. So far if I've understood correctly based on these articles:

*

*Discussion Forum: Custom Metric EC2 Action

*CloudWatch Documentation: Create Alarms to Stop, Terminate, Reboot, or Recover an Instance
This will only work if the metric is defined as follows:

*

*Tied to certain instance

*With type of System/Linux

However in my case I have a custom metric that is actually not instance-related but "global" and if a certain limit is passed, I would need to stop all instances, no matter from which instance the limiting log is received.
Does anybody know if there is way to make this work? What I'd need is some way to make CloudWatch work like this:

*

*If arbitrary custom metric value passes a certain limit -> stop defined instances not tied to the metric itself.

The main problem is that the EC2 option is greyed out as the metric is not tied to certain EC2 instance and I'm not sure if there's any way to do this without actually making the metric itself certain instance related.

A: Have the custom CloudWatch metric post alerts to an SNS topic.
Have the SNS topic trigger a Lambda function that shuts down your EC2 instances via a call to the AWS API.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Oracle ordering with IN clause In Oracle 12c, I have a select statement that uses  the IN keyword with a long list of serial numbers as part of the IN clause. Is there a way to keep the order of the results the same as the order of the list in the IN clause?
Tried different Order By clauses, but no success.


text:
Q: Python: Make Virtual Assistant Listen Again After Saying "Hey Assistant" Using the code below the virtual assistant will listen for commands but after saying "try again" it will stop to listen. How do I make it listen again using the wake command "hey assistant".
def myCommand():

    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        r.pause_threshold =  1
        text = r.listen(source)
    try:
        query = r.recognize_google(text, language='en')
        print('User: ' + query + '\n')

    except sr.UnknownValueError:
        speak('Sorry sir! I didn\'t get that.')
        query = str(input('Try again'))

    return query

A: # you can call it using this...
hotword = 'hey assistant'
while 1:
    result = myCommand()
    if hotword in result:
        #here what you want to do...
        #respose_of_assistant()


text:
Q: Azure Custom Policy: Resource Must Not Have Unknown Tag - How? For this example, there are two allowable tag names for a resource.

*

*Environment

*Client

I want to create a policy that evaluates a resource as non compliant if it is given a tag that is neither of the above. (Note that I want to avoid using parameters, preferring that the allowable tag names are 'burnt in' to the definition.)
I have tried the following code, however it is flagging resources as being compliant when they have a tag other than the above.
  "mode": "Indexed",
  "policyRule": {
    "if": {
      "allOf": [
        {
          "field": "tags",
          "exists": "true"
        },
        {
          "field": "tags",
          "notContainsKey": "Environment"
        },
        {
          "field": "tags",
          "notContainsKey": "Client"
        }
      ]
    },
    "then": {
      "effect": "deny"
    }
  },
  "parameters": {}
}

Can anyone see where I'm going wrong?

A: If I understand correctly it is allowed to create a resource with:

*

*no tags

*the 'Client' tag only

*the 'Environment' tag only

*'Client' and 'Environment' tags only

All other cases must be blocked.
{
  "mode": "All",
  "policyRule": {
    "if": {
      "not": {
        "value": "[if(equals(length(field('tags')),0),'noTags',if(and(equals(length(field('tags')),1),or(contains(field('tags'),'Environment'),contains(field('tags'),'Client'))),'environmentOrClientTagOnlyExists',                                if(and(equals(length(field('tags')),2),and(contains(field('tags'),'Environment'),contains(field('tags'),'Client'))),'environmentAndClientTagsExist','atLeastOneNotAllowedTagExists' )  )  )]",
        "in": [
          "noTags",
          "environmentOrClientTagOnlyExists",
          "environmentAndClientTagsExist"
        ]
      }
    },
    "then": {
      "effect": "deny"
    }
  },
  "parameters": {}
}


text:
Q: How do I persist session data for logins using pyramid_redis_session backend? I'm using pyramid_redis_session as the backend session_factory. I'm not sure how to go about persisting session data during a login.
As per the pyramid documentation, its simply:
request.session['sid'] = hashedvalue

However, there is also the remember() function for logins. Is remember() to be used for logins and, and the above way to be used for other session data?

A: The session and the authentication policy are two separate systems. If you want the policy to know that the user is logged in you should use remember to inform it of that fact otherwise you will have the userid in the session but the authentication policy will not know - it typically has its own way of storing who the logged in user is.


text:
Q: Static config object similar to pythons logging object The logger object is as I understand a singleton, only one instance can ever exist. You get a reference by this:
import logging
log = logging.getLogger('MyLogger')

I would like to do the same with a global config object, rather then have to pass my config as a parameter. What is the best approach to do this?


text:
Q: Comunicación entre componentes ReactJs Me ayudan, por favor?
tengo dos componentes hermanos, uno que muestra los comentarios de cada estado y otro donde puedo agregar un comentario al estado correspondiente.
componente  <Estados>
el componente estados recibe la lista de estados desde su padre y la renderiza en el hook currentEstado, este tiene dos componentes hijos que hacen la función de mostrar los comentarios asociados a el estado y escribir el comentario asociado al estado
const Estados = (props) => {
    const [estadosState, setCurrentEstado] = useState(props.estados)
    const addComentario = (comentario, id) => {
       estadosState.map(e =>{
            if(e.id == id) {
                e.comentariosEstado.push(comentario)
            }
        })
    }
return (
        <Fragment>

 lista

                {
                    estadosState.length > 0 ?
                    estadosState.map((item, index) =>

                                {item.estado}
                                <Comentarios comentarios={item.comentariosEstado}>
                                </Comentarios>
                                <EscribirComentarios
                                    id={item.id}
                                    addComentario={addComentario}>

                                </EscribirComentarios>

                        ) : (

No hay comentarios aún {props.estados.length}

                        )
                }

        </Fragment>

    );
}

tengo el componente <comentarios>  este componente me ayuda a renderizar los comentarios asociados a cada estado, en una iteración realizada previamente en el componente padre <Estados>
const Comentarios = (props) => {
    console.log('comentarios', props.comentarios)
    return (
        <Fragment>

                {
                props.comentarios.map((comentario, index) =>

                        {comentario.nombre}

{comentario.comentario}

                )
                }

        </Fragment>
    )
}

Y tengo el componente <escribir-comentario>
Este componente no es más que un formulario que manda un comentario y en el método addComentario() se le agrega la lógica, y listo.
en teoría funciona porque se agregan estados, y se visualizan, pero cuando voy a agregar un comentario asociados a un estado, el en el log funciona, hace el push a la lista, pero no el componente <Comentarios>  no me renderiza la lista completa, quisiera que me ayudaran con este tema, yo creo que es porque no uso el concepto de hooks correctamente, pero soy nuevo en esto.
Gracias.
  const EscribirComentarios = (props) => {

   const { handleSubmit, register } = useForm();
   const onSubmit = (data, e) => {
       props.addComentario(data, props.id)
       //limpiar campos
       e.target.reset();

   }
   return(
       <React.Fragment>
           <form onSubmit={handleSubmit(onSubmit)} className="containerEscribirComentaro">

                   <input
                       name="comentario"
                       ref={
                           register({
                               required: { value: true, message: 'Comentario obligatorio' }
                           })
                       }
                   />

                   <input
                       type="submit"
                       value="Comentar"
                   />

           </form>
        </React.Fragment>
   )
}

EDITADO
Si, el componente padre no está interviniendo en el método de agregar comentarios al estado, este es el padre <app.js>
function App() {
  const estados = [
    {
      id: uuidv4(),
      nombre: 'Juan Rodriguez',
      estado: 'Este es un estado de información en ejemplo.',
      comentariosEstado: [
        { id: uuidv4(), comentario: 'Este es un comentario del estado', nombre: 'Elena' },
        { id: uuidv4(), comentario: 'Este es un comentario del estado', nombre: 'Elena' }
      ]
    },
    {
      id: uuidv4(),
      nombre: 'Martha Fernández',
      estado: 'Este es un estado de información en ejemplo 2.',
      comentariosEstado: [
        { id: uuidv4(), comentario: 'Este es un comentario del estado 2', nombre: 'Camilo' },
        { id: uuidv4(), comentario: 'Este es un comentario del estado 2', nombre: 'Luffy' }
      ]
    }
  ]
  const [estadosList, setEstadosList] = useState(estados)

  const armarEstados = (estado) =>{
    // después se genera un random para el estado.nombre.
    estado.id = uuidv4()
    estado.nombre = "Camilo F."
    estado.comentariosEstado = []
  }

  const addEstado = (estado) => {
    // estado.id  = uuidv4()
    armarEstados(estado)
    setEstadosList([
      ...estadosList,
      estado
    ])

  }

  return (
    <React.Fragment>
      <EscribirEstados addEstado={addEstado}></EscribirEstados>
      <Estados estados={estadosList}></Estados>
    </React.Fragment>

  );
}

A: el primer error que observo es como estas manejando el hook useState, no es buena practica que el dato del useState, valga la redundancia, venga directamente de los props,
igualmente, en el componente <Estados/> no haria falta agregar un useState ya que los datos vienen directamente desde el padre, al componente <Estados/> yo lo haria de la siguiente manera
const Estados = props => {

const { estados } = props

const addComentario = (comentario, id) => {
  estados.map(e => {
    if (e.id == id) {
      e.comentariosEstado.push(comentario)
    }
  })
}

return (
  <Fragment>

      lista

      {estados.length > 0 ?  estados.map((item, index)=>

        {item.estado}
          <Comentarios comentarios={item.comentariosEstado} />
          <EscribirComentarios
            id={item.id}
            addComentario={addComentario}
          />

        ): (

            No hay comentarios aún {estados.length}

        )}

  </Fragment>
);
}

como podras ver, el atributo estados que estabas pasando al componente <Estados/> ya no hace falta guardarlo en el estado del componente, y quedaria un codigo mas limpio,
ahora bien, estas diciendo que el problema es que no se muestran los datos a la hora de agregar un nuevo comentario, lo que yo haria es agregar un useEffect al componente padre, lo haria de esta forma
function App() {
  const estados = [
    {
      id: uuidv4(),
      nombre: 'Juan Rodriguez',
      estado: 'Este es un estado de información en ejemplo.',
      comentariosEstado: [
        { id: uuidv4(), comentario: 'Este es un comentario del estado', nombre: 'Elena' },
        { id: uuidv4(), comentario: 'Este es un comentario del estado', nombre: 'Elena' }
      ]
    },
    {
      id: uuidv4(),
      nombre: 'Martha Fernández',
      estado: 'Este es un estado de información en ejemplo 2.',
      comentariosEstado: [
        { id: uuidv4(), comentario: 'Este es un comentario del estado 2', nombre: 'Camilo' },
        { id: uuidv4(), comentario: 'Este es un comentario del estado 2', nombre: 'Luffy' }
      ]
    }
  ]
  const [estadosList, setEstadosList] = useState(estados)

  //simplemente hacemos que el componente se vuelva a renderizar cuando haya un cambio
  //en el array de estados
  useEffect(()=>{},[estadosList])

  const armarEstados = (estado) =>{
    // después se genera un random para el estado.nombre.
    estado.id = uuidv4()
    estado.nombre = "Camilo F."
    estado.comentariosEstado = []
  }

  const addEstado = (estado) => {
    // estado.id  = uuidv4()
    armarEstados(estado)
    setEstadosList([
      ...estadosList,
      estado
    ])

  }

  return (
    <React.Fragment>
      <EscribirEstados addEstado={addEstado}></EscribirEstados>
      <Estados estados={estadosList}></Estados>
    </React.Fragment>
  );
}

de esa forma hacemos que cuando haya un cambio en la lista de estados, se vuelva a renderizar, puedes informarte mas sobre los hooks en la pagina oficial de react, son de mucha ayuda a la hora de usar componentes funcionales en react, otra cosa, cuando un componente no necesita hijos, puedes hacer unsa sola etiqueta
//esta porcion de codigo se puede simplificar de la sugiente manera
return (
    <React.Fragment>
      <EscribirEstados addEstado={addEstado}></EscribirEstados>
      <Estados estados={estadosList}></Estados>
    </React.Fragment>
  );

return (
    <>
      <EscribirEstados addEstado={addEstado} />
      <Estados estados={estadosList} />
    </>
  );

espero que hayas poder solucionado tu problema, cualquier pregunta ya sabes

A: Se vé que aún estas en etapa de desarrollo, pero con esta modificación podrás avanzar y seguir mejorando tu código.
Modifica la función addComentario del componente Estados de la siguiente forma:
const addComentario = (comentario, id) => {
             let copyObj = {
                  id: uuidv4(),
                  comentario: comentario.comentario,
                  nombre: 'usuario en sesion'
             }
             let copyEstados = estadosState.map(e =>{
                   if(e.id === id) {
                       e.comentariosEstado.push(copyObj);
                       return Object.assign({}, e, {comentariosEstado:e.comentariosEstado} )
                   } else {
                       return e;
                       }
                   })
             setCurrentEstado(copyEstados);
}

Ya habías creado una copia de todo el estado con map, solo se agregó el nuevo valor de la propiedad comentariosEstado para cada estado de información, es decir cada elemento de tu estado:
Object.assign({}, e, {comentariosEstado:e.comentariosEstado} )

Este nuevo valor es todo el array comentariosEstado, ya lo tenias listo cuando codificaste el push:
e.comentariosEstado.push(copyObj);

Por último se complemento el nuevo objeto comentarios, con el nuevo id que se supone se debe generar y el usuario que se supone que está en sesión:
let copyObj = {
                id: uuidv4(),
                comentario: comentario.comentario,
                nombre: 'usuario en sesion'
              }

Finalmente se hace el re-render con la función setCurrentEstado y la nueva copia del Estado:
setCurrentEstado(copyEstados);

Recuerda importar el modulo uuid en el componente Estados.


text:
Q: simple string comparison in bash I'm looking to get the number of subdirectories within a directory and compare that with a predefined number.
Ex:
cd /Applications/
x=echo ls -d */ | wc -l | sed 's/^ *//g'
y="52"

if [ "$x" == "$y" ]; then
    echo "equal"
else
    echo "not equal"
fi

It will give me a number for x (52 in my case), but will always say "not equal". What am I doing wrong? Any help would be greatly appreciated.
Thanks

A: For bash, do this:
cd /Applications/
dirs=( */ )   # dirs is an array with the names of directories here
if (( ${#dirs[@]} == $y )); then
    echo "equal"
else
    echo "not equal"
fi

A: Replace
x=echo ls -d */ | wc -l | sed 's/^ *//g'

with:
x="$(ls -d */ | wc -l | sed 's/^ *//g')"

Explanation:  When you write x=echo ls -d */ ..., bash thinks that you mean to temporarily set the the variable x to a value of "echo" and then run the ls command.  You, instead, want to run the command s -d */ | wc -l | sed 's/^ *//g' and save the output in x.  The construct x=$(...) tells bash to execute whatever was in the parens and assign the output to x.
Also, bash's [ command does not accept ==.  Use = for string comparison.  However, you really want mathematical comparison. So use '-eq':
  if [ "$x" -eq "$y" ]; then


text:
Q: Delete some parts in json response python This is my JSON response and i want to drop the whole meta header part.
{
    "meta": {
        "limit": 1000,
        "next": "https://cisco-demo.obsrvbl.com/api/v3/observations/all/?limit=1000&offset=1000",
        "offset": 0,
        "previous": null,
        "total_count": 1863020
    },
    "objects": [
        {
            "creation_time": null,
            "end_time": "2017-08-17T19:40:00Z",
            "id": 281,
            "observation_name": "External Port Scanner",
            "port_count": 251,
            "port_ranges": "0-1023",
            "resource_name": "port_scanner_external_v1",
            "scan_type": "inbound",
            "scanned_ip": "209.182.184.2",
            "scanned_ip_country_code": "US",
            "scanned_packets": 999,
            "scanner_ip": "130.126.24.53",
            "scanner_ip_country_code": "US",
            "scanner_packets": 997,
            "source": 109,
            "time": "2017-08-17T19:40:00Z"
        },
        {
            "creation_time": null,
            "end_time": "2017-08-17T19:50:00Z",
            "id": 304,
            "observation_name": "External Port Scanner",
            "port_count": 41,
            "port_ranges": "0-1023",
            "resource_name": "port_scanner_external_v1",
            "scan_type": "inbound",
            "scanned_ip": "209.182.184.2",
            "scanned_ip_country_code": "US",
            "scanned_packets": 152,
            "scanner_ip": "130.126.24.53",
            "scanner_ip_country_code": "US",
            "scanner_packets": 152,
            "source": 109,
            "time": "2017-08-17T19:50:00Z"
        },

A: import json

with open('myfile.txt') as fp:
    my_dict = json.loads(fp.read())

try:
    del my_dict['meta']
except KeyError:
    pass

I'm assuming you already have your JSON as dictionary, in the code above I just load it from a text file. The command you're looking for is del. It's a good idea to have it in a try/catch block just in case you're dealing with a dictionary that doesn't have the meta field, because in that case it would throw a KeyError and break.


text: Q: What is the current status of derived differential geometry? I hope you will excuse this naive and general question. I've read from many places (e.g. Dominic Joyce's website, John Pardon's thesis, etc.) that the/a "right" foundations for many constructions in sympletic geometry, such as Fukaya category, and Gromov-Witten theory should be done starting from some formalism of derived differential geometry. I am aware that Dominic Joyce is still writing a series of books on this, but my question is more about let's say big picture understanding of this approach. Is there a consensus, assuming a general theory of derived manifolds, how these constructions should be done? If so, can someone explain, sacrificing the rigor needed, a high level outline of these constructions? Sorry if this is inside of say Joyce's writings.


text:
Q: ASP.NET: HttpApplication lifecycle In an HttpModule, I'd like to intercept the Response after the HttpResponse.Headers collection has been set but before the body of the Response has been added to the Response Stream. Would this be on the HttpContext.Current.PreSendRequestContent event?

A: No, it would be HttpApplication.PreSendRequestHeaders and there might be content already in the Response stream (even the entire body) waiting to be sent after the headers.


text:
Q: Anonymous class can be replaced with lambda? While i'm writing some code in intellij, it keeps popping up, says

Anonymous class can be replaced with lambda?

So what does that mean? what is lambda expression and how Anonymous class can be replaced with lambda?
Play.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JPanel playscreen = new JPanel();
playscreen.setBackground(Color.WHITE);
p.add(playscreen);

}
});

A: Anonymous new can be replaced with lambda ?
It's not 100% correct, Anonymous class for an interfaces having one abstract method can be replaced with lambda expression (which is called functional interface)
Since ActionListener has only one method actionPerformed(ActionEvent e) you can write it using lambda expression
Play.addActionListener((event) -> {
JPanel playscreen = new JPanel();
playscreen.setBackground(Color.WHITE);
p.add(playscreen);
});

Lambda Expressions

One issue with anonymous classes is that if the implementation of your anonymous class is very simple, such as an interface that contains only one method, then the syntax of anonymous classes may seem unwieldy and unclear. In these cases, you're usually trying to pass functionality as an argument to another method, such as what action should be taken when someone clicks a button. Lambda expressions enable you to do this, to treat functionality as method argument, or code as data.

FunctionalInterface

A functional interface has exactly one abstract method. Since default methods have an implementation, they are not abstract. If an interface declares an abstract method overriding one of the public methods of java.lang.Object, that also does not count toward the interface's abstract method count since any implementation of the interface will have an implementation from java.lang.Object or elsewhere.

A: Your code can be changed to this:
Play.addActionListener((event) -> {
    JPanel playscreen = new JPanel();
    playscreen.setBackground(Color.WHITE);
    p.add(playscreen);
});

The reason you can do this is because ActionListener is a functional interface, meaning that it has exactly one abstract method that you must implement. A lambda is able to essentially take the place of that single function and act as an implementation of that interface.
The Lambda acts like the implementation of the method actionPerformed and (event) is the argument to that method and the -> { ... } is the body of that method.


text:
Q: querydsl - remove whitespace in the middle of a COLUMN Is there a way to do this query in querydsl?
SELECT *
FROM table
WHERE replace(column_name, ' ', '') = 'someValue';

The StringPath from the QClass has no .replace() function and it's necessary for some characters (specifically, spaces in the middle) to be removed from column_name before testing it with someValue.
Sample column_name contents: ABC, DEF, AB *
If someValue is ABC, ABC and AB* should appear.

A: You can express the replace invocation via
Expressions.stringTemplate("replace({0},'  ','')", columnPath)


text:
Q: DBCC or index maintenance causes SQL memory dump and error "Cannot continue the execution because the session is in the kill state." During DBCC and Index Maintenance tasks on one of our databases, we consistently receive an error message: Cannot continue the execution because the session is in the kill state, SQL will also generate a memory dump. (sample below).
We have plenty of space available in the database, and in TempDB.
What are some possible causes? We have applied the latest CU for 2019, and also restored this database to a test environment where the same error is generated.
Current time is 10:01:44 11/14/22.
=====================================================================
       BugCheck Dump
=====================================================================

This file is generated by Microsoft SQL Server
version 15.0.4261.1
upon detection of fatal unexpected error. Please return this file,
the query or program that produced the bugcheck, the database and
the error log, and any other pertinent information with a Service Request.

Computer type is Intel(R) Xeon(R) Platinum 8280 CPU @ 2.70GHz.
Bios Version is INTEL  - 6040000
PhoenixBIOS 4.0 Release 6.0
8 X64 level 8664, 2 Mhz processor (s).
Windows NT 10.0 Build 14393 CSD .

Memory
MemoryLoad = 66%
Total Physical = 32767 MB
Available Physical = 10841 MB
Total Page File = 37631 MB
Available Page File = 13601 MB
Total Virtual = 134217727 MB
Available Virtual = 134033777 MB
***Stack Dump being sent to D:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\MSSQL\LOG\SQLDump0229.txt
SqlDumpExceptionHandler: Process 57 generated fatal exception c0000005 EXCEPTION_ACCESS_VIOLATION. SQL Server is
terminating this process.
* *******************************************************************************
*
* BEGIN STACK DUMP:
*   11/14/22 10:01:44 spid 57
*
*
*   Exception Address = 00007FFAAD371D77 Module(sqlmin+00000000000F1D77)
*   Exception Code    = c0000005 EXCEPTION_ACCESS_VIOLATION
*   Access Violation occurred reading address 0000000000000000
* Input Buffer 122 bytes -
*             DBCC CHECKDB('DP_XXX_SAP') WITH PHYSICAL_ONLY
*
*
*  MODULE                          BASE      END       SIZE
* sqlservr                       00007FF770D80000  00007FF770E1EFFF  0009f000
* ntdll                          00007FFAD0C70000  00007FFAD0E3EFFF  001cf000
* KERNEL32                       00007FFAD03C0000  00007FFAD046CFFF  000ad000
* KERNELBASE                     00007FFACD470000  00007FFACD68DFFF  0021e000
* CRYPT32                        00007FFACD690000  00007FFACD882FFF  001f3000
* ucrtbase                       00007FFACDA10000  00007FFACDB03FFF  000f4000
* MSASN1                         00007FFACD0B0000  00007FFACD0BFFFF  00010000
* ADVAPI32                       00007FFAD0980000  00007FFAD0A25FFF  000a6000
* msvcrt                         00007FFAD00E0000  00007FFAD017DFFF  0009e000
* sechost                        00007FFACE440000  00007FFACE49AFFF  0005b000
* RPCRT4                         00007FFACE580000  00007FFACE69CFFF  0011d000
* ole32                          00007FFAD0470000  00007FFAD05A8FFF  00139000
* combase                        00007FFAD05B0000  00007FFAD0875FFF  002c6000
* bcryptPrimitives               00007FFACD9A0000  00007FFACDA0BFFF  0006c000
* GDI32                          00007FFAD0080000  00007FFAD00B3FFF  00034000
* gdi32full                      00007FFACD1F0000  00007FFACD373FFF  00184000
* USER32                         00007FFACE210000  00007FFACE375FFF  00166000
* win32u                         00007FFACE1F0000  00007FFACE20DFFF  0001e000
* NETAPI32                       00007FFAC32B0000  00007FFAC32C8FFF  00019000
* pdh                            00007FFAC3470000  00007FFAC34BCFFF  0004d000
* SQLOS                          00007FFAB2970000  00007FFAB2977FFF  00008000
* sqlmin                         00007FFAAD280000  00007FFAB02E7FFF  03068000
* sqllang                        00007FFAB02F0000  00007FFAB2922FFF  02633000
* sqlTsEs                        00007FFAAC990000  00007FFAAD25CFFF  008cd000
* sqldk                          00007FFAAC460000  00007FFAAC98DFFF  0052e000
* OLEAUT32                       00007FFACE380000  00007FFACE43FFFF  000c0000
* msvcp_win                      00007FFACD380000  00007FFACD41BFFF  0009c000
* opends60                       00007FFAB2960000  00007FFAB2968FFF  00009000
* qds                            00007FFAAC260000  00007FFAAC38BFFF  0012c000
* svl                            00007FFAB2930000  00007FFAB295CFFF  0002d000
* WS2_32                         00007FFAD01E0000  00007FFAD0249FFF  0006a000
* MSVCP140                       00007FFAC39B0000  00007FFAC3A3CFFF  0008d000
* MPR                            00007FFAC38E0000  00007FFAC38FAFFF  0001b000
* VCRUNTIME140                   00007FFAC3990000  00007FFAC39AAFFF  0001b000
* WININET                        00007FFABFE20000  00007FFAC0201FFF  003e2000
* WINMM                          00007FFACB640000  00007FFACB662FFF  00023000
* Secur32                        00007FFAC3580000  00007FFAC358BFFF  0000c000
* WINHTTP                        00007FFAC6EE0000  00007FFAC6FACFFF  000cd000
* secforwarder                   00007FFAAC240000  00007FFAAC250FFF  00011000
* ODBC32                         00007FFABA710000  00007FFABA7BEFFF  000af000
* VCRUNTIME140_1                 00007FFAC3520000  00007FFAC352BFFF  0000c000
* WINMMBASE                      00007FFACB610000  00007FFACB63AFFF  0002b000
* cfgmgr32                       00007FFACD420000  00007FFACD461FFF  00042000
* DPAPI                          00007FFACC290000  00007FFACC299FFF  0000a000
* ncrypt                         00007FFACCBF0000  00007FFACCC15FFF  00026000
* bcrypt                         00007FFACCFF0000  00007FFACD01AFFF  0002b000
* NTASN1                         00007FFACCBB0000  00007FFACCBEAFFF  0003b000
* NETUTILS                       00007FFACC790000  00007FFACC79CFFF  0000d000
* SSPICLI                        00007FFACCD10000  00007FFACCD3BFFF  0002c000
* SAMCLI                         00007FFAC9970000  00007FFAC9988FFF  00019000
* WINTRUST                       00007FFACD890000  00007FFACD8E4FFF  00055000
* USERENV                        00007FFACC7A0000  00007FFACC7BFFFF  00020000
* AUTHZ                          00007FFACC310000  00007FFACC35AFFF  0004b000
* dhcpcsvc                       00007FFACA030000  00007FFACA049FFF  0001a000
* profapi                        00007FFACD0C0000  00007FFACD0D3FFF  00014000
* NSI                            00007FFAD0AC0000  00007FFAD0AC7FFF  00008000
* LOGONCLI                       00007FFACC7C0000  00007FFACC7FFFFF  00040000
* psapi                          00007FFACE570000  00007FFACE577FFF  00008000
* kernel.appcore                 00007FFACD0E0000  00007FFACD0EEFFF  0000f000
* instapi150                     00007FFAA85A0000  00007FFAA85B3FFF  00014000
* CRYPTSP                        00007FFACCB20000  00007FFACCB36FFF  00017000
* rsaenh                         00007FFACC530000  00007FFACC562FFF  00033000
* CRYPTBASE                      00007FFACCFE0000  00007FFACCFEAFFF  0000b000
* imagehlp                       00007FFAD00C0000  00007FFAD00DBFFF  0001c000
* gpapi                          00007FFACC040000  00007FFACC062FFF  00023000
* wkscli                         00007FFAC9BC0000  00007FFAC9BD7FFF  00018000
* cscapi                         00007FFAA9AC0000  00007FFAA9AD1FFF  00012000
* sqlevn70                       000001A117150000  000001A11748EFFF  0033f000
* CLUSAPI                        00007FFAC0CF0000  00007FFAC0DA8FFF  000b9000
* DNSAPI                         00007FFACC6E0000  00007FFACC781FFF  000a2000
* IPHLPAPI                       00007FFACC6A0000  00007FFACC6D7FFF  00038000
* RESUTILS                       00007FFAC17A0000  00007FFAC1800FFF  00061000
* VERSION                        00007FFAC3A40000  00007FFAC3A49FFF  0000a000
* hkruntime                      00007FFA96C00000  00007FFA96ED2FFF  002d3000
* hkcompile                      00007FFA96840000  00007FFA9697FFFF  00140000
* dbghelp                        00007FFAC32D0000  00007FFAC3461FFF  00192000
* hkengine                       00007FFA96140000  00007FFA96836FFF  006f7000
* SHLWAPI                        00007FFAD0A30000  00007FFAD0A81FFF  00052000
* XmlLite                        00007FFAC56E0000  00007FFAC5715FFF  00036000
* ncryptprov                     00007FFAC34C0000  00007FFAC3513FFF  00054000
* msv1_0                         00007FFACC900000  00007FFACC966FFF  00067000
* NtlmShared                     00007FFACC8F0000  00007FFACC8FBFFF  0000c000
* cryptdll                       00007FFACC9D0000  00007FFACC9E3FFF  00014000
* kerberos                       00007FFACCA20000  00007FFACCB10FFF  000f1000
* schannel                       00007FFACC470000  00007FFACC4E7FFF  00078000
* SECURITY                       000001A7B6100000  000001A7B6102FFF  00003000
* MSCOREE                        00007FFABA680000  00007FFABA6E5FFF  00066000
* mscoreei                       00007FFAB2980000  00007FFAB2A1BFFF  0009c000
* SqlServerSpatial150            00007FFA939A0000  00007FFA93A41FFF  000a2000
* clbcatq                        00007FFACE6A0000  00007FFACE73EFFF  0009f000
* msxml3                         00007FFA930A0000  00007FFA932CBFFF  0022c000
* msoledbsql                     00007FFA92C50000  00007FFA92ED7FFF  00288000
* COMDLG32                       00007FFAD0880000  00007FFAD0979FFF  000fa000
* shcore                         00007FFACD140000  00007FFACD1E7FFF  000a8000
* SHELL32                        00007FFACEB70000  00007FFAD0075FFF  01506000
* windows.storage                00007FFACDB10000  00007FFACE1E5FFF  006d6000
* COMCTL32                       00007FFAC5140000  00007FFAC51EBFFF  000ac000
* powrprof                       00007FFACD0F0000  00007FFACD13BFFF  0004c000
* MSWSOCK                        00007FFACC970000  00007FFACC9CCFFF  0005d000
* MSOLEDBSQLR                    000001A7B8300000  000001A7B8321FFF  00022000
* dhcpcsvc6                      00007FFACA130000  00007FFACA145FFF  00016000
* sqlncli11                      00007FFA93EE0000  00007FFA94232FFF  00353000
* MSVCR100                       0000000060700000  00000000607D1FFF  000d2000
* SQLNCLIR11                     000001A7B8330000  000001A7B8367FFF  00038000
* netbios                        00007FFABEF50000  00007FFABEF5BFFF  0000c000
* sqlnclirda11                   000000005FD90000  00000000600E8FFF  00359000
* SQLNCLIRDAR11                  000001A7B8390000  000001A7B83C7FFF  00038000
* ualapi                         00007FFACA8D0000  00007FFACA8E9FFF  0001a000
* ESENT                          00007FFACA5D0000  00007FFACA8C1FFF  002f2000
* ntmarta                        00007FFACBE10000  00007FFACBE41FFF  00032000
* clr                            00007FFAAB800000  00007FFAAC23AFFF  00a3b000
* MSVCR120_CLR0400               00007FFAAB6D0000  00007FFAAB7C6FFF  000f7000
* mscorlib.ni                    00007FFAA9DE0000  00007FFAAB370FFF  01591000
* SqlAccess                      00007FFA93020000  00007FFA93095FFF  00076000
* clrjit                         00007FFAA9260000  00007FFAA938AFFF  0012b000
* BatchParser                    00007FFA92690000  00007FFA926B9FFF  0002a000
* SRVCLI                         00007FFAC46B0000  00007FFAC46D5FFF  00026000
* ftimport                       0000000000350000  0000000000374FFF  00025000
* MSFTE                          0000000049980000  0000000049D2DFFF  003ae000
* mskeyprotect                   00007FFAA8410000  00007FFAA8424FFF  00015000
* ntdsapi                        00007FFAC2AA0000  00007FFAC2AC8FFF  00029000
* DSPARSE                        00007FFAC9BE0000  00007FFAC9BECFFF  0000d000
* ncryptsslp                     00007FFAA8490000  00007FFAA84B0FFF  00021000
* xpsqlbot                       00007FFAA4100000  00007FFAA4109FFF  0000a000
* xpstar                         00007FFA90800000  00007FFA90871FFF  00072000
* SQLSCM                         00007FFA90C50000  00007FFA90C63FFF  00014000
* xpstar                         000001A95FDA0000  000001A95FDACFFF  0000d000
* cryptnet                       00007FFABFC20000  00007FFABFC4EFFF  0002f000
* odbccp32                       00007FFA906D0000  00007FFA906F3FFF  00024000
* rasadhlp                       00007FFAC7580000  00007FFAC7589FFF  0000a000
* fwpuclnt                       00007FFACA390000  00007FFACA3F9FFF  0006a000
* oledb32                        00007FFA88EF0000  00007FFA88FDCFFF  000ed000
* MSDART                         00007FFA90080000  00007FFA900A5FFF  00026000
* Comctl32                       00007FFABB220000  00007FFABB499FFF  0027a000
* comsvcs                        00007FFAB2B10000  00007FFAB2CACFFF  0019d000
* msdasql                        00007FFA88E30000  00007FFA88EE0FFF  000b1000
* MSDATL3                        00007FFA88E00000  00007FFA88E21FFF  00022000
* MSDASQLR                       000001A7B8470000  000001A7B847FFFF  00010000
* SQLSRV32                       00007FFA88D40000  00007FFA88DF9FFF  000ba000
* xplog70                        00007FFA999A0000  00007FFA999B5FFF  00016000
* xplog70                        000001A7B86C0000  000001A7B86C3FFF  00004000
* msodbcsql17                    00007FFA90A30000  00007FFA90C03FFF  001d4000
* sqlvdi                         00007FFAC4510000  00007FFAC454AFFF  0003b000
* EpMPApi                        00007FFA8F7B0000  00007FFA8F853FFF  000a4000
* EpMPThe                        000000005FC70000  000000005FC7BFFF  0000c000
* DBNETLIB                       00007FFAA3560000  00007FFAA3581FFF  00022000
*
*     P1Home: 000001BC95119090:  0000000000000000  0000000000000001  0000000000000000  0000000000000000  000001BC
95118620  00000004FFFFFFFF
*     P2Home: 000001BC95118CB0:  000001BC00000002  000001BC95118620  000001BC95118B30  000001BC95118AB0  000001BC
95118CD0  000001BC95118CD0
*     P3Home: 0100000013440000:
*     P4Home: 00007FFAAD28D6A2:  186B8948246B8966  0FC98548704B8B48  4B8B480005821685  866B850FC9854858  4B8B4803
8B48000B  0189480848894808
*     P5Home: 000001BC95118FF0:  000001BC00000001  000001BC95118620  000001BC95118D80  000001AC25D9BE68  000001AC
25D9BF78  0000000000000002
*     P6Home: 000001BC95119740:  000001BC95118CE0  000001A1C4D96A90  0000000000000001  0000000000000000  00000000
00000000  000001BC95119100
* ContextFlags: 000000000010005F:
*      MxCsr: 0000000000001FA8:
*      SegCs: 0000000000000033:
*      SegDs: 000000000000002B:
*      SegEs: 000000000000002B:
*      SegFs: 0000000000000053:
*      SegGs: 000000000000002B:
*      SegSs: 000000000000002B:
*     EFlags: 0000000000010246:
*        Rax: 0000000000000000:
*        Rcx: 0000000000000000:
*        Rdx: 0000000000000002:
*        Rbx: 0100000013440000:
*        Rsp: 0000007212DF2490:  0100000013440000  0000000000000000  0000000000000000  000001AF9DD23DD0  000001A4
ABE03D00  0000007212DF0003
*        Rbp: 0000000000000000:
*        Rsi: 0000000000000000:
*        Rdi: 000001B52AFA6EE0:  00007FFAAEF1CD50  000001B52AFA7FE0  0000000000000000  0000000000000000  00000000
00000000  0000000000000000
*         R8: 0000000000000000:
*         R9: 0000000000000003:
*        R10: 000001AF9DD22160:  0000000000000000  0000000000000000  000001CAC0C32170  000001BE1758A170  21212121
00000001  000001A198032378
*        R11: 0000007212DF1F80:  0000007212DF2090  00007FFAAD372A1B  000001AF9DD23D28  0000000000000002  000001A4
84122380  0000000000000010
*        R12: 0000000000000000:
*        R13: 000001BA67F80460:  00007FFAAEF40E68  000001B302A08048  000001BA67F80190  00007FFAAF69FE78  00007FFA
AF69FE78  000001BC34D30040
*        R14: 000001AF9DD23D10:  00007FFAAEF4AE58  00007FFAAEF5E380  0000007212DF24F0  0100000013440000  0047000F
00000293  000040000018000B
*        R15: 0000000000000000:
*        Rip: 00007FFAAD371D77:  1824948D48078B49  50FFCF8B49000001  8087894824448B08  4C2444B70F000003  66000003
84878966  B70F00000386B789
* *******************************************************************************
* -------------------------------------------------------------------------------
* Short Stack Dump
00007FFAAD371D77 Module(sqlmin+00000000000F1D77)
00007FFAAD35EC9D Module(sqlmin+00000000000DEC9D)
00007FFAAD35E90B Module(sqlmin+00000000000DE90B)
00007FFAAD35DAE5 Module(sqlmin+00000000000DDAE5)
00007FFAAD35F091 Module(sqlmin+00000000000DF091)
00007FFAAE883CE7 Module(sqlmin+0000000001603CE7)
00007FFAAE8818E3 Module(sqlmin+00000000016018E3)
00007FFAAE874D98 Module(sqlmin+00000000015F4D98)
00007FFAAE8ED64C Module(sqlmin+000000000166D64C)
00007FFAB1391EF0 Module(sqllang+00000000010A1EF0)


text:
Q: With python, How to read the "date created" of a file? I am writing a short script in python that will scan through a list of folders for image files and then re-organize them.
One of the optional way of organizing them i wish to have is by the date they are created.
Currently, I am trying to read the image creation date as follows
import os.path, time

f = open("hi.jpg")
data = f.read()
f.close()
print "last modified: %s" % time.ctime(os.path.getmtime(f))
print "created: %s" % time.ctime(os.path.getctime(f))

But I get an error that reads
Traceback (most recent call last):
  File "TestEXIFread.py", line 6, in <module>
    print "last modified: %s" % time.ctime(os.path.getmtime(f))
  File "/usr/lib/python2.7/genericpath.py", line 54, in getmtime
    return os.stat(filename).st_mtime
TypeError: coercing to Unicode: need string or buffer, file found

Can anyone tell me what it means?

A: You need to be using a string for the filename instead of the file object.
>>> import os.path, time
>>> f = open('test.test')
>>> data = f.read()
>>> f.close()
>>> print "last modified: %s" % time.ctime(os.path.getmtime('test.test'))
last modified: Fri Apr 13 20:39:21 2012
>>> print "created : %s" % time.ctime(os.path.getctime('test.test'))
created : Fri Apr 13 20:39:21 2012


text:
Q: Java not recognizing public classes in same project file I'm coding in Java using IntelliJ IDEA 2022 on Windows 10. I run each program from IntelliJ's terminal using the following command:
cmd /c --% java -cp <Location of .jar file of library I use> FileName.java
This worked fine for running programs that only contained methods from that library. However, now that I want to use methods from another class I wrote that is in the same folder as the one I want to run, it throws the following error:
error: cannot find symbol
How can I solve this?
I'm quite new to programming so sorry if the question is a bit unclear

A: If you want to do more coding in Java, I would recommend that you don't work with manual compilation and execution, but use a build system like Gradle or Maven
Both follow the "Convention over Configuration" approach, Maven more than Gradle, that means you have to place your code into a specific folder structure. But you also have to create a small configuration file (either build.gradle for Gradle or pom.xml for Maven).
As you use IntelliJ IDEA, you could simply create a project as Gradle or Maven project inside the IDE, which creates the folder structure for you, but I would also recommend that you work through the respective "Getting started" sections of the documentation.
While using a build system gives you the burden of learning an additional system from the beginning, it will make your life as developer so much easier on the long run, that I would say it is worth to learn that stuff early.
Plan B: When you do not want to learn it (or not yet), you could use a track of Oracles Java Tutorial to learn how to first compile and then run Java code in two individual steps. The chapter is called "Hello World!" for Microsoft Windows. While the tutorial was written for an older version of Java (JDK 8) and does not cover the trick with the compiling and running a single Java class with one command, it still is a good source for some more basic steps. Compiling and running java classes in a way that multiple classes can be used together is one of them.


text:
Q: Cannot borrow pointer even if previous borrow is "forgotten"? I do not understand why the function fn1 doesn't compile, i.e.
why "let z = &mut x;" cannot be assigned while previously
taken reference stored in "y" is not used anymore ("y" is reassigned
to something else).
Moreover, why both fn2 and fn3 do compile ok while they are doing "logically" the same thing?
fn2 differs from fn1 in fact, that "y" goes out of scope instead of reassigning, but that is
different only in respect to "y" pointer storage, not in respect to what is "y" pointing to.
fn3 differs from fn1 in fact, that "z" is assigned from "y" instead of directly from "&mut x".
fn fn1() {
    let mut x = 1i32;
    let mut somethingelse = 7i32;
    let mut y = &mut x;
    *y = *y + 1;
    println!("y = {}", *y);
    y = &mut somethingelse;
    println!("just something: {}", *y);
    // y is not used anymore...
    let z = &mut x;
    *z = *z + 1;
    println!("z = {}", *z);
}

fn fn2() {
    let mut x = 1i32;
    {
        let y = &mut x;
        *y = *y + 1;
        println!("y = {}", *y);
    }
    let z = &mut x;
    *z = *z + 1;
    println!("z = {}", *z);
}

fn fn3() {
    let mut x = 1i32;
    let z;
    let y = &mut x;
    *y = *y + 1;
    println!("y = {}", *y);
    z = y;
    *z = *z + 1;
    println!("z = {}", *z);
}

A: Currently, borrow scopes are lexical, that is, they correspond to the braces in the code. There's a bug to change this to account for cases like your fn1, but like you see in fn2, there are workarounds for now.
For fn3, if you try to use y again, you will get this error:
error: use of moved value: `*y`

This is because the compiler can tell (via the statement z = y) that y is no longer needed and thus moves the mutable borrow to z, making y invalid.


text:
Q: sql query to get data from an audit table where column match one value, but not another I have a table t_audit with 4 columns: name, address, updated (Y or N), and user_id (ID of the user who updates it).
I want to search the audit table, to get the names of customers updated by user_id 1, but not 2.
I tried this:
select ta.name
from t_audit ta
where (ta.updated = 'Y' and user_id = 1 )
    and not exists (ta.updated='Y' and user_id = 2)

But it does not work. How can I fix this?

A: for Oracle
select ta.name
from t_audit ta
where (ta.updated = 'Y' and user_id = 1 )
minus
select ta.name
from t_audit ta
where (ta.updated = 'Y' and user_id = 2 )

for others
select ta.name
from t_audit ta
where (ta.updated = 'Y' and user_id = 1 )
EXCEPT
select ta.name
from t_audit ta
where (ta.updated = 'Y' and user_id = 2 )

A: Your not-exists syntax is incorrect, the following is untested of course by should be close to what you are expecting
select ta.name
from t_audit ta
where ta.updated = 'Y' and ta.user_id = 1
  and not exists (
    select * from t_audit ta2
    where ta2.name=ta.name and ta2.updated='Y' and ta2.user_id = 2
)


text:
Q: Pass a variable to a PHP script running from the command line I have a PHP file that is needed to be run from the command line (via crontab). I need to pass type=daily to the file, but I don't know how. I tried:
php myfile.php?type=daily

but this error was returned:

Could not open input file: myfile.php?type=daily

What can I do?

A: Just pass it as normal parameters and access it in PHP using the $argv array.
php myfile.php daily

and in myfile.php
$type = $argv[1];

A: Parameters send by index like other applications:
php myfile.php type=daily

And then you can get them like this:
<?php
    if (count($argv) == 0)
        exit;

    foreach ($argv as $arg)
        echo $arg;
?>

A: Save this code in file myfile.php and run as php myfile.php type=daily
<?php
$a = $argv;
$b = array();
if (count($a) === 1) exit;
foreach ($a as $key => $arg) {
    if ($key > 0) {
        list($x,$y) = explode('=', $arg);
        $b["$x"] = $y;
    }
}
?>

If you add var_dump($b); before the ?> tag, you will see that the array $b contains type => daily.

A: You can use the following code to both work with the command line and a web browser. Put this code above your PHP code. It creates a $_GET variable for each command line parameter.
In your code you only need to check for $_GET variables then, not worrying about if the script is called from the web browser or command line.
if(isset($argv))
    foreach ($argv as $arg) {
        $e=explode("=",$arg);
        if(count($e)==2)
            $_GET[$e[0]]=$e[1];
        else
            $_GET[$e[0]]=0;
    }

Edited. Using this I found a Small bug. If your parameter value contains an = it fails. I'm using this code now:
if(isset($argv))
   foreach ($argv as $arg) {
       $e=explode("=",$arg);
       if(count($e)>=2)
           $_GET[$e[0]]=substr($arg,strlen($e[0])+1,strlen($arg));
       else
           $_GET[$e[0]]=0;
   }

A: I strongly recommend the use of getopt.
If you want help to print out for your options then take a look at GetOptionKit.

A: You could use what sep16 on php.net recommends:
<?php

parse_str(implode('&', array_slice($argv, 1)), $_GET);

?>

It behaves exactly like you'd expect with cgi-php.
$ php -f myfile.php type=daily a=1 b[]=2 b[]=3

will set $_GET['type'] to 'daily', $_GET['a'] to '1' and $_GET['b'] to array('2', '3').

A: Just pass it as parameters as follows:
php test.php one two three

And inside file test.php:
<?php
    if(isset($argv))
    {
        foreach ($argv as $arg)
        {
            echo $arg;
            echo "\r\n";
        }
    }
?>

A: These lines will convert the arguments of a CLI call like php myfile.php "type=daily&foo=bar" into the well known $_GET-array:
if (!empty($argv[1])) {
    parse_str($argv[1], $_GET);
}

Though it is rather messy to overwrite the global $_GET-array, it converts all your scripts quickly to accept CLI arguments.
See parse_str for details.

If you want the more traditional CLI style like php myfile.php type=daily foo=bar a small function can convert this into an associative array compatible with a $_GET-array:
// Convert $argv into associative array
function parse_argv(array $argv): array
{
    $request = [];
    foreach ($argv as $i => $a) {
        if (!$i) {
            continue;
        }

        if (preg_match('/^-*(.+?)=(.+)$/', $a, $matches)) {
            $request[$matches[1]] = $matches[2];
        } else {
            $request[$a] = true;
        }
    }

    return $request;
}

if (!empty($argv[1])) {
    $_GET = parse_argv($argv);
}

A: Using the getopt() function, we can also read a parameter from the command line. Just pass a value with the php running command:
php abc.php --name=xyz

File abc.php
$val = getopt(null, ["name:"]);
print_r($val); // Output: ['name' => 'xyz'];

A: The ?type=daily argument (ending up in the $_GET array) is only valid for web-accessed pages.
You'll need to call it like php myfile.php daily and retrieve that argument from the $argv array (which would be $argv[1], since $argv[0] would be myfile.php).
If the page is used as a webpage as well, there are two options you could consider. Either accessing it with a shell script and Wget, and call that from cron:
#!/bin/sh
wget http://location.to/myfile.php?type=daily

Or check in the PHP file whether it's called from the command line or not:
if (defined('STDIN')) {
  $type = $argv[1];
} else {
  $type = $_GET['type'];
}

(Note: You'll probably need/want to check if $argv actually contains enough variables and such)

A: There are four main alternatives. Both have their quirks, but Method 4 has many advantages from my view.

./script is a shell script starting by #!/usr/bin/php

Method 1: $argv
./script hello wo8844rld
// $argv[0] = "script", $argv[1] = "hello", $argv[2] = "wo8844rld"

⚠ Using $argv, the parameter order is critical.

Method 2: getopt()
./script -p7 -e3
// getopt("p::")["p"] = "7", getopt("e::")["e"] = "3"

It's hard to use in conjunction of $argv, because:

⚠ The parsing of options will end at the first non-option found,
anything that follows is discarded.

⚠ Only 26 parameters as the alphabet.

Method 3: Bash Global variable
P9="xptdr" ./script
// getenv("P9") = "xptdr"
// $_SERVER["P9"] = "xptdr"

Those variables can be used by other programs running in the same shell.
They are blown when the shell is closed, but not when the PHP program is terminated. We can set them permanent in file ~/.bashrc!

Method 4: STDIN pipe and stream_get_contents()
Some piping examples:

Feed a string:
./script <<< "hello wo8844rld"
// stream_get_contents(STDIN) = "hello wo8844rld"

Feed a string using bash echo:
echo "hello wo8844rld" | ./script
// explode(" ",stream_get_contents(STDIN)) ...

Feed a file content:
./script < ~/folder/Special_params.txt
// explode("\n",stream_get_contents(STDIN)) ...

Feed an array of values:
./script <<< '["array entry","lol"]'
// var_dump( json_decode(trim(stream_get_contents(STDIN))) );

Feed JSON content from a file:
echo params.json | ./script
// json_decode(stream_get_contents(STDIN)) ...

It might work similarly to fread() or fgets(), by reading the STDIN.

Bash-Scripting Guide

A: if (isset($argv) && is_array($argv)) {
    $param = array();
    for ($x=1; $x<sizeof($argv);$x++) {
        $pattern = '#\/(.+)=(.+)#i';
        if (preg_match($pattern, $argv[$x])) {
            $key =  preg_replace($pattern, '$1', $argv[$x]);
            $val =  preg_replace($pattern, '$2', $argv[$x]);
            $_REQUEST[$key] = $val;
            $$key = $val;
        }
    }
}

I put parameters in $_REQUEST:
$_REQUEST[$key] = $val;

And it is also usable directly:
$$key = $val

Use it like this:
myFile.php /key=val

A: I found this vanilla/garden-cli on github. I think it answers all the needs for PHP CLI.

A: To bypass the complexity of passing to the file, it sounds like you could use sed to insert the line directly into the php file.
sed -i "i (backslash)type=daily myfile.php
or as I use it with variables:

sed -i "i (backslash)$type = "(backslash)"${daily}(backslash)"(backslash); ${path}"/myfile.php"


text:
Q: CSS: how to make a circle with 60% one color and 40% other color around an image? Is it possible to make a circle with 60% one color and 40% other color around an image.
I have tried using the below code,
//CSS
.waitlist .img-thumbnail {
    border: 2px solid #dee2e6;
    background: linear-gradient(90deg, #2A89F6 50%, transparent 50%),
                linear-gradient(-90deg, #CCC 50%, transparent 50%);
}

//HTML

The output for above code is,

But I want the output as,

Is it possible to achieve the required output?

A: you can do it like this:

.box {
  border-radius:50%;
  display:inline-block;
  padding:5px;
  background:
   linear-gradient(-40deg, grey 50%,transparent 0), /*adjust the deg value here to control the %*/
   linear-gradient(to right, red 50%,transparent 0),
   grey;
}
.box img {
  border-radius:50%;
  display:block;
}


text:
Q: Gson Json conversion adding extra back slash I am working on a service that has the following code (I can change this code):
import com.google.gson.JsonObject;
import com.google.gson.Gson;

Gson gson = new Gson();
JsonObject json = new JsonObject();
json.addProperty("customer", gson.toJson(customer));
anotherServiceClient.dispatch(json.toString());

AnotherService Class code has a dispatch method implementation that takes in a String object and adds it to a json where party is a String. I can't change this code.
    JsonObject json = new JsonObject();
    json.addProperty("party", inputCustomerJson);

I need the anotherService to have the output like:
"party": "{\"customer\":\"{\"id\":\"A123\"}"}

but instead it is :
"party": "{\"customer\":\"{\\\"id\\\":\\\"A123\\\"}"}

A: The problem is this line:

json.addProperty("customer", gson.toJson(customer));

Gson.toJson produces a JSON string as output ("{\"id\":\"A123\"}"), so when you then later serialize this data again as JSON the backslashes and double quotes are escaped.
Most likely you want to use Gson.toJsonTree and JsonObject.add(String, JsonElement):
json.add("customer", gson.toJsonTree(customer));


text:
Q: OpenCart install on bluehost getting 5.2+ required I'm getting PHP 5.2+ required when installing OpenCart on Bluehost.
Bluehost runs PHP 5.2.9. Searching the forums I see others running OpenCart successfully on this version.
Where do I start to try and get opencart up and running?

A: First of all, 5.2.9 is definitly 5.2+ (5.2+ means at least 5.2 ; 5.2.9 is 5.2 with fixes ;-) )
You could try to check the version of PHP you have on your hosting service, creating a page that only contains
<?php
    phpinfo();
?>

This post could interest you, too : Bluehost php5 or php4 your choice ; either you have to go through their support, or maybe you have some option in your administration panel, to choose between PHP 4 (which is way outdated... it's a shame if it's still the default version) and PHP 5 ?

A: To fix this issue

*

*List item

*Log into cPanel

*Click Software / Services

*Click PHP Config

*Select PHP5

*Save your changes

A: upload a php file with the following code in it to your webroot and open it, it will tell you which version of php is really running. There is a chance that php wasn't upgraded on the box you are on.
<?
echo 'Current PHP version: ' . phpversion();


text:
Q: How it is possible to 'rotate image, only if it is in portrait mode (But not in landScape mode)' In my iphone application I have used image view to display the enlarged images, getting from another view,
in first view i have a specified place for display ing images captured from imagePicker,
Here images are displayed in correct orientation what we captured
In the (2nd) detail view, i have a large (3x4) image view to display the captured image in bigSize, (Here ALSO images are displayed in correct orientation what we captured)
But
My requirement is i need to display large image in 3x4 pixel ratio image view,
For this
If image in landScape mode display it in as it is orientation,
If it is in portrait mode we need to rotate it to landscape (90˚).
How it is possible to rotate image , ONLY IF it is in portrait mode (But not in landScape mode)

A: All you need to do is to check the size of the image in terms of height and width. If the height of the image is greater than the width of the image clicked then this means that you have taken the image in portrait mode.


text:
Q: TypeScript array sort by array off numbers I Need to sort an array by ID. checkin another array of numbers
    var itens:[] = [{
    item:{id:1},item:{id:2},item:{id:3},item:{id:4}
    }]

var sort:[] = [1,3,2,4];

result:
var itens:[] = [{
    item:{id:1},item:{id:3},item:{id:2},item:{id:4}
    }]

A: Your items array is not really correct, that's an array of one item.
With that fixed, here is how you could sort:
const items = [{id: 1}, {id: 2}, {id: 3}, {id: 4}];
const sort = [1, 3, 2, 4];
const sorted = sort.map(val => items.find(item => item.id === val));
console.log(sorted);


text:
Q: Using array_map vs array_column and array_combine in php Let's say I have an associative array like below:
$myAssocArray = [
[ 'Name' => 'AWS_Bucket-Name1',  'Value' => 'Bucket data',...],
[ 'Name' => 'AWS_Bucket-Name2',  'Value' => 'Bucket data',...],
[ 'Name' => 'AWS_Bucket-Name3',  'Value' => 'Bucket data',...],
[ 'Name' => 'AWS_Bucket-Name4',  'Value' => 'Bucket data',...],
];

From this I want to create a simple associative array like below:
[ ['AWS_Bucket-Name1' => 'Bucket data'], ['AWS_Bucket-Name2' => 'Bucket data'], ...]

So I can take two approaches to resolve this:
(1) Use array_map function in php:
$destinationArray = array_map('myMapFunction', $myAssocArray);

function myMapFunction($entity): array {
   if (is_array($entity) && isset($entity['Name'], $entity['Value'])) {
      return [$entity['Name'] => $entity['Value']];
    }
}

OR
(2) Using array_column and array_combine functions:
$keys = array_column($myAssocArray, 'Name');
$values = array_column($myAssocArray, 'Value');
$destinationArray = array_combine($keys, $values);

What will be more recommended approach and which will be more performant and efficient? OR is there even better solution available that does not need foreach loop?

A: I wouldn't look at the performance here because these operations are very small. I would focus more on the clean code side.
array_map() solution is harder to understand at the first look.
You don't need to use array_combine() and double invocation of array_column(). Instead you can pass third argument to array_column() which is

"index key"
  The column to use as the index/keys for the returned array. This value may be the integer key of the column, or it may be the string key name.

The following code
array_column($myAssocArray, 'Value', 'Name')

prints the same output as desired.
Have in mind that PHP internally can notice and optimize a lot of things to improve performance. Obviously, it's better when developer does so, but sometimes you gain 1 μs of performance with the cost of clean code and headache of a developer maintaining that code.

*

*Working fiddle

*More info on php.net/array_column


text:
Q: Programs to find class number of bi-quadratic fields I'm interested in studying ideal class group structure for bi-quadratic fields.
The problem I'm facing is the lack of examples.
Is there any program where I can find the class number of a bi-quadratic field (at least for small discriminant)?
I've found the following link for real quadratic fields (if it helps someone):
http://www.numbertheory.org/php/classnopos.html


text:
Q: Random adjacency matrix with variation on number of edges per node The following function returns a randomly generated adjacency matrix of size nxn, representing a graph.
import random

def random_adjacency_matrix(n):
    matrix = [[random.randint(0, 1) for i in range(n)] for j in range(n)]

    # No vertex connects to itself
    for i in range(n):
        matrix[i][i] = 0

    # If i is connected to j, j is connected to i
    for i in range(n):
        for j in range(n):
            matrix[j][i] = matrix[i][j]

    return matrix

It is a very naive solution, and I'd like it to satisfy two additional requirements.

*

*The graph the matrix represents must be fully connected, in other words there must not be any nodes that can't be reached from any other node in some number of steps.

*Each node has a number of edges. Right now it's totally random, and thus fairly uniform how many edges a node has, and when n is large the average number of edges tends to be large too for all graphs. I would like the average number of edges per node to vary more, independent of the size of the graph, so that some graphs have very few connections and others have a lot.
Edit:
Using the networkx package, this seems to be what I want, only with point 1 above also satisfied:
import networkx, random
G = networkx.binomial_graph(50, random.random()) # 50 nodes, random probability of an edge

A: First, let met recommend the networkx graph library.  It's very easy to use and has a nice toolbox of algorithms already included.  For instance, you can easily test a graph for connectivity or ask for the set of connected components in the graph.
Second, there are a variety of named statstical distributions that are canon.  If you could find the one you're thinking of, that would be helpful to both you and anyone that's offering to help.  From the rough description that you've given, it sounds like you might be looking for a power-law distribution (aka "long tail" distribution, see also "scale free network").  You see these kinds of distributions a lot in (e.g.) social networks, in which case there are relatively few VERY highly connected nodes (i.e. the popular ones), and then many, many nodes with very low connectivity.  Between the few highly connected, and the many sparsely connected, there is a sort of exponential decay in the middle.  This seems to be THE paper that describes randomly generated social networks: Random Graph Models of Social Networks.
Given networkx and the appropriate statistical distribution, you should be able to build the graph of your dreams.  Good luck with your project, and happy coding.

A: There is not enough information given to fully specify the type of graph that you want. Nevertheless, since graphs are usually abstractions of some physical structure, a common request for a random graph is one that is scale-free. These graphs have the property that the degree distribution follows a power law asymptotically. Population dynamics, Facebook friends, citation networks and internet traffic all have a power law dependence over some domain. The cannonical method for generating scale-free networks is the Barabási–Albert method. Reproduced below (from wikipedia) is an animation of the creation of such a network. It is guaranteed to be connected for any N and generalizations allow you to set the connectivity.

networkx can generate these random graphs with ease:
import networkx

node_number = 20
initial_nodes = 2
G = networkx.barabasi_albert_graph(node_number, initial_nodes)

A: Problem 1:
First create a random spaning tree which connects all the nodes together and then add other edges.
Problem 2:
Create a list of all (i,j) for 1 ≤ i < j ≤ n, shuffle the list and take the first k edges. Your graph will then have n vertices and k±n edges.

A: (1) This one is easy - just create a tree first, and only after the connectivity is assured - start adding more edges.
That can be done easily, by iteratively increasing a set of connected vertices.
Pseudo code:
source <- select random vertex
set <- {source}
while set != V:
   chose a random vertex v from set, and u from V\set
   add (v,u),(u,v) as an edge
   add u to set

(2)
I'd use normal distribution to chose the number of edges per node. Each node will get a different random variable - and thus will have different number of nodes.

*

*I think it is a good approach since things tend to be normally
distributed in real life (due to central limit theorem).

*You can control the connectivity by modifying the mean and variance
of the random variables which are used to determine the number of
edges per vertex.

*You could also use any other distribution to chose the number of
edges per node, but I believe normal distribution fits best.


text:
Q: Placing footer at the bottom I am trying to place my footer at the bottom of the page, not sticky. I set the bottom to 0px but when the page is too long, my footer stays on the top rather than being at the bottom of the page. Also my footer keeps on sticking with my logo instead of being at the bottom of the page. What should I do to fix this problem?
Heres an example

CSS
.logo {
    display: block;
    z-index: 20;
    height: 200px;
    margin-left: auto;
    margin-right: auto;
    margin-top: 100px;
}

footer {
    width: 100%;
    background: rgba(0,0,0,0.6);
    bottom: 0;
}

HTML

Follow Us On Social Media!

Appreciate your help!

A: Add position relative property to html tag and position absolute to footer as shown below and footer will be always at the bottom of the page content.

html {
  min-height:100%;
  position:relative;
}

.logo {
    display: block;
    z-index: 20;
    height: 200px;
    margin-left: auto;
    margin-right: auto;
    margin-top: 100px;
}

.footer {
    width: 100%;
    background: rgba(0,0,0,0.6);
    position:absolute;
    bottom: 0;
}

Check this Jsfiddle for reference


text:
Q: Java Transaction Manager I am started with doing some searches for a transaction manager which could be used in JAVA, I stumbled upon JTA and hibernate as well as JOTM, however - when I search after Java Transaction ... well I mainly see results from JTA - which seems to be the most dominant transaction manager, do you guys now any other Transaction Managers?

A: JTA is a standard API for transaction management in Java. There are many implementations of this API (basically, each Java EE server has its own implementation, and there are other ones, like JOTM, Bitronix, Atomikos for example).
Having a standard API allows developing a transactional application which is portable across transaction managers/application servers. A transaction manager which would not respect this API would shoot itself in the foot, because nobody would use it.
See Atomikos vs JOTM vs Bitronix vs?

A: When selecting any technology, always go for what has been out in the public for long and is extremely popular. That, and what has a lot of support out there. That is hibernate as far as persistence is concerned. JTA is simply Java Transaction API. There are a number of implementations of it. Popular opensource ones are:
JBossTS
Atomikos TransactionsEssentials
Bitronix JTA
Hibernate plays well with all popular JTA's. I too was hesitant of hibernate at first but it's well worth the effort of setting up and learning. What JTA you wish to use depends on a number of factors. I would concentrate on:

*

*What best suits your needs. This means it really depends on the type of project you are doing and your experience in JTA.

*Are you using a Application Server? does it provide an implementation of JTA?

*What has the best documentation for you needs.

Hope this helps.


text:
Q: Error_csrf in edit user form when call Ajax function in ion_auth I have error_csrf in edit user form when call function Ajax drop down for Country State & City.
I have the same error with:
$config['csrf_protection'] = FALSE;

And
$config['csrf_protection'] = TRUE;
$config['csrf_token_name'] = 'csrf_test_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = TRUE;
$config['csrf_exclude_uris'] = array('dashboard/get_city/.*+','dashboard/get_city/[0-9]+');

When i submit the form of edit user i have this error "This form post did not pass our security checks." but only when i change drop-down of country who it call an Ajax function {dashboard/get_city/[0-9]+} to update a drop-down of list of city,
and when i don't change de drop-down of country and they are not a call to this Ajax function, the submit form is OK, and the user information are update
Thank you for your help.

A: That is csrf protection by ion auth, you just remove the line like this :
// do we have a valid request?
if ($this->_valid_csrf_nonce() === FALSE)
{
    show_error($this->lang->line('error_csrf'));
}

And just leave built-in Codeigniter CSRF protection to true :
$config['csrf_protection'] = TRUE;


text:
Q: Why can't I do a $scope update within a jQuery scope? I'm using typeahead to get some suggestions on an input text, this is inside a div controlled by an Angular controller.
The code for the suggestion tasks works with a jQuery plugin, so when I select, something I'm trying to assign a value to $scope, however this is NEVER happening.
I already tried getting the scope of the element with var scope = angular.element($("#providersSearchInput").scope() and then assign it as suggested here but it didn't work.
This is what I'm trying:

    <input type="text" id="providersSearchInput" data-provide="typeahead" class="form-control input-md" placeholder="Buscar proovedores">
    {{currentProvider}}

The controller looks like this:
tv3App.controller('ProvidersController', function($scope, $rootScope, $http, $timeout) {

  var resultsCache = [];

  $("#providersSearchInput").typeahead({
    source:     function (query, process) {
                  return $.get("/search/providers/?query=" + query, function (results) {
                    resultsCache = results;
                    return process(results);
                  },'json');
                },
    matcher:    function (item) {
                  var name = item.name.toLowerCase();
                  var email = item.email.toLowerCase();
                  var contact_name = item.contact_name.toLowerCase();
                  //console.log(name);
                  var q = this.query.toLowerCase();
                  return (name.indexOf(q) != -1 || email.indexOf(q) != -1 || contact_name.indexOf(q) != -1);
                },
    scrollHeight: 20,
    highlighter: function (itemName) {
      var selected = _.find(resultsCache,{name:itemName});
      var div = $('

');
      var name = $('').html('Empresa:  ' + selected.name);
      var contact = $('').html('  Contacto:  ' + selected.contact_name);
      var email = $('').html('  e-mail: ' + selected.email);

      return $(div).append(name).append(contact).append(email).html();
    },
    minLength:  3,
    items:      15,
    afterSelect: function (item) {
      console.log(item);
      $scope.$emit('providerSelected',item);
    }
  });

  $scope.$on('providerSelected', function (event,provider) {
    console.log(provider);
    $scope.currentProvider = provider;
    $scope.$apply();
  });

});

Edit
I tried this to check any changes:
  $scope.$watch('currentProvider',function (newValue,oldValue) {
    console.log(oldValue);
    console.log(newValue);
  });

So when selecting something it actually triggers and $scope.currentProvider seems to be updated but its never getting rendered at view ...

A: get https://angular-ui.github.io/bootstrap/
once you do, in your code make sure
angular.module('myModule', ['ui.bootstrap']);

and for typeahead have
<input type="text" ng-model="currentProvider" typeahead="provider for provider in getProviders($viewValue) | limitTo:8" class="form-control">

In your controller make sure you have
$scope.getProviders = function(val){
    return $http.get('/search/providers/?query=' + val).then(function(response){
        return response.data;
    })
}

This should do the trick although I haven't tested


text:
Q: How can 2 separated web applications can share a second level cache with Hibernate? I have 2 web applications.
I want it to access to the same shared database with Hibernate and i want to use a second level cache in each. But i want the second web application to be able to see the first web application's modifications.
I am not sure to have understood but is Hazelcast a solution for my need ?
Will i be able to manage transactions as before with Spring with that solution?
Thank you.

A: I think you are making this more complicated than it needs to be. Just set up both web apps to  pull in data using a select statement, and whenever you modify data (using an update) on one of the page, do a post back.
This way no matter which page makes a change, the page posts back and when the other page loads the change is already there. This should also work if you are using ajax to avoid post backs.

A: Just Do It. Any change that an application makes to a database should be visible to any other application that reads that database. Once a change is committed, it should be on the hard drive, and anybody else who reads the database from the hard drive should see it.

A: Why do you think you can't have two separate session factories? This won't cause any problem, except if you're using a non-clustered second-level cache to store read-write entities.

A:
So i cannot use two separated Hibernate Session Factories.

Why not? Except you have set the flush mode to MANUAL, there should be no problem. Typical setting is COMMIT or AUTO.
Any further problems can occur using a second level cache. Avoid this if your app server has no JTA environment.
PS: The hibernate settings can be configured by spring, but it can be done any other way.


text:
Q: Spliting string to array by constant number I'v been trying to split string to array of components by number, but have no idea how to do it. I know that each components lenght is 9 except the last one. But there is no separation between them. Maybe anyone would know how could i make this split possible?
string : E44000000R33000444V33441
And i'd like to get array with: E44000000 R33000444 V33441
in past I'v used this method, but i guess there should be a way to separate by constant number. Any ideas
NSArray *myWords = [message componentsSeparatedByString:@";"];

A: Please try the below code.
NSString *stringTest = @"E44000000R33000444V33441323";
NSMutableArray *arrayTest = [NSMutableArray array];
while([stringTest length] > 8) {
    [arrayTest addObject:[NSString stringWithString:[stringTest substringToIndex:9]]];
    stringTest = [stringTest substringFromIndex:9];
}
NSLog(@"arrayTest - %@", arrayTest);

A: Try this one..
NSString *mainString=@"E44000000R33000444V";
NSMutableArray *brokenString=[NSMutableArray new];

int start=0;
for (; start<mainString.length-9; start+=9) {
     [brokenString addObject:[mainString substringWithRange:NSMakeRange(start, 9)]];
}
[brokenString addObject:[mainString substringFromIndex:start]];
NSLog(@"->%@",brokenString);

Output is :
->(
    E44000000,
    R33000444,
    V
)

A: I investigated the NSString, and i didn't found any function like that. But you can create a category of NSString and put this function in that category and you can use as a NSString instance method.
- (NSArray *) componentSaparetedByLength:(NSUInteger) length{
        NSMutableArray *array = [NSMutableArray new];
        NSRange range = NSMakeRange(0, length);
        NSString *subString = nil;
        while (range.location + range.length <= self.length) {
            subString = [self substringWithRange:range];
            [array addObject:subString];
            //Edit
            range.location = range.length + range.location;
            //Edit
            range.length = length;
        }

        if(range.location<self.length){
            subString = [self substringFromIndex:range.location];
            [array addObject:subString];
        }
        return array;
}

A: You can get the substring upto the characters which you want in a loop(string length) & pass the next index for getting the next substring. After getting each substring you can add it to the array.
Used SubstringToIndex & SubstringFromIndex functions to get the substring.

A: Also not an requirement here, I want to propose a solution that is capable of handling characters from more sophisticated script systems, like surrogate pairs, base characters plus combining marks, Hangul jamo, and Indic consonant clusters.
@interface NSString (Split)
-(NSArray *)arrayBySplittingWithMaximumSize:(NSUInteger)size
                                     options:(NSStringEnumerationOptions) option;
@end

@implementation NSString (Split)

-(NSArray *)arrayBySplittingWithMaximumSize:(NSUInteger)size
                                     options:(NSStringEnumerationOptions) option
{
    NSMutableArray *letterArray = [NSMutableArray array];
    [self enumerateSubstringsInRange:NSMakeRange(0, [self length])
                                options:(option)
                             usingBlock:^(NSString *substring,
                                          NSRange substringRange,
                                          NSRange enclosingRange,
                                          BOOL *stop) {
                                 [letterArray addObject:substring];
                             }];

    NSMutableArray *array = [NSMutableArray array];
    [letterArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if (idx%size == 0) {
            [array addObject: [NSMutableString stringWithCapacity:size]];
        }
        NSMutableString *string = [array objectAtIndex:[array count]-1];
        [string appendString:obj];

    }];

    return array;
}

@end

usage
NSArray *array = [@"E44000000R33000444V33441" arraysBySplittingWithMaximumSize:9
                                                                       options:NSStringEnumerationByComposedCharacterSequences];

results in:
(
    E44000000,
    R33000444,
    V33441
)


text:
Q: WP common.phar no such file I run wp plugin on my localhost, it uses Common.phar file in config, and it returns the error: Warning: require_once(/usr/share/php/Log.php): failed to open stream: No such file or directory in...
But on my localhost (used Apache), there is no such path. How to activate and run a plugin?

A: If that's the only problem, you can create the path and file manually. But I guess you can also provide Wordpress an option to log things into another file


text:
Q: What does following hql query mean order by
   (case when CAR.DRIVER is null then 1 else 0 end),
   CAR.DRIVER, CAR.NAME

A: This query sorts looking first if the car has a driver. In case that the car has a driver, the query returns 0. This means that the cars that have a driver will appear first on the results.
After that, it's a normal sort using the car's driver and the car's name.


text:
Q: How to update a list box by an asynchronous call? I have developed a windows forms c# application, i just want update items in a Listbox in the main form by spin offing another thread without blocking the GUI form.
Since threads cannot access form entities like listbox, i thought of using delegates.
Following code in the below shows how i used a delegate to do that task, but it blocks the GUI form. so i just want to convert it to an asynchronous delegate which updates list box without blocking the GUI Form
delegate declaration
 delegate void monitoringServiceDel();

calling the delegate
new monitoringServiceDel(monitoringService).BeginInvoke(null, null);

delegate method implementation
private void monitoringService()
{
        this.listEvents.Invoke(new MethodInvoker(delegate()
        {
            int i = 0 ;
            while (i<50)
            {

                listEvents.Items.Add("count :" + count++);
                Thread.Sleep(1000);
                i ++;
            }

        }));

}

A: For Win Forms you'll need to use the Control's Invoke method:

Executes the specified delegate on the thread that owns the control's
  underlying window handle

The basic scenario is:

*

*Do the heavy lifting work with a BackgroundWorker to retrieve all of your items on a non UI blocking thread.

*On the BackgroundWorker.RunWorkerCompleted Event, use the Control's Invoke method to add the items to the Control (ListBox in your case).

Something along the lines of:
var bw = new BackgroundWorker();
bw.DoWork += (sender, args) => MethodToDoWork;
bw.RunWorkerCompleted += (sender, args) => MethodToUpdateControl;
bw.RunWorkerAsync();

This should get you going in the right direction.
Edit: working sample
public List<string> MyList { get; set; }

private void button1_Click( object sender, EventArgs e )
{
    MyList = new List<string>();

    var bw = new BackgroundWorker();
    bw.DoWork += ( o, args ) => MethodToDoWork();
    bw.RunWorkerCompleted += ( o, args ) => MethodToUpdateControl();
    bw.RunWorkerAsync();
}

private void MethodToDoWork()
{
    for( int i = 0; i < 10; i++ )
    {
        MyList.Add( string.Format( "item {0}", i ) );
        System.Threading.Thread.Sleep( 100 );
    }
}

private void MethodToUpdateControl()
{
    // since the BackgroundWorker is designed to use
    // the form's UI thread on the RunWorkerCompleted
    // event, you should just be able to add the items
    // to the list box:
    listBox1.Items.AddRange( MyList.ToArray() );

    // the above should not block the UI, if it does
    // due to some other code, then use the ListBox's
    // Invoke method:
    // listBox1.Invoke( new Action( () => listBox1.Items.AddRange( MyList.ToArray() ) ) );
}

A: If you are modifying a UI element, then you are going to HAVE to block the UI thread. If the items come in bursts or require processing between adding each one, then you might want to think about running the processing behind the scenes (via a backgroundworker or a Task). But, if you are just taking data and populating the list, then you are required to use the UI thread.

A: The easiest solution would be to use the BackgroundWorker control, combined with two Panels. The idea is to have one panel on the foreground Visible when the form loads, and have an ImageBox inside of it that plays a simple loading gif. The ListBox will be inside the other panel that won't be visible by default and will be right behind the first panel.
Once the form is loaded, start your BackgroundWorker and accomplish whatever Data retrieving or updating that you have to do and once the Task is complete, set the data inside your ListBox and simply bring the ListBox panel and make it visible.
That way you'll have a Semi Asynchronous loading of your ListBox, while it's not updated after every item being added. You can use this technique anytime you want, not simply on form load!
Here is a code example:
namespace AsyncForm
{
    public partial class Form1 : Form
    {

        private List<String> collectionItems = new List<String>();

        public Form1()
        {
            InitializeComponent();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            for (int i = 0; i < 20; i++)
            {
                ((List<String>)e.Argument).Add("Something " + i);
                System.Threading.Thread.Sleep(200);
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            listBox1.Items.AddRange(collectionItems.ToArray());
            listBox1.Visible = true;
            pictureBox1.Visible = false;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            backgroundWorker1.RunWorkerAsync(collectionItems);
        }
    }
}

A: You should separate function to update UI and long-time process.
To handle UI logic..
    private void UpdateUI(string item)
    {
        if (Thread.CurrentThread.IsBackground)
        {
            listEvents.Dispatcher.Invoke(new Action(() => //dispatch to UI Thread
            {
                listEvents.Items.Add(item);
            }));
        }
        else
        {
            listEvents.Items.Add(item);
        }
    }

To do asynchronous process using TaskParallel
    private void Dowork()
    {
        Task task = Task.Factory.StartNew(() =>
        {
            int i = 0;
            while (i < 10)
            {
                Thread.Sleep(1000);
                UpdateUI(i.ToString());
                i++;
            }
        });
    }


text:
Q: Skull removal from grey matter MRI i'm working on brain images (nifti). I segmented the brain with SPM12. So the segmentation went fine but for some (a lot) of the subjects, i get this:

It's a 3D image (T1 MRI) from "ADNI" database.
Like you can see there are still pieces of the skull. I need to remove them. can you tell me the steps to accomplish that? A code/algorithm using matlab or R?
Thank you!


text:
Q: Algorithm to find the furthest point on 2D from other points I have 2D map with points. I need to find a place where I can put a new point and it will be the furthest point from the closest neighbors.
Example, I have a map:
start.x = 0
start.y = 0
end.x = 100
end.y = 100

and array of points List<Point> = {(10,10), (50, 50), (90, 90)}

The result is (0, 100).

So far I found only possible solution using voronoi diagramms:
https://en.wikipedia.org/wiki/Fortune%27s_algorithm
Is there any simpler solution?


text:
Q: Melhor opção a ser usada em tratamento de erros? Estou criando uma biblioteca em PHP para fazer a conexão com o banco de dados e manipular dados do mesmo, mas não sei qual a melhor opção para tratar os erros, se é melhor usar try/catch, echo/return ou die.
Atualmente estou usando vários if/else para percorrer (validar) os dados, em caso de erro exibo um echo com o erro e dou um return false (para não executar o código restante), caso não tenha erro, apenas continuo minhas verificações e no fim retorno true ou array (dependendo da função). Veja um exemplo da minha função mais simples (a deletar):
function deletar($tabela, $where = NULL)
{
    if(!function_exists("conectar"))
    {   //falta include de conexao.php
        echo "Não há uma conexão ativa com o seu banco de dados!\n
Inclua a página ../conexao.php
";
        return false;
    }
    else
    {
        //conexao feita
        if($tabela)
            $tabela = "DELETE FROM ".$tabela." ";
        else
        {
            echo "
Não foi indicada nenhum tabela.
";
            return false;
        }

        $where = minwhere($where);

        echo $sql = $tabela.$where;

        if($conn = conectar())
        {
            if($result = $conn->query($sql))
            {
                $stmt = $conn->prepare( $sql );
                if($result = $stmt->execute())
                        echo "
Deletado!
";
                else
                    echo "
Query inválida!
";

                $conn = null;
                return true;
            }
            else
            {
                echo "
Query inválida!
";
                return false;
            }
        }
        else
        {
            echo "
Não foi possível conectar-se ao banco de dados!
\nVerifique as variáveis do arquivo ../conexao.php";
            return false;
        }
    }
};

Segue o restante da biblioteca (para se alguém quiser analisar outros funções).
O que pode melhorar no tratamento de erros? O modo que estou fazendo é uma alternativa válida ou um código ruim?

A: Basicamente está certo, só poderia ser mais organizado. Eu poderia organizar mais ainda do que fiz abaixo, mas fugiria do estilo que está sendo feito.
Esse monte de echo é sempre uma forma rasa de tratar o erro. Em aplicações sérias, o tratamento seria feito de forma totalmente diferente, jamais jogaria um texto de qualquer jeito na página. Mas pra isso teria que reestruturar toda a aplicação, não só esse trecho. Eu até entendo que a maioria das pessoas fazem assim, mas é o jeito "porco" de fazer.
Sinceramente, por ser uma biblioteca, achei um código horroroso. Parece código de quem está iniciando em programação. Eu não seguiria ela para aprender.
function deletar($tabela, $where = NULL) {
    if(!function_exists("conectar")) {
        echo "Não há uma conexão ativa com o seu banco de dados!\n
Inclua a página ../conexao.php
";
        return false;
    }
    if(!$tabela) {
        echo "
Não foi indicada nenhum tabela.
";
        return false;
    }
    $tabela = "DELETE FROM ".$tabela." ";
    $where = minwhere($where);
    echo $sql = $tabela . $where;
    if(!($conn = conectar())) {
        echo "
Não foi possível conectar-se ao banco de dados!
\nVerifique as variáveis do arquivo ../conexao.php";
        return false;
    }
    if($result = $conn->query($sql)) {
        $stmt = $conn->prepare( $sql );
        echo ($result = $stmt->execute()) ? "
Deletado!
" : "
Query inválida!
";
        $conn = null; //isto provavelmente é um erro
        return true;
    }
    echo "
Query inválida!
";
    return false;
}

Coloquei no GitHub para referência futura.
Trato do assunto em outra pergunta.

A: Solução utilizando try catch
try {

    if(!function_exists("conectar")) {
        throw new Exception( "Não há uma conexão ativa com o seu banco de dados!\n
Inclua a página ../conexao.php
" );
    }
    if(!$tabela) {
        throw new Exception( "
Não foi indicada nenhum tabela.
" );
    }

    $tabela = "DELETE FROM ".$tabela." ";
    $where = minwhere($where);
    echo $sql = $tabela . $where

    if(!($conn = conectar())) {
        throw new Exception( "
Não foi possível conectar-se ao banco de dados!
\nVerifique as variáveis do arquivo ../conexao.php" );
    }

    $result = @$conn->query($sql);

    if(!$result) {
        throw new Exception( "
Query inválida!
" );
    }

    $stmt = $conn->prepare( $sql );
    echo ($result = $stmt->execute()) ? "
Deletado!
" : "
Query inválida!
";
    $conn = null; //isto provavelmente é um erro
    return true;

} catch( Exception $e ) {

    echo $e->getMessage();
    return false;
}