text:
Q: DDD One aggregate, two possible data sources I have a scenario where we've decided to pull some functionality in-house which we should have done a long time ago because it's part of our core domain. As part of the transition we will temporarily be working with either an external service to store and retrieve Widgets or our database depending on the type. When interacting with our local database we'll be using optimistic concurrency which will add a version field to our Widget that is not present when interacting with the external service.
What is the canonical domain driven design solution here? What is the best way to abstract this and where should it be implemented? My first instinct was to implement an abstract factory pattern in the application service layer, but one could argue that this could all be abstracted into the repository. In such a way when we pull out the external service consumers won't need to make a change. Since we are using aggregate design and don't have an overly complex use case we don't need to worry about a unit of work or anything like that. Transactional concerns are maintained entirely within the repository.

A: Since the repository is responsible for the storage abstraction I think it would be the repository's responsibility to coordinate with multiple storages as well.
You could implement something similar to:

Now if you must support an expectedVersion you could make it clear in the interface's contract that expectedVersion may not be supported by all implementations and will throw or simply won't be honored.

"There would be a unique constraint on the entity ID + version
number."

That works for concurrency conflicts, but won't prevent non-concurrent lost updates anyway e.g.

*

*Client C1 loads widget W(v1) on screen.

*Client C2 loads widget W(v1) on screen.

*Client C2 make changes and saves (e.g. update description).

*Repository loads W(v1) in memory and saves back W(v2).

*Client C1 make changes and saves (e.g. update description).

*Repository loads W(v2) in memory and saves back W(v3).
In the end the description update by C2 was lost silently. You'd generally solve this problem by sending the expected version along with the command.


text:
Q: Why does my tkinter Listbox keep moving? I've been trying to create a simple questionnaire in tkinter (Python 3) and I'm having a problem where my listbox moves whenever I edit a label underneath it.
To illustrate what I mean, here are two pictures: http://imgur.com/a/4v92O
Can anyone help me understand why the box doesn't stay still?
class Questionnaire(Frame):
# GUI

def __init__(self, master):

    # Initialise

    Frame.__init__(self,master)
    self.grid()
    self.createProgSelect()
    self.createQuestions()

def createProgSelect(self):

    # Degree programme label

    lblProg = Label(self, text='Degree Programme:', font=('MS', 8,'bold'))
    lblProg.grid(row=1, column=0, columnspan=2, sticky=NE)

    # Listbox

    self.listProg.configure(yscrollcommand=scroll.set)
    self.listProg = Listbox(self, height= 3)
    self.listProg.grid(row=1, column=2, columnspan=2, sticky=E)

    # Scrollbar

    scroll = Scrollbar(self, command= self.listProg.yview)
    scroll.grid(row=1, column=4, sticky=W)

    # Listbox items

    for item in ["CS", "CS with", "BIS", "SE", "Joints",""]:
        self.listProg.insert(END, item)

    self.listProg.selection_set(END)

def createQuestions(self):

    # Strongly agree

    lblStrAgr = Label(self, text = 'Strongly \n Agree', font=('MS', 8,'bold'))
    lblStrAgr.grid(row=3, column= 4, rowspan=2)

    # Partly agree

    lblStrAgr = Label(self, text = 'Partly \n Agree', font=('MS', 8,'bold'))
    lblStrAgr.grid(row=3, column= 5, rowspan=2)

    # Partly disagree

    lblStrAgr = Label(self, text = 'Partly \n Disagree', font=('MS', 8,'bold'))
    lblStrAgr.grid(row=3, column= 6, rowspan=2)

    # Strongly disagree

    lblStrAgr = Label(self, text = 'Strongly \n Disagree', font=('MS', 8,'bold'))
    lblStrAgr.grid(row=3, column= 7, rowspan=2)

    self.varQ1 = IntVar()

    # Label for question 1

    Q1Label = Label(self, text='1. Short text')
    Q1Label.grid(row=5, column=0)

    # Radio buttons for question 1

    R1Q1 = Radiobutton(self, variable=self.varQ1, value=4)
    R1Q1.grid(row=5, column= 4)

    R2Q1 = Radiobutton(self, variable= self.varQ1, value=3)
    R2Q1.grid(row=5, column= 5)

    R3Q1 = Radiobutton(self, variable= self.varQ1, value=2)
    R3Q1.grid(row=5, column= 6)

    R4Q1 = Radiobutton(self, variable= self.varQ1, value=1)
    R4Q1.grid(row=5, column= 7)

Sorry for the slightly stupid question.

A: You are creating a grid. A grid implies that all of the items in a particular column are of the same width, and all of the items in a particular row are the same height. If, for example, a given column grows in width, all the columns to the right will naturally move over to make room.
Your listbox is in column 3. Your label is in column 0. When you configure the label to have very wide text it causes column 0 to expand to accommodate the label. This causes all of the following columns to move over.
My guess for a solution is to have your label span three columns (...grid(..., columnspan=3)), though I don't know for certain exactly what you are trying to accomplish.

redpajama_set_name: RedPajamaStackExchange


text:
Q: RuntimeException on plain NavigationDrawer I have an error going on my code. I am trying to build a navigation drawer to jump between fragments of my app. I modified the drawer to suit my need on the XML code. But after that, when i try to test the app, the app is installed but it crashes at launch.
It shows this error :
java.lang.RuntimeException: Unable to start activity ComponentInfo{zeinfederico.example.tasklead/zeinfederico.example.tasklead.MainActivity}: java.lang.NullPointerException: findViewById(R.id.drawer_layout) must not be null
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3782)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3961)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:91)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:149)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:103)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2386)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:213)
        at android.app.ActivityThread.main(ActivityThread.java:8178)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)
     Caused by: java.lang.NullPointerException: findViewById(R.id.drawer_layout) must not be null
        at zeinfederico.example.tasklead.MainActivity.onCreate(MainActivity.kt:32)

I have a very hard time understanding why my drawer_layout could be null as it actually displays the drawer. To be sure, i tried to put a safe call operator. The problem is that the problem then jumps to NavigationView and so on. Often when i have this kind of behavior, i know that there is something downstream that isn't well written. But i couldn't find anything relevant here.
Since last update of android studio, i had a few weird errors. First, my bundle support became incompatible. I detail this issue in this question: Plugin "Android Bundle Support" is incompatible. And then, i got an exception in my android app analyzer. Maybe those issues are correlated with this one i don't know.
I would like to thank you in advance for your help and time on this issue of mine ;)
To help with this here is a copy of my MainActivity Code:

import android.os.Bundle
import android.view.Menu
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.snackbar.Snackbar
import com.google.android.material.navigation.NavigationView
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import androidx.drawerlayout.widget.DrawerLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar

class MainActivity : AppCompatActivity() {

    private lateinit var appBarConfiguration: AppBarConfiguration

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.content_main)
        val toolbar: Toolbar? = findViewById(R.id.toolbar)
        setSupportActionBar(toolbar)

//        val fab: FloatingActionButton = findViewById(R.id.fab)
//        fab.setOnClickListener { view ->
//            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
//                    .setAction("Action", null).show()
//        }
        val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
        val navView: NavigationView = findViewById(R.id.nav_view)
        val navController = findNavController(R.id.nav_host_fragment)
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        appBarConfiguration = AppBarConfiguration(setOf(
                R.id.nav_profile, R.id.nav_premium, R.id.nav_schedule, R.id.nav_schedule, R.id.nav_tutorial,
        R.id.nav_about, R.id.nav_settings, R.id.nav_procrastination), drawerLayout)
        setupActionBarWithNavController(navController, appBarConfiguration)
        navView.setupWithNavController(navController)
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
        menuInflater.inflate(R.menu.main, menu)
        return true
    }

    override fun onSupportNavigateUp(): Boolean {
        val navController = findNavController(R.id.nav_host_fragment)
        return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
    }
} ```

Here is content_main.xml:

    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/app_bar_main">

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/mobile_navigation" />
</androidx.constraintlayout.widget.ConstraintLayout>


text:
Q: Center text and image I am trying to center a block of text within a page and put a horizontally and vertically centered image inside the block of text. I don't want to use background-image.
This is what I got, but is not working at all.

        This is my Text. Blah Blah Blah Blah Blah Blah

        Blah Blah Blah Blah Blah Blah

        Retrieved from:

        Blah Blah Blah Blah Blah Blah

        Blah Blah Blah Blah Blah Blah

A: position: relative;
instead of absolute
http://codepen.io/anon/pen/hsBux

 This is my Text. Blah Blah Blah Blah Blah Blah

    Blah Blah Blah Blah Blah Blah

    Retrieved from:

    Blah Blah Blah Blah Blah Blah

    Blah Blah Blah Blah Blah Blah

A: I've read a article about this. To perfectly align the blocks use:
.Center-Container {
  position: relative;
}

.Absolute-Center {
  margin: auto;
  position: absolute;
  top: 0; left: 0; bottom: 0; right: 0;
}

these css styles are the key ! check it out here:

div {
  font-family: Times;
  font-size: 12pt;
  width: 400px;
  height: 200px;
  z-index: 20;
  margin-left: auto;
  margin-right: auto;
  top: 50px;
  background-color: red;
}
p {
  position: relative;
}
img {
  z-index: 1;
  margin: auto;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
}

    B lah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah
    Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah

You can read about this in here

http://www.smashingmagazine.com/2013/08/09/absolute-horizontal-vertical-centering-css/
EDIT
The img tag is now IN the p tag. you can check here Should I put paragraph tags around images?
if thats a good idea.


text:
Q: Does the time.sleep() method not make my widget come up? I'm trying to make a button, that when you press the button "Send", it will show for 2 seconds the words "Your message has been sent".
When I start the program, I press "Send", but it doesn't show anything. I think its something to do with the "time.sleep()" method. Can someone tell me whats wrong here?
class Application(Frame):
def __init__(self, master):
    Frame.__init__(self, master)
    self.grid()
    self.create_widgets()

def create_widgets(self):
    self.lbl1=Label(self, text="Write your message:")
    self.lbl1.grid(row=0, column=0, columnspan=2, sticky=W)

    self.entry=Entry(self)
    self.entry.grid(row=0, column=2, columnspan=3, sticky=W)

    self.bttn=Button(self, text="Send", command=self.send)
    self.bttn.grid(row=1, column=0, sticky=W)

def send(self):
    self.lbl2=Label(self, text="Your message has been sent")
    self.lbl2.grid(row=2, column=0,  columnspan=2, sticky=W)
    self.disappear()

def disappear(self):
    start=time.time()
    time.sleep(2)
    self.lbl2.grid_remove()

A: Is this a Tkinter app? You'd probably be better off using something like
root.after(2000, disappear)

To invoke your disappear function after 2 seconds.


text:
Q: PHP CURL Req. Json Format And Using Variables How to use variable on postfields json type on php ?
I set deger variable  123 but curl don't send this data please help me
<?php
$deger=123;
$curl = curl_init();

curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://serviceurl',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS =>'{
    "iprocessnumber": "$deger",
    "activationStatus": "SUCCESS",
    "code": "100",
    "message": "Test mesajı"
}',
        CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json'
        ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

?>

A: You could use that CURLOPT_POSTFIELDS to be pointed to a JSON encoded array.
$postFields holds the encoded fields.
<?php
$deger=123;
$curl = curl_init();

$postFields= [

        "iprocessnumber"=>$deger,
        "activationStatus"=>"SUCCESS",
        "code"=>"100",
        "message"=>"Test mesajı"
];
curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://serviceurl',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS =>json_encode($postFields),
        CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json'
        ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

?>

Hope this helps.


text:
Q: How to locally fetch JSON without AJAX I'm building a game using HTML5 Canvas and Javascript and I'm using JSON formatted tile maps for my levels. The tiles render correctly in FireFox, but when I use Chrome, the JSON fetching fails with a "Origin null is not allowed by Access-Control-Allow-Origin." I was using jQuery's $.ajax command and all my files are in one directory.
I would use this post's solution, but I can't use the web server solution.
Is there any other way to fetch JSON files to be parsed and read from? Something akin to loading an image just by giving the URL? Or is there some way to quickly convert my JSON files into globally available strings so I can parse it with JSON.parse()?

A: One option which may work for you in Chrome is to invoke the browser with the command line switch --allow-file-access-from-files. This question addresses the issue : Google Chrome --allow-file-access-from-files disabled for Chrome Beta 8
Another possibility is to fetch the JSON data as a script, setting a global variable to the JSON value

A: Why is the local web server not an option? Apache is free, can be installed on anything, and easy to use, IMO.  Also, for Chrome specifically, look into --allow-file-access-from-files
But if nothing else works, maybe you could just add links to the files in script tags, and then append var SomeGlobalObject = ... to the top of each file.  You might even be able to do this dynamically by using JS to append the script tag to head.  But in the end, instead of using AJAX, you can just do JSON.parse(SomeGlobalObject)
In other words, load the files into the global namespace by adding script tags.  Normally this would be considered bad practice, but used ONLY for testing, in the absence of any other options, it may work.


text:
Q: ¿Cómo puedo sacar una variable de un bucle for y utilizarla de forma idependiente? Teniendo este código:
import json

tweets = open ('Tweets.txt')
found = 0
linea = 0
for line in tweets:
    contenido=json.loads(line)
    linea += 1
    if 'text' in contenido:
        found += 1
        print("%3d %4d text=%s" % (found, linea, contenido['text']))

Megustaría extraer la variable contenido (dónde contiene los tweets) para así poder utilizarla en otro bucle con esta variable que muestro a continuación:
sentimientos = open("Sentimientos.txt")
valores = {}
for linea in sentimientos:
    termino, valor = linea.split("\t")
    valores[termino] = int(valor)
print (valores.items() )

Que muestra un dict con el valor de palabras. De tal forma que puedas calcular el valor de cada tweet en función de la suma de los valores de las palabras que contenga cada tweet.
Muchas gracias!

A: Primero construimos una función generadora. Esto es útil cuando se desea tener dos procesos, donde uno genera datos que deben ser procesados por el otro a medida que van siendo generados.
La función recibe el nombre de un archivo con tweets (uno por linea). La función recorre el archivo, produciendo un texto a la vez:
def sig_texto(nombre_archivo):
    """ Función generadora.
        En cada llamada retorna el texto de otro tweet.
    @param nombre_archivo El nombre del archivo de tweets.
    @yield El texto del tweet
    """
    with open (nombre_archivo) as tweets:
        for line in tweets:
            contenido=json.loads(line)
            if 'text' in contenido:
                yield contenido['text']

También necesitamos construir un diccionario con los sentimientos valorizados:
with open("sentimientos.txt") as sentimientos:
    valores = {}
    for linea in sentimientos:
        termino, valor = linea.split("\t")
        valores[termino.lower()] = int(valor)

Tomamos la precaución de reducir a minúscula el texto de los sentimientos.
Tenemos ahora que recorrer los tweets, separando cada texto en palabras, descartando todos los caracteres especiales (.,?-, etc) que puedan traera
pegadas. Eso lo hacemos con una expresión regular y findall().
import re

palabra = re.compile("[\w]+")

Ahora recorremos los tweets valorizando cada palabra. Si el tweet tiene un valor distinto de cero, lo mostramos
for text in sig_texto('Tweets.json'):
    #   Por cada tweet.
    valor_tweet = 0
    #   Recorrer las palabras dentro del tweet
    for termino in palabra.findall(text):
        term = termino.lower()
        if term in valores:
            valor_tweet += valores[term]

    if valor_tweet > 0:
        print(valor_tweet, text)

Comprobación
Ahora, con todo junto, probemos
import json
import re

palabra = re.compile("[\w]+")
def sig_texto(nombre_archivo):
    """ Función generadora.
        En cada llamada retorna el texto de otro tweet.
    @param nombre_archivo El nombre del archivo de tweets.
    @yield El texto del tweet
    """
    with open (nombre_archivo) as tweets:
        for line in tweets:
            contenido=json.loads(line)
            if 'text' in contenido:
                yield contenido['text']

#
#   Cargar el diccionario de sentimientos.
#
with open("sentimientos.txt") as sentimientos:
    valores = {}
    for linea in sentimientos:
        termino, valor = linea.split("\t")
        valores[termino.lower()] = int(valor)

for text in sig_texto('Tweets.json'):
    #   Por cada tweet.
    valor_tweet = 0
    #   Recorrer las palabras dentro del tweet
    for termino in palabra.findall(text):
        term = termino.lower()
        if term in valores:
            valor_tweet += valores[term]

    if valor_tweet > 0:
        print(valor_tweet, text)

con este archivo de sentimientos:
love    1
amor    1
mariage 1
ugly    -1
happy   1
sincero 1

produce:
1 RT @byunghns:  I LOVE #틴탑 SO MUCH #쉽지않아 IS GOING TO BE SO GOOD
2 RT @Positivamos: tudo o que eu quero é um amor sincero.
1 RT @GossipRoomOff: Si Nathalie sait pertinemment que son couple ne va pas durer, alors pourquoi accepter la demande en mariage de Vivian ? …
2 RT @Positivamos: tudo o que eu quero é um amor sincero.
2 RT @Positivamos: tudo o que eu quero é um amor sincero.
2 RT @Positivamos: tudo o que eu quero é um amor sincero.
2 RT @Positivamos: tudo o que eu quero é um amor sincero.
2 RT @Positivamos: tudo o que eu quero é um amor sincero.
1 RT @Nashgrier: Happy Birthday to one of my best friends @jackgilinsky Can't wait till you're out in LA! Have a good one!
2 RT @Positivamos: tudo o que eu quero é um amor sincero.
2 RT @Positivamos: tudo o que eu quero é um amor sincero.
2 RT @Positivamos: tudo o que eu quero é um amor sincero.
2 RT @Positivamos: tudo o que eu quero é um amor sincero.
2 RT @Positivamos: tudo o que eu quero é um amor sincero.
2 RT @Positivamos: tudo o que eu quero é um amor sincero.
2 RT @Positivamos: tudo o que eu quero é um amor sincero.
2 RT @Positivamos: tudo o que eu quero é um amor sincero.
1 I thought I would be happy by now
1 RT @JeremiahTaylorr: happy birthday @MeghanNally ❤❤ imysm i found this in my dropbox http://t.co/NEFZJVWs6I
1 Happy Birthday to Robbie , @arsenalfantv you offer excellent insight & coverage on The Mighty Arsenal hope you continue to expand & Innovate
2 RT @Nashgrier: Happy birthday @tfionash I love you soooo much! Thank you for everything, you have no idea how much you mean to me. Hope it'…


text:
Q: SIGINT ignored in google pubsub_v1/python from google.cloud import pubsub_v1

def run():
  # created full_* vars here...

  future = subscriber.subscribe(full_subscription, print_and_ack_message)

  try:
    future.result()
  except KeyboardInterrupt: # this doesn't work for some reason...
    logging.info("Subscription terminated...")
    future.cancel()
  except BaseException as exc:
    logging.info("Other %s", type(exc))

if __name__ == '__main__':
  run()

The above code cannot be interrupted on macOS, zsh, iTerm and pyenv-virtualenv with python 2.7.15, for some reason?
CTRL+C fails from the terminal with this code; nothing happens, only ^C is visible in the output and it does neither terminate nor print anything. What is wrong?
I'm following the docs

A: You don't need to use the result method here:

The subscriber is non-blocking, so we must keep the main thread from exiting to allow it to process messages in the background.

def run():
    future = subscriber.subscribe(full_subscription, print_and_ack_message)
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        future.cancel()


text:
Q: Оплата на сайте Задача такая: необходимо повесить на сайт возможность оплаты картой. После выполнения транзакции необходимо узнать какая сумма была переведена и какие-нибудь дополнительные параметры: например последние 4 цифры карты, или email который был указан при оплате или хоть что-нибудь... И вывести данные на страничке.
Есть удобное решение которое делается за 2 минуты через яндекс деньги. Но там идет просто переадресация на сервис яндекса где все платиться, а возможности получить сколько и кем было переведено я не нашел.
Подскажите???
Добавлю:
Поясню еще чего хочу добиться: вешаю форму на страницу сайта с оплатой от Яндекса, форма содержит одно поле для ввода суммы и кнопка оплатить, при нажатии на кнопку идет редирект на сервис Яндекса - там вводится вся необходимая информация (ФИО, мэил, адрес плательшика, данные карты. Происходит транзакция и вывод ее результата-все это на стороне яндекса, дальше Яндекс показывает кнопку "вернуться в магазин" при нажатии на которую идет редирект на мой сайт). А мне собственно нужно чтобы когда он вернулся на мой сайт я мог показать ему на страничке что он молодец и перевел 100 рублей. Поздравляю

A: Почитайте документацию к любому платежному сервису. Почти все из них при настройке предлагают вам указать некий callback_url это адрес, на который платежная система выполнит запрос после успешного выполнения платежа. Туда же она отправит и параметры. Ни одна платежная система просто так не даст вам выдергивать из себя данные, которые вы хотите получить по другому(во всяком случае более простому) сценарию из-за банальнейших соображений безопасности. Я думаю, вы и сами бы не хотели, что бы иной вариант был возможен.

A: Это называется бухгалтерский учет, и работа с персональными данными (не сарказм). Это действительно важная информация. Информация о платеже у вас в заказе (кто, сколько), информация о статусе в "callback" и в вашем банке.
Информация о кредитной карте?
Это похоже на фишинг.


text:
Q: How to fetch value from JSON array I have a JSON array like below . I need to fetch the value of  all "name " elements in it and concatenate them to a single string.  How can i do that?
Please note that "name " is a child/element of "modifiers" and modifiers is a child/element of "_embedded" and each "modifiers' can be either empty[] or can contain multiple objects each object having "embedded" ,"id", "name" within it.
{
"items": [{
    "_embedded": {
        "modifiers": [{
            "_embedded": {
                "modifiers": [{

                    "_embedded": {
                        "modifiers": []
                    },
                    "id": "3145738",
                    "name": "ABCD"
                }]
            },
            "id": "312121738",
            "name": "EFGH"
        }]
    }
}]
}

A: A quick way to do this is to stingify the object and use positive look behind to get the names :

const obj = {
  "items": [{
    "_embedded": {
      "modifiers": [{
        "_embedded": {
          "modifiers": [{

            "_embedded": {
              "modifiers": []
            },
            "id": "3145738",
            "name": "ABCD"
          }]
        },
        "id": "312121738",
        "name": "EFGH"
      }]
    }
  }]
}

const result = JSON.stringify(obj).match(/(?<=name":")\w+/g).join(',');

console.log(result)

A: You can JSON.stringify the json and extract names from it:

const data = {
  items: [{
    _embedded: {
      modifiers: [{
        _embedded: {
          modifiers: [{
            _embedded: {
              modifiers: []
            },
            id: "3145738",
            name: "ABCD"
          }]
        },
        id: "312121738",
        name: "EFGH"
      }]
    }
  }]
};

const res = JSON.stringify(data).match(/"name"\:\"\w+\"/g).map(el => el.slice(8, el.length - 1))
console.log(res)


text:
Q: sh pig command not found I setup a crontab that run a php script regularly. The php script runs a pig script using exec().
However I get this error message:

sh: pig: command not found

How can this be solved?

A: Can you run pig normally, from the command line? If so, run whereis pig to get the full path and use that in the crontab entry. If not, install it (using whatever method/package manager is normal on your OS.

A: Looks like your first issue is not able to find the pig path in the crontab since the error is "sh: pig: command not found". You might have a PATH variable in your local environment which is no longer present in your cron environment, try with absolute path to the pig script in your cron.


text:
Q: Problem on Angle of declination There was a problem in my book that read- A magnet is pointing towards geographic north at a place where the  horizontal component of the Earth's magnetic field is 40 microtesla. Magnetic dipole moment of the bar is 60 Am^2 and the torque acting on it is 1.2 x 10^-3 Nm. What's the declination at this place?
Now, the angle of declination is defined as the angle between the true geographic north-south direction and the north-south line shown by the compass needle. Since the magnet is pointing toward the geographic north shouldn't the angle of declination be zero? The solution of the problem involved equating torque with M x B which gave sin $\theta$ = 0.5 (where $\theta$ is the angle between the vectors M and B). Even if the angle of declination is not zero, how can we be sure that it is 30 degrees? Please explain this with a sketch.

A: In this case we have to assume that the support for magnet keeps it horizontal while allowing it to rotate around a vertical axis.  Since it is not in line with the horizontal component of the earths field, there will be a torque acting on it of: τ = MBsin(θ) which is trying to bring it into alignment. The θ is the angle between the true north and the direction of the horizontal component of the field.


text:
Q: Determining a line integral of $\frac{p'}{p}$ with $p$ being a polynomial Let $p: \mathbb{C} \to \mathbb{C}$ be a polynomial, and $R > 0$ large enough, so that all roots of $p$ lie within $B_R(0)$ (the open ball with radius $R$ around $0$).
I now want to determine:
$$\int_{\partial B_R(0)} \frac{p'(z)}{p(z)} dz$$
So far, I thought of setting $\gamma: [0, 2π] \to \mathbb{C}, t \mapsto R e^{i t}$ (parameterizing the circle with radius $R$), and setting $p(z) = a_n z^n + ... + a_1 z + a_0$.
Now I guess, one could solve this integral "on foot", by substituting $p(z) = a_n z^n + ... + a_1 z + a_0$ and $p'(z) = n a_n z^{n-1} + ... + a_1$ into the formula, and calculating $\int_0^{2π} \frac{p'(\gamma(t))}{p(\gamma(t))} \dot{\gamma(t)}dt$, but that looks like it would become way too complicated. Is there an elegant way (using a theorem or so) of evaluating this integral?

A: A better approach is to start with the complete
factorization of $p$:
$$
  p(z) = a_n(z-z_1)\cdots(z-z_n) \, .
$$
Then
$$
  \frac{p'(z)}{p(z)} = \frac{1}{z-z_1} + \ldots + \frac{1}{z-z_n}
$$
and each integral
$$
 \int_{\partial B_R(0)} \frac{dz}{z-z_j}
$$
can easily be computed with the residue theorem.
Alternatively, you can argue that the value of the integral does
not depend on $R$ (once that $R$ is so large that all roots of $p$ lie within $B_R(0)$). And for $ |z| \to \infty$,
$$
  \frac{p'(z)}{p(z)} = \frac {n}{z} + O(\frac{1}{z^2})
$$


text:
Q: Fetching Initial State in Redux I'm building an application where I need to fetch the initial redux sate from the server before my main component mounts.
In my actions, I used redux-thunk to get the necessary data:
export const getInitialStateSuccess = (state: any): IfetchThemeSuccess => {
    console.log('state', state);
    return {
        type: FETCH_INIT_STATE,
        state
    };
};

// here I fetch the data from the server and call getInitialStateSuccess
// to pass it to redux init state
export const getInitialState = () => {
     return (dispatch: any) => {
         api.getInitState().then((data) => {
              dispatch(getInitialStateSuccess(data));
          });
      };
 }

However, I do not know where I should call getInitialState(). I need to initialize the state of the app before the main component mounts. Do you think it would be a good practice to call this action in componentWillMount? It has to be called only once.
Please let me know if the approach I'm describing above is a good practice or not.
Thanks!

A: You can call it in WillMount but DidMount is preferred. This is because WillMount can be called twice if you have server-side rendering.
Either way, you're going to need a intermediary "loading" screen before hand since the call is asynchronous, and it is going to render before data has loaded.

A: The best place to place your API or server calls is in the componentDidMount() lifecycle.
Note that this will trigger a re-render once your data overrides your initial state.
This will force you to manage your initial state before the componentDidMount() lifecycle. It is common practice to do this in the constructor method.
You can see this for yourself in the React documentation here: https://reactjs.org/docs/react-component.html
"componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. Setting state in this method will trigger a re-rendering."

A: Your initial state will live in a reducer. And on your react component, once you make it connected, you can use the helper method mapStateToProps to access the current state.


text:
Q: Constructor / Destructor calling sequence in inheritance Why order of constructors called in inheritance is reverse than calls to destructors ? Any specific reason ?

A: Yes there is.  The order for constructors is base, derived.  This ensures that the constructor for derived can rely on base being properly initialised while the derived constructor runs.
The order for destructors is derived, base.  This ensures that derived can rely on base still being valid while the derived destructor runs.


text:
Q: What does projectile protection mean? I am enchanting my boots [minecraft Xbox 360] but I always get projectile protection. But I don't know what it means?

A: Directly from the minecraft wiki, as there's not really anything more to add than a basic definition.
Projectile protection:

Includes damage from arrows, ghast/blaze fire charges, etc.

As you might expect, "Projectile protection" does in fact, protect you from projectiles...
It's worth noting that this will NOT protect you if a Ghast projectile explodes near you (That would require "Blast Protection")
In case this is a problem of translation, here's Google's definition of "Projectile":

An object propelled through the air, especially one thrown as a weapon.


text:
Q: How to get new post URL? I'm wondering... how can I get the new post URL in my theme? Is there a built-in function for this?
So, it should return something like http://example.com/wp-admin/post-new.php?post_type=post.
Connor.

A: admin_url('post-new.php');

The admin_url function will handle generating most of the link, you just need to give it the final component. You can pass in GET parameters as well. Just look at the backend URL to see what you need.
admin_url('post-new.php?post_type=page');

Or using add_query_arg as suggested by @Rarst ...
add_query_arg(array('post_type'=>'page'),admin_url('post-new.php'));

It is overkill for simple URLs but useful for dynamic ones.


text:
Q: Serilog printing contextual property I am using Serilog and want to print some information message that contains contextual property.
For example:
var logger = Log.ForContext("FirstName", "Yosi");
logger.Information("Hello {FirstName}")

and this works as expected, but when I add parameter to the log message it self, I get unexpected result.
var logger = Log.ForContext("FirstName", "Yosi");
logger.Information("Hello {FirstName} {LastName}", "Attias")

I expect the result to be:

Hello Yosi Attias

but I get:

Hello Attias {LastName}

Is there a fix for that? am I missing something? or this is a bug?

A: Message templates are only evaluated against the parameters that are passed in to the logging method. Log statements are intended to work consistently regardless of any other configuration/context in the program.
If you want to add additional properties to the logging output, add them to the outputTemplate argument of whatever sink you are configuring:
Log.Logger = new LoggerConfiguration()
    .WriteTo.ColoredConsole(outputTemplate:
    "{Timestamp:HH:mm} [{Level}] ({LastName}) {Message}{NewLine}{Exception}")
    .CreateLogger();

A: use refection to add properties and their values automatically to log them all in Serilog:
public static Task GenericLog(MyClassLog myclassLog, string message=null)
{
    if (string.IsNullOrEmpty(message)) message = nameof(myclassLog);

    var properties = typeof(MyClassLog).GetProperties();

    var propertyEnrichers = new PropertyEnricher[properties.Length];

    for (int i = 0; i < properties.Length; i++)
        propertyEnrichers[i] =
            new PropertyEnricher(
                properties[i].Name,
                properties[i].GetValue(myclassLog)
                );

    var withProps = Log.ForContext(propertyEnrichers);

    withProps.Debug(message);

    return Task.CompletedTask;
}


text:
Q: Curve Fitting Data to a Function containing an Integral I have the following set of data I'm trying to curve fit
import numpy as np

y = [145,145,146,145,145,145,145,144,143,142,140,138,134,129,122,114,106,96,86,76,67,57,48,39,32,24,18,12,8]
x = np.linspace(0, 500*(len(y) - 1), len(y))

I imagine this is a pretty straightforward task but the function I'm curve fitting it to contains the following integral which is making life difficult:
enter image description here
I've tried the following but I understand its far from correct as I'm not sure how to include x in the bounds of the integral:
def integrand(x, a, b, c):
    return a*np.exp(-(x-b)**2/(2*c**2))

def curve(a, b, c):
    res = scipy.integrate.quad(integrand, x, np.inf, [a, b, c])
    return res[0]

vcurve = np.vectorize(curve, excluded=set([1]))

popt, pcov = scipy.optimize.curve_fit(vcurve, displacement, power, p0=[2.0])
print(popt)

Any help would be greatly appreciated. Thanks


text:
Q: Extracting multiple shapefiles by mask I have one shapefile which is divided into multiple villages (polygons). I can see the name of the villages from attribute table of the shapefile. For each village, I want to extract elevation from ASTER DEM image. In other words, I want to extract based on the attribute (ObjectID/Name) of one shapefile.
Is there any efficient way (i.e. coding, model building) to do it? [I am using ArcGIS 10.5.1]

A: As indicated by @FelixIP in the comment, you should use the Zonal Statistics tools in the ArcToolbox and specifically the Zonal Statistics as Table.
Beware, you will not have one elevation, but a statistical summary of the caracteristics of the pixels the village polygon intersects.
You need to have Spatial analyst extension activated to be able to use it. If you don't have SA, you might be interested to look at free tools like QGIS instead of redevelopping a new tool.


text:
Q: Elastic Search - Filter data which match value along with data type I am using ES 5.7 of AWS. There is list of objects stored in elastic search cluster.Each object has one field status which value is integer, but because of one programmatic bug of indexer for some objects status value stored as text instead of integer. I need to filter the objects using bool query for which status is text.
I have used below query to filter the data.
sample data
{
   "took":22,
   "timed_out":false,
   "_shards":{
      "total":16,
      "successful":16,
      "failed":0
   },
   "hits":{
      "total":3208,
      "max_score":1,
      "hits":[
         {
            "_index":"entity-data",
            "_type":"account",
            "_id":"b7b46c",
            "_score":1,
            "_source":{
               "status":"3"
            }
         },
         {
            "_index":"entity-data",
            "_type":"account",
            "_id":"b7b46",
            "_score":1,
            "_source":{
               "status":3
            }
         }
      ]
   }
}

bool query used to filter based on status
{
   "query":{
      "bool":{
         "filter":[
            {
               "term":{
                  "status": "3"
               }
            }
         ]
      }
   }
}

Here "status": "3" and "status": 3 is providing same result.

I need to filter data where "status": "3".
Any suggestion will be helpful. Thanks in advance.

A: You script doesnt work since the mapping of the field would of type long and while doing the search using the script you wrote it only looks at the inverted index which is of type long.
You can use painless script to access the document values and find all the string values. The script checks the datatype of the field status and returns true only for String type's. Hence, it will return all documents containing String values.
PUT t1/doc/1
{
   "status": 3
}

PUT t1/doc/2
{
   "status": "3"
}

GET t1/_search
{
    "query": {
        "bool" : {
            "filter" : {
                "script" : {
                    "script" : {
                        "inline": "if(params._source.status instanceof String) return true;",
                        "lang": "painless"
                     }
                }
            }
        }
    }
}

Output:
{
  "took": 2,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 1,
    "max_score": 0,
    "hits": [
      {
        "_index": "t1",
        "_type": "doc",
        "_id": "2",
        "_score": 0,
        "_source": {
          "status": "3"
        }
      }
    ]
  }
}

Additional Information:
If you want to change all those string values to long, you can reindex into a new index and use script to manipulate the values.
//Create new index
PUT t2

//reindex from t1 to t2 and change string to integer
POST _reindex
{
  "source": {
    "index": "t1"
  },
  "dest": {
    "index": "t2"
  },
  "script": {
    "lang": "painless",
    "inline": "if(ctx._source.status instanceof String){ctx._source.status = Integer.parseInt(ctx._source.status)}"
  }
}


text:
Q: How to plot 2 curves on a histogram in base R? I made this histogram with base R:

Here is the code:
data=read.csv("cholesterol.csv")
newdata=subset(data, data$SEX=="female")
newdata1=subset(data, data$SEX=="male")
hist(newdata$CHOLESTEROL,breaks=10,col=rgb(red = F, green = T, blue = F,
alpha = 0.3), xlim=c(0,350), ylim=c(0,25), xaxs="i", yaxs="i", las=1, main="", xlab="Cholesterol", ylab="Frequentie", border=rgb(red = F, green = T, blue = F, alpha = 0.3))
hist(newdata1$CHOLESTEROL, breaks=10,col=rgb(red = T, green = F, blue = F, alpha = 0.4), border=rgb(red = T, green = F, blue = F, alpha = 0.4), add=T)
legend('topright', c('Female','Male'),fill = rgb(0:1,1:0,0,0.4), bty='n', border = NA)

I now want to plot a curve on this histogram and I want for each group (female and male) a distinct curve.
I tried several commando's (such as lines(density(newdata$CHOLESTEROL), col="red", lty=1, lwd=1)) but none of them resulted in a curve. I also could not find a solution on the internet, so I hope anyone can help me :)

A: Try adding probability=TRUE to the calls to hist.  This will scale the histogram to have an area of 1, the same as the result of density so that they plot nicely together.  Your code above is probably adding the curve, but with the difference in scaling it looks like a horizontal line along the bottom.


text:
Q: jQuery listener for PHP event I have a simple form submission and in my process.php file I check each field for its valitity. If it fails, I'm using key/value pairs in $_SESSION to display an alert message on the login page.
The alert message is displayed on a div (with some bootstrap styling, if that matters) that is set to .hide when the page loads.
Is there a jQuery function or event listener I can use to detect the PHP echo and .toggle the alert box?
Heres my relevant code as it stands:

    <?php
        if (isset($_SESSION['first_name'])) {
        echo $_SESSION['first_name'];
        }

        if (isset($_SESSION['last_name'])) {
        echo $_SESSION['last_name'];
        }

        if (isset($_SESSION['email'])) {
        echo $_SESSION['email'];
        }

        if (isset($_SESSION['passlen'])) {
        echo $_SESSION['passlen'];
        }

        if (isset($_SESSION['passmatch'])) {
        echo $_SESSION['passmatch'];
        }
?>

And:

A: Simplest thing would be to check if #error-box contains any text:
$(document).ready(function(){
    if ($.trim($("#error-box").text()).length < 1) {
        $("#error-box").hide();
    }
}

A: php runs on the server and and javascript runs in the browser, after the php code is executed and translated to html. Rather than hiding/showing with javascript, only insert the error message if there are any errors.
<?php
// validate your form

if ($errors) : ?>

    print your errors

<?php endif; ?>

Then you don't need javascript to hide/show anything.

A: I think you have a wrong approach. As you say you have a simple form i expect you dont use ajax. So by calling your php script you will have a page reload and you can just echo the box if you need.
<?php $fields = array('first_name', 'last_name', 'email', 'passlen', 'passmatch');?>

<?php if ($_SESSION['first_name'] || $_SESSION['last_name'] || $_SESSION['email'] || $_SESSION['passlen'] || $_SESSION['passmatch'] ): ?>

        <?php
            foreach($fields as $_field){
               if (isset($_SESSION[$_field])) {
                 echo $_SESSION[$_field];
               }
            }

    ?>

<?php endif; ?>

Well it could be done better, but it shows what i want to tell!


text:
Q: can an iOS app include a user-space network device driver? I see Mac kernel module development tips and tricks by Apple but does it extend to IOS apps? Is it possible for an IOS app to load a kernel module behaving as a user space network device for iPhone IOS.

A: No. That information is specific to desktop Mac OS; there is no way to load kernel extensions on iOS.

A: The changes to networking in iOS11 may enable what you are asking about, although your question is ambiguous as your goal is not clearly stated.


text:
Q: Can a snowflake stream trigger a task without adding any schedule? I have a stream created in snowflake and a task which moves stream data into another table. I want the task to execute automatically every time there is new data in stream. How to automatically trigger the task when there is new data in stream?

A: Tasks can only triggered on a schedule but you can have them run as often as every minute
If a run takes more than 1 minute, then the next task is delayed until 1 min after the previous task finishes
While it is not "on demand" a task running every minute should suffice for most situations. Of course it means a warehouse constantly running but the same would be true for an on demand service assuming new data arrives all the time. If data is irregular, you can add a stream has data check so the task does not run if there is no data: https://docs.snowflake.com/en/sql-reference/functions/system_stream_has_data.html


text:
Q: Frequency and Volume Relational in Sound In a real life example: Suppose if I change the volume of TV, Computer or, Stereo sound device, would the frequency of sound change as well? In other words, when I lower the volume does it make frequency go lower, higher or, stay constant?

A: The only way loudness and pitch are related is in the details of how your ear operates. For extremely loud sounds, your ear tends to perceive the pitch of those sounds slightly flatter than when they are heard at normal loudness levels.
Another thing to note here is that when sounds are not very loud, the ear loses effectiveness at low frequencies, which then sound "weak in the mix". Many stereo playback systems contain a contour network which automatically boosts the loudness of the bass frequencies whenever the system is running at low loudness levels to make up for this tendency. This too is an effect that is in your ear, not in the physics of sound transmission through air.

A: There is not link between the two.
We define the frequency (for a periodic wave) as the number of occurences of the wave per units of time. The volume, however, is a description of the amplitude of the wave.
That is, of course, for sonic waves.


text:
Q: Do these files need to be pushed to Github? I made a Rails application.
Do i need to push these files to Github?
.browserslistrc

.gitattributes

.rspec

.ruby-version

A: The short answers are "if you want", and "there's no reason not to".
All of these files do something to make it easier to replicate your code base and setup on another machine. None of them contain secrets that shouldn't be shared.

*

*.browserslistrc

The config to share target browsers and Node.js versions between different front-end tools.

*.gitattributes

a simple text file that gives attributes to pathnames.

These attributes affect how the contents stored in the repository are copied to the working tree files when commands such as git switch, git checkout and git merge run. They also affect how Git stores the contents you prepare in the working tree in the repository upon git add and git commit.

*.rspec

Read command line configuration options from files

*.ruby-version

Many Ruby (or Rails) projects will include a simple .ruby-version file, which simply specifies a version number


text:
Q: When to use const keyword for variable vs when to traverse the object I am working on a JavaScript application where I have to access a big object at many places. I am wondering what is the better way to go for it in terms of time and space optimisation.
For example, let's say I have on object (this is just an example, my objects will be much bigger and deeply nested):
family: {
    person: {
        firstName: Sherlock,
        lastName: Holmes,
        age: 22,
        address: {
            building: 221B,
            addressLine1: Baker Street,
            city: London,
        }
    }
}

Now, if I want to access the address here and print it on my webpage, then what is the good approach:
Shall I do this:

{family.person.address.building}

{family.person.address.addressLine1}

{family.person.address.city}

or, I store them in consts and then display here like:
const address = family.person.address
const {
    building, addressLine1, city
} = address

{building}

{addressLine1}

{city}

In the former one, I am not creating new variable but traversing the object in depth each time I have to access something.
In the latter one, I don't have to do that traverse but have created 4 new variables
I feel second one is the fast approach (takes less time) because object is not traversed multiple times but I didn't find any articles supporting it.
Which approach will give me better time or space optimisation in my application?


text:
Q: Wake from sleep Kernel Panic: -- "Could not read LR" -- What is LR? When I try and understand this Kernel Panic Report, But I don't know what LR is. What is LR?  How can I tell if this is a hardware problem or software?
*** Panic Report ***
panic(cpu 1 caller 0xffffff800a79b0d4): launchd exited (signal 9, exit status 0 CS_KILLED)

uuid info:
0x7fff6dc7e000  uuid = <a468d85e-d8d6-3461-8c99-49d3b9acfc63>
0x10e779000 uuid = <48362449-4519-317e-9a8b-7524036de5ea>

Thread 3 crashed

RAX: 0x0000000000000000, RBX: 0x00007fff6dcbe5f8, RCX: 0x000000010e779a00, RDX: 0x000000010e7c17b8
RSP: 0x0000700000080650, RBP: 0x00007000000806d0, RSI: 0x00000000000001b1, RDI: 0x00007fff6dcbe5f8
R8:  0x00007fff94871119, R9:  0x0000700000080a40, R10: 0x000000000015be00, R11: 0x000000010e7b9170
R12: 0x00007fdb8147ddb0, R13: 0x0000000000000000, R14: 0x0000000000000000, R15: 0x000000010e7bf831
RFL: 0x0000000000010246, RIP: 0x00007fff6dc984d0, CS:  0x000000000000002b, SS:  0x0000000000000023

Thread 0: 0xffffff8015913b60
    0x00007fff985c5dcd
    0x0000000000000000

Thread 1: 0xffffff8015ac3000
      Could not read LR from frame at 0x0000700000116d48    <--------------Error

Thread 2: 0xffffff8015c43db0
    0x00007fff985d47b5
    0x0000000000000000

Thread 3: 0xffffff801b40a6d0
    0x00007fff6dc82063
    0x00007fff94871262
    0x000000010e7b9170
    0x000000010e78a4a0
    0x000000010e78eb95
    0x00007fff985c040b
    0x00007fff985d0675
    0x00007fff985c4a83
    0x00007fff985c5200
    0x00007fff985cb707
    0x00007fff985c3d53
    0x00007fff985c3b00
    0x00007fff89dab4de
    0x00007fff89da9341
    0x0000000000000000

Thread 4: 0xffffff8021758920
    0x000000010e7a447f
    0x00007fff985d8324
    0x00007fff985c040b
    0x00007fff985c503b
    0x00007fff985cb707
    0x00007fff985c3d53
    0x00007fff985c3b00
    0x00007fff89dab4de
    0x00007fff89da9341
    0x0000000000000000

Mac OS version: 15F34
Kernel version: Darwin Kernel Version 15.5.0: Tue Apr 19 18:36:36 PDT 2016; root:xnu-3248.50.21~8/RELEASE_X86_64
Kernel UUID: 7E7B0822-D2DE-3B39-A7A5-77B40A668BC6
System model name: MacBookAir5,2 (Mac-2E6FAB96566FE58C)

A: LR is a Link Register.

A link register is a special-purpose register which holds the address to return to when a function call completes.

More info on Wikipedia.
Crash occured on Thread 3 and it's not related to the LR. It's hard to tell what happened since the report is not symbolicated.


text:
Q: Arduino : Check byte array for chars one at a time I communicate with Arduino via Serial using a program that sends a series of bytes.
In order for the Arduino to realize it is receiving a message rather than junk, I have tagged the start of my byte array with the chars 'S' 'T' 'A' 'R' 'T'. After this will eventually follow a series of bytes that will be assigned to internal variables (not yet implemented).
The Arduino must read each byte sequentially and compare it to the byte array and if all are present in the correct order it will continue with the next part of the program, otherwise it will should discard current byte and wait for more bytes to arrive.
I am trying to implement it in the most efficient and readable way rather than using a series of nested if statements.
So far I have got:
byte inByte = 0;
byte handShake[] = {'S','T','A','R','T'};

void setup() {
  Serial.begin(9600);

}

void loop()
{
  while (Serial.available())
{
  for (int x =0; x < sizeof(handShake) ; x++)
    {
    inByte = Serial.read();
    Serial.println(x);
    if (inByte == handShake[x])
     {
        if (x == (sizeof(handShake)-1)) {setArduino();}
      }
       else break;
   }
  }
}

void setArduino () {
  Serial.println("Ready To Set Parameters");
}

This however doesn't seem to get past the second byte and I'm not sure why.

A: Worked it out :
Here is the answer:
byte inByte = 0;
char handShake[] = {'S','T','A','R','T'};

void setup() {
  Serial.begin(9600);

}

void loop()
{
  while (Serial.available())
  {
  for (int x =0; x < sizeof(handShake) ; x++)
    {
    inByte = Serial.read();
    Serial.println(x);
    if (inByte == handShake[x])
      {
       if (x == (sizeof(handShake)-1)) {setArduino();}
       while(!Serial.available()) {delay(1);}
      }
       else {break;}
    }
  }
}

void setArduino () {
  Serial.println("Ready To Set Parameters");
}

This may not be the most efficient way perhaps, but I can't see a problem with it currently.

A: Better answer : This allows the rest of the loop to iterate while waiting for the message to finish and if the full handshake message isn't received the counter will reset.
byte inByte = 0;
char handShake[] = {'S','T','A','R','T'};
int messageIndex = 0;

void setup() {
  Serial.begin(9600);

}

void loop()
{
  while (Serial.available())
  {
    inByte = Serial.read();
    Serial.println(messageIndex);
    if (inByte == handShake[messageIndex])
      {
        messageIndex++;
        if (messageIndex == sizeof(handShake)) {messageIndex = 0; setArduino();}
      }
       else {messageIndex=0;}
  }
// Other code while waiting for message to finish
Serial.println("tick");
}

void setArduino () {
  Serial.println("Ready To Set Parameters");
}

A: You could try to calculate your message. CRC is old and good solution. I use it and it works perfect for me. I am not sure what kind of device are you communicating with.
//define
const uint32_t Polynomial = 0xEDB88320;
const uint16_t NumBytes = 256;
uint8_t data[NumBytes];

/// compute CRC32
uint32_t crc32_bitwise(const void* data, uint16_t length, uint32_t previousCrc32 = 0)
{
  uint32_t crc = ~previousCrc32; // same as previousCrc32 ^ 0xFFFFFFFF
  uint8_t* current = (uint8_t*) data;

  while (length--)
  {
    crc ^= *current++;
    for (uint8_t j = 0; j < 8; j++)
    {
      uint8_t lowestBit = crc & 1;
      crc >>= 1;
      if (lowestBit)
        crc ^= Polynomial;
    }
  }
  return ~crc; // same as crc ^ 0xFFFFFFFF
}
void setup() {
  // put your setup code here, to run once:
}

void loop() {
  // put your main code here, to run repeatedly:
}

when you need to calculate CRC
uint32_t crc = crc32_bitwise(data_bytes, sizeof(data_bytes));
data_bytes is byte array.
Then you can get all settings or message in byte data[x] and calculate CRC. Then you can add CRC to the message and send message byte data[x+sizeof(CRC)]
P.S. Use byte instead of int. For ex. for(byte x =0; x<sizeof(handShake); x++)


text:
Q: building flexible GUI I have a Layout that I want to populate with items consisting of 2 textviews and one button. I do not know before hand how many items that will populate my Layout.
Since I don't know when writing the layout.xml how many items I want to add, thats means that I have to add the items in the java instead of the xml. But I do not like to build GUI in java because it looks ugly.
Does anyone know if I can create an xml file for my item and then add new items to my layout during execution?
I have written some pseudo code to try to demonstrate what I want to accomplish:
MainLayout.xml
//My empty Layout
<Layout myMainLayout >
</RelativeLayout>

Fragment_post.xml
//one post
<TextView/>
<TextView/>
<Button/>

In the code somewhere
setContentView(R.layout.MainLayout);
MyMainLayout.addFragment(R.layout.Fragment_post);

A: You can add your fragment_post.xml wherever you want:
LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout view=(LinearLayout)inflater.inflate(R.layout.yourfragment, null);
yourLayout.addView(view);

Please don't confuse a Fragment with a piece of the GUI. See here for details: http://developer.android.com/guide/components/fragments.html

A: Sure you can do this. Just set an initial empty layout to your activity.
onCreate()
{
setContentView(R.layout.initial_layout);
}

Then get and keep a reference to main layout.
LayoutInflater inflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout mainLayout=(RelativeLayout)inflater.inflate(R.layout.initial_layout, null);

Next, add  new views to your layout as and when you need them.
LinearLayout view=(LinearLayout)inflater.inflate(R.layout.fragment_post, null);
mainLayout.addView(view);

But note that what you refer to as fragments here are not what android refers to as fragments. Learn about actual android fragments here:
http://developer.android.com/guide/components/fragments.html


text:
Q: Type having conversion to Type&& operator I was surprised to see that the following compiles:
struct C {
    operator C&&() {
        std::cerr << "ref'd\n";
        throw std::runtime_error("what is happening?");
    }
};

A type with an operator for its own rvalue-reference conversion.  However, I can't get the operator called using what I thought may do it.  Passing a value to a function taking an rvalue reference fails, and calling std::move on an object doesn't trigger anything.
Why is this code able to compile at all, and is there any way to actually get this function to run?
clang gives warning: conversion function converting 'C' to itself will never be used with or without the reference on the type.

A: void foo(C&&){}
int main(){
  C c;
  foo(c.operator C&&());
}

so, basically useless, but not completely.

A: struct C
{
    operator C()
    {
    }
};

is also allowed and gives the same warning. It's referred to in §12.3.2/1:

A conversion function is never used to convert a (possibly
  cv-qualified) object to the (possibly cv-qualified) same object type
  (or a reference to it), to a (possibly cv-qualified) base class of
  that type (or a reference to it), or to (possibly cv-qualified) void.

In other words, it isn't forbidden, but it simply doesn't do anything. Yakk and Wintermute have already shown examples of member function call syntax, but cppreference shows an example of virtual dispatch as alluded to in footnote 116 (N3337, footnote 118 in N4140):
struct D;
struct B {
    virtual operator D() = 0;
};
struct D : B
{
    operator D() override { return D(); }
};

int main()
{
    D obj;
    D obj2 = obj; // does not call D::operator D()
    B& br = obj;
    D obj3 = br; // calls D::operator D() through virtual dispatch
}


text:
Q: AQjmsFactory issue with Point-to-Point I should connect to an Oracle AQ single consumer Point-to-Point queue by the AQjmsFactory.getConnectionFactory API (as stated by the Oracle documentation) using Spring/Camel frameworks.
The following error stack shows me that it tries to create a topic connection.
Could anybody tell me why?
Thank you so much!
org.springframework.jms.UncategorizedJmsException: Uncategorized exception occurred during JMS processing; nested exception is oracle.jms.AQjmsException: JMS-243: Argomento MY_QUEUE non trovato; nested exception is oracle.jms.AQjmsException: JMS-142: È necessario creare largomento JMS nelle tabelle di coda attivate per più consumatori
    at org.springframework.jms.support.JmsUtils.convertJmsAccessException(JmsUtils.java:316)
    at org.springframework.jms.support.JmsAccessor.convertJmsAccessException(JmsAccessor.java:169)
    at org.springframework.jms.core.JmsTemplate.execute(JmsTemplate.java:487)
    at org.apache.camel.component.jms.JmsConfiguration$CamelJmsTemplate.send(JmsConfiguration.java:469)
    at org.apache.camel.component.jms.JmsProducer.doSend(JmsProducer.java:414)
    at org.apache.camel.component.jms.JmsProducer.processInOnly(JmsProducer.java:368)
    at org.apache.camel.component.jms.JmsProducer.process(JmsProducer.java:154)
    at org.apache.camel.processor.SendProcessor.process(SendProcessor.java:145)
    at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:77)
    at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:542)
    at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:197)
    at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:197)
    at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:97)
    at org.apache.camel.component.dataset.DataSetConsumer.sendMessages(DataSetConsumer.java:89)
    at org.apache.camel.component.dataset.DataSetConsumer$1.run(DataSetConsumer.java:70)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: oracle.jms.AQjmsException: JMS-243: Argomento MY_QUEUE non trovato
    at oracle.jms.AQjmsError.throwEx(AQjmsError.java:374)
    at oracle.jms.AQjmsSession.createTopic(AQjmsSession.java:2723)
    at org.springframework.jms.support.destination.DynamicDestinationResolver.resolveTopic(DynamicDestinationResolver.java:72)
    at org.springframework.jms.support.destination.DynamicDestinationResolver.resolveDestinationName(DynamicDestinationResolver.java:55)
    at org.springframework.jms.support.destination.JmsDestinationAccessor.resolveDestinationName(JmsDestinationAccessor.java:114)
    at org.apache.camel.component.jms.JmsConfiguration$CamelJmsTemplate.access$000(JmsConfiguration.java:458)
    at org.apache.camel.component.jms.JmsConfiguration$CamelJmsTemplate$1.doInJms(JmsConfiguration.java:471)
    at org.springframework.jms.core.JmsTemplate.execute(JmsTemplate.java:484)
    ... 15 common frames omitted
Caused by: oracle.jms.AQjmsException: JMS-142: È necessario creare largomento JMS nelle tabelle di coda attivate per più consumatori
    at oracle.jms.AQjmsError.throwEx(AQjmsError.java:313)
    at oracle.jms.AQjmsSession.getTopic(AQjmsSession.java:5899)
    at oracle.jms.AQjmsSession.createTopic(AQjmsSession.java:2716)
    ... 21 common frames omitted

A: I solved on my own debugging the camel source code (due to an inherited legacy sources): it was an error on ActiveMQ component addressing "oracleaq:topic:MY_QUEUE" in place of "oracleaq:MY_QUEUE".


text:
Q: Sort Order Rows/Cols and the Entries of an Adjacency Matrix I've worked the following code to produce the correct adjacency matrix. However, I would like the rows and columns to align to an alpha or numerical sort of the vertices. For instance, this code produces the TableHeadings A D B C across the top row and down the left-most column. Instead, I would like the TableHeadings to be A B C D across the top row and down the left-most column. The entries need to following that ordering as well. Any advice is most appreciated!!!! Also, can this be done for vertices with numerical names and not letter names?
Clear[edges]
edges = {A <-> D, A <-> B, B <-> D, C <-> C, D <-> A};
g = LayeredGraphPlot[edges, Left,
  VertexShapeFunction -> ({Lighter[LightYellow],
      EdgeForm[Lighter[Blue]], Disk[#, .15], Black,
      Text[Style[#2, 9.5, Black], #1]} &)]
EdgeList[edges] // TableForm
v = VertexList[Graph[edges]];
am = AdjacencyMatrix[Graph[edges]];
TableForm[am, TableHeadings -> {v, v}]

A: order = Ordering[v]

(* {1, 3, 4, 2} *)

TableForm[am2 = (#[[order]] & /@ am)[[order]],
 TableHeadings -> (Sort /@ {v, v})]

A: Why don't you just construct your graph with the desired vertex ordering in the first place?
edges = {"A" <-> "D", "A" <-> "B", "B" <-> "D", "C" <-> "C", "D" <-> "A"};

Provide the explicit vertex list like so:
Graph[{"A", "B", "C", "D"}, edges]

Or like this:
Graph[Sort@VertexList[edges], edges]


text:
Q: Adding transform to an image blurs it in Chrome I have an image with a transform applied to it to :transform: translate(-50%,-50%);
Only in Chrome this causes the image to be blurry.
I've tried different proposed solutions such as setting translateZ(0); filter: blur(0) without any success.
Removing the transform property removes the blurry effect.
Here is the current css for the image :
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    height: auto;
    width: auto;
    max-height: 100%;
    max-width: 100%;
And it looks like this :
And here is the actual image returned from my image service :

Notice that the first image has blurred edges and the original image does not.


text:
Q: State Design pattern and infinite loops with MonoGame I am trying to use state design pattern with my game(MonoGame game).I want to detect collision , so I give cell type and upon it gives me a specific action.But unfortunately this implementation gives infinite loop "Exception.StackOverflow" in player instances.
     abstract class PlayerState
     {
         abstract public void doAction(Player player );
     }

Classes implements PlayerState
    class DeadState:PlayerState
    {
       public override void doAction(Player player)
            {
               player.dead();
               player.setState(this);
            }
     }

     class IncreaseGold: PlayerState
     {
    public override void doAction(Player player)
           {
               player.increaseGold();
               player.setState(this);
           }
     }

Player.cs
      public void setState(PlayerState state) { this.state = state; }
      public PlayerState getState() { return state; }

ActionController.cs
     Player player = new Player();

    public void passCell(int cellType)
    {
        if (cellType == 1)
        {
            new DeadState().doAction(player);
        }
        if (cellType == 2)
        {
            new IncreaseGold().doAction(player);
        }
    }

finally in my Update method on Game1.cs
    protected override void Update(GameTime gameTime)
    {
       player.passCell(cellType);

       base.Update(gameTime);
    }


text:
Q: Input field validation for non-whitespaces word length Maximum 40 How to make an input field to type only a non-whitespaces word of size 40 characters? suggest any directive or any other solution?
Valid input text: "Lorem ipsum dolor sit amet, justo explicari honestatis"
inValid input text: "Lorem ipsum dolor sit amet, Loremipsum      LoremLoremLoremLoremLoremLoremLoremLoremLorem justo"
invalid input contains a word with size 45 characters without any space
i.e: "LoremLoremLoremLoremLoremLoremLoremLoremLorem"

A: You could register a changelistener on the input field and analyze the entire input every time the user typed something. Subtract the number of whitespaces from the length of the input field value and if the result exceeds 40 characters, delete the last character of the input and notify the user.


text:
Q: Python - How to compare two files and output only the different lines in a third file I have searched for similar questions on SO but didn't find anything that worked for me.
I have two large files, they should be the same but one of the files is 60 lines longer than the other. I want to know what these lines are and where I can find them.
I've read that one can use difflib to do this but I can't figure out how to go about it. I always get + and - in the file but I don't want that. I just want to scan through both files and report the uncommon 60 lines into a third file.
I wrote this code but it does not print out the different lines.
f1 = open('file1.txt','r')
f2 = open('file2.txt','r')
f3 = open('file3.txt','w')

diff = set(f1).difference(f2)
same.discard('\n')

for line in same:
    f3.write(line)

A: Well, you could do something like this:
with open('file1.txt') as infile:
    f1 = infile.readlines()

with open('file2.txt') as infile:
    f2 = infile.readlines()

only_in_f1 = [i for i in f1 if i not in f2]
only_in_f2 = [i for i in f2 if i not in f1]

with open('file3.txt', 'w') as outfile:
    if only_in_f1:
        outfile.write('Lines only in file 1:\n')
        for line in only_in_f1:
            outfile.write(line)

    if only_in_f2:
        outfile.write('Lines only in file 2:\n')
        for line in only_in_f2:
            outfile.write(line)

Note: same content in different lines is treated as a difference

A: You can easily solve this using sets.
set1 = set()
with open(file1) as f:
    for line in f:
        set1.add(line.strip())
#Repeat for set 2
with open(diff_file, 'w') as f:
    for line in set2 - set1:
        f.write(line + '\n')


text:
Q: Rails Model-Association Form Question Hey guys, I'm having trouble understanding a Rails construct. I'm using Rails 3 but I doubt this is specific to this version.
I have a model, Goal that has_many :commits and naturally, a Commit model that belongs_to :goal. I created the proper migration so that commits_table.references :goal.
I am actually going through the Rails Getting Started guide, except in that article they use a Post and Comment respectively.
Now that I've described the situation I can express my confusion. On the Goal's show view, I have embedded a form to create a new Commit which is 'attached' to the currently viewed Goal. This works fine and all. However, I am having trouble understanding why we do this
<%= form_for([@goal, @goal.commits.build]) do |f| %>

Shouldn't it be form_for(@commit)? I understand why we want the @goal, to provide some context since the commit is a nested resource. However, in the actual generated source, the form is appropriately named as commit, that is, the fields are named commit_blah. How did Rails know this? I understand that there's this whole system of "trust and magic" and all, but I mean at least at the high level, what from this code hinted to Rails that I wanted a commit?
I looked at the documentation for form_for and it seems like one of the parameters could be the action to take for the form. I imagine that in this case, that's what the @goal.commits.build parameter is for? To designate the action to take? Is this how Rails deduces that I want a commit? Would this also explain why this form is handled by the Commit controller even though this code is in the Goal's view?
Also, why are these parameters passed as an array ([])? In Ruby, will the method still just take it as two separate parameters, or is there a reason why this was passed this way?
Finally, rails generate automatically gave me some error showing code in my other _form.html.erb partials:
<% if @commit.errors.any? %>

<%= pluralize(@commit.errors.count, "error") %> prohibited this commit from being saved:

    <% @commit.errors.full_messages.each do |msg| %>

<%= msg %>

    <% end %>

<% end %>

If I want to add this to this embedded form, how would I do so? I guess my question is, what would I use in place of @commit?
Thanks. I'm just trying to get my head around these new concepts.

A: If you go back to the documentation and click 'show source', you'll see
def form_for(record_or_name_or_array, *args, &proc)
  ...
  case record_or_name_or_array
  when String, Symbol
    ...
  when Array
    object = record_or_name_or_array.last
    object_name = options[:as] || ActiveModel::Naming.singular(object)
    apply_form_for_options!(record_or_name_or_array, options)
    args.unshift object
  else
    ...
  end
  ...
  output << fields_for(object_name, *(args << options), &proc)
  ...

For form_for, the first parameter can be a record, name or an array.  In your case, you pass it an array.  The code then determines the 'object' as the last member of that array, which is your @goal.commits.build object. The object name is determined from the ActiveModel::Naming.singular method.
console > ActiveModel::Naming.singular(@goal.commits.build)
=> "commit"

Then it generated the appropriate form fields using fields_for and 'commit'.

A: It looks like you are using nested resources.  Check your routes.rb file to see if you have something like:
map.resources :commits, :has_many => :goals
or perhaps:
map.resources :commits do |commit|
  commit.resources :goals
end
If that is the case, then you will need to supply both the commit and goal objects to the form_for method.


text:
Q: SharePoint SPClaimProvider details/usage I have to implement my own SPClaimProvider for PeoplePicker. There are some methods to override. Problem: I can't figure out some methods/parameters usage. All of these methods are claims specific.
Examples:

*

*method FillClaimValueTypes. What is claim value type? What doest it mean?

*method FillSearch, parameters hierarchyNodeID, searchTree - what this all is about? How can I use this?

Got ideas?

A: Have you had a chance to check out these articles?
How to create a claims provider
Claims Walkthrough: Writing Claims Providers for SharePoint 2010
for FillClaimValueTypes - just a list that must match order of FillClaimTypes as well. This is what your provider adds in terms of claims.  The type is a namespace, ie. such as http://mystuff/claims/myspecialclaim - it's a distinguishing identifier.
Check out this to see what methods are called by which process in your farm Know what process is calling your Claim Provider
There are other samples out there.  Nancy Brown has a good series:
Custom Claims Providers: Hierarchical Claims - Part 1, background


text:
Q: How can I tokenize this text into sentences with Regex
"You could not possibly have come at a better time, my dear Watson,"
  he said cordially. 'It is not worth your while to wait,' she went
  on."You can pass through the door; no one hinders." And then, seeing that I smiled and shook my head, she suddenly threw aside her
  constraint and made a step forward, with her hands wrung together.

Look at the highlighted area. How can I possibly distinguish a case where '"' is followed by a period (.) to end a sentence and a case where a period (.)  is followed by a '"'
I have tried this piece for the tokenizer. It works well except for just that one part.
(([^।\.?!]|[।\.?!](?=[\"\']))+\s*[।\.?!]\s*)

Edit: I am not planning to use any NLP toolkit to solve this problem.

A: Use NLTK instead of regular expressions here:
from nltk import sent_tokenize
parts = sent_tokenize(your_string)
# ['"You could not possibly have come at a better time, my dear Watson," he said cordially.', "'It is not worth your while to wait,' she went on.", '"You can pass through the door; no one hinders."', 'And then, seeing that I smiled and shook my head, she suddenly threw aside her constraint and made a step forward, with her hands wrung together.']

A: Found this function a while ago
def split_into_sentences(text):

caps = u"([A-Z])"
prefixes = u"(Mr|St|Mrs|Ms|Dr)[.]"
suffixes = u"(Inc|Ltd|Jr|Sr|Co)"
starters = u"(Mr|Mrs|Ms|Dr|He\s|She\s|It\s|They\s|Their\s|Our\s|We\s|But\s|However\s|That\s|This\s|Wherever)"
acronyms = u"([A-Z][.][A-Z][.](?:[A-Z][.])?)"
websites = u"[.](com|net|org|io|gov|mobi|info|edu)"

if not isinstance(text,unicode):
    text = text.decode('utf-8')

text = u" {0} ".format(text)

text = text.replace(u"\n",u" ")
text = re.sub(prefixes,u"\\1<prd>",text)
text = re.sub(websites,u"<prd>\\1",text)
if u"Ph.D" in text: text = text.replace(u"Ph.D.",u"Ph<prd>D<prd>")
text = re.sub(u"\s" + caps + u"[.] ",u" \\1<prd> ",text)
text = re.sub(acronyms+u" "+starters,u"\\1<stop> \\2",text)
text = re.sub(caps + u"[.]" + caps + u"[.]" + caps + u"[.]",u"\\1<prd>\\2<prd>\\3<prd>",text)
text = re.sub(caps + u"[.]" + caps + u"[.]",u"\\1<prd>\\2<prd>",text)
text = re.sub(u" "+suffixes+u"[.] "+starters,u" \\1<stop> \\2",text)
text = re.sub(u" "+suffixes+u"[.]",u" \\1<prd>",text)
text = re.sub(u" " + caps + u"[.]",u" \\1<prd>",text)
if u"\"" in text: text = text.replace(u".\"",u"\".")
if u"!" in text: text = text.replace(u"!\"",u"\"!")
if u"?" in text: text = text.replace(u"?\"",u"\"?")
text = text.replace(u".",u".<stop>")
text = text.replace(u"?",u"?<stop>")
text = text.replace(u"!",u"!<stop>")
text = text.replace(u"<prd>",u".")
sentences = text.split(u"<stop>")
sentences = sentences[:-1]
sentences = [s.strip() for s in sentences]
return sentences


text:
Q: Combine tags on Windows Phone? Recently I have found that there are too many of Windows Phone tags which is quite confusing when doing some search.
As you can see, currently we have 6 tags talking about Windows Phone.
windows-phone
windows-phone-7
windows-phone-7.1
windows-phone-7.1.1
windows-phone-7.5
windows-phone-8
I know there are already some topics discussing about the windows phone duplicate tags:
Tags [windows-phone-7.1] and [windows-phone-mango] are synonymous
Change [windows-phone-7] to [windows-phone]
Correct tag for Windows Phone 8
But I still think we should combine them, because sometimes for the asker, they've no idea what tags they should add, so they may just put the tags randomly or just put windows-phone on it, that makes people search question harder.

A: There is currently tag windows-phone-7 with synonyms wp7 and windows-phone-7.5.
There is also another tag windows-phone-7.1 with synonym windows-phone-mango.
Obviously these tags are wrongly matched. These five should be in my opinion all merged into one tag windows-phone-7.
There is currently no point now for distinguishing between WP7 and WP7.5, because developers can now target only WP7.5, no longer WP7.
Note there is also new tag windows-phone-8, that should be kept separate.

A: The problem that we are seeing is that there are all these tags but people aren't following all of them equally.
So someone will post a question that targets windows phone 8 but then they use ALL of the windows phone tags like this guy here windows phone 8 binding list inside list to the listbox
I suggest we just combine all of the windows phone tags into 2 tags. Windows-Phone7.X and Windows-Phone8.X
Please, for the sake of my sanity, stop the madness and combine these.

A: I think all mentioned tags should be merged to windows-phone.
Sure, there are significant differences between the versions. But do we realy need that distinction?
Most questions posted these days address developing for WP 8. But the question could be relevant for earlier versions as well. If the poster is unaware of that, he'll probably tag it with WP 8 where WP would be a better tag. The community could correct this but why would we lay this burden upon the community?
Suppose the tags are merged and a developer has a question related to a specific version. He can only pick WP so the tagging system obscures that it his question is related to a specific version. Is this bad? I don't think so. The question and the answers can address the fact that it relates to a specific version.
Pros:

*

*Clean tags

*Just one tag to follow when you are intereseted in Windows
Phone development

*Easy to use for new and seasoned developers

*Future proof (more or less)

Cons:

*

*Loose specifics

By the way, our highly fragmented and frequent updated friends from android use just one tag. I'm not sure if that should be considered a pro or a con... B-)


text:
Q: Parsing double value for current culture ASP.NET MVC  doesn't bind "1.5" double value(because invalid format for current culture). So i am trying to parse it manualy for current culture.
My solution is replacing "1.5" float point with valid float seperator  for current culture.
How can i replace float seperator by valid seperator in current culture ?
Do you have better solution for it ?

A: Just specify which culture you want to use when parsing:
CultureInfo culture = new CultureInfo(Request.UserLanguages[0]);
return double.Parse("1.5", culture.NumberFormat);

See the documentation for more detail.

A: If you just want to have "1.5" parse no matter the culture, try this:
var culture = System.Globalization.CultureInfo.GetCultureInfo("en-US");
Double.Parse("1.5", culture.NumberFormat);

That creates an instance of the en-US culture and tells the parser to use it in this specific case.


text:
Q: How to create a view in oracle with dynamic columns We have a main table that contains 5 columns, we need to load file that the columns in this file vary each time which means sometimes the file contains 8 columns five of them the same field exists in the main table and sometimes 10 fields five of them the same of main table and etc..,
Main table called population and its structure as below
pop_rec_id, name, age, address, transaction_date
data example:
152,john,26,palestine,1/1/2015
the file will be loaded into extra table called population_extra_fields and its structure as below
id,pop_rec_id(foreign key for population table),column_name,column_value
data example:
1,152,segment,high
2,152,region,West bank
3,152,city,Rammallah
we need to have a dynamic view to retrieve the data from both tables and the column names in the view should be the same as the names from population table and the column names from population_extra_fields
the view result should look like below based on the above data
pop_rec_id | name| age|address  |transaction_date| segment|region    | city
152        | john| 26 |palestine|1/1/2015        | high   | west bank| rammallah


text:
Q: How to offset the Y position of every second column in a Grid Control So, this is a standard 5x6 Grid.
<Grid Width="600" Height="840" >
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="1*"/>
        <ColumnDefinition Width="1*"/>
        <ColumnDefinition Width="1*"/>
        <ColumnDefinition Width="1*"/>
        <ColumnDefinition Width="1*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="1*"/>
        <RowDefinition Height="1*"/>
        <RowDefinition Height="1*"/>
        <RowDefinition Height="1*"/>
        <RowDefinition Height="1*"/>
        <RowDefinition Height="1*"/>
    </Grid.RowDefinitions>
</Grid>

Which produces something like this:

However, I need a way to offset the Y position of every second column to make the end result look like this:

I'm aware that I could use multiple Grids to achieve this, but is there any way this can be done with a single Grid? Or even perhaps a different Control?
Thanks

A: Make the grid rows only half the height, meaning double the rows: The use Grid.Row and Grid.Rowspan to create your layout. Just span every item over two rows and start every second column at Grid.Row = "1"


text:
Q: Learn Markup Validation So from the (very little) that I've read about Markup Validation, it's basically just a grammar/spelling check.  However, I can't find any sources on how to make "good" HTML code.  Is there any site in which I can learn how to write HTML properly?
Here's my code that was called horrid (specifically the HTML).

<title>MySQL Search!</title>

Search Results:

Card Name
Mana Cost
Card Set
Ability
Image

<?php
require 'dbconnect.php';
$Checkbox = $_POST['Ability'];
$q="SELECT * FROM mtgcards WHERE Ability LIKE '%$Checkbox%'";
$r = mysqli_query($dbc, $q);
while ($row = mysqli_fetch_array($r)) {
    Echo "" . $row['Name'] . "	";
    Echo "" . $row['Mana Cost'] . "	";
    Echo "" . $row['Colour'] . "	";
    Echo "" . $row['Set'] . "	";
    Echo "" . $row['Ability'] . "	";
    Echo "" . '	';
    Echo "
";
}

mysqli_close($dbc);
?>

A: Basically you need look into Web template system

It is considered messy to mix PHP and HTML like you did in your post.
And it will get worse as your web app grows.
There are many ones for PHP, one of the most popular ones is twig and smarty.
You can also create your own.
The bigger issue here is that you are not using prepared statements, you should be using prepare() to execute your queries.


text:
Q: Copy 3 rows and paste them above I'm trying to find a value ~P~ in column A. Copy the row it is on, and the 2 next ones. And paste all 3 above the row i found ~P~ on.
I have this:
Private Sub NPaddlinebutton_Click()
    Dim i As Long
    For i = Range("A" & Rows.Count).End(xlUp).Row To 1 Step -1
        If Range("A" & i).Value = "~P~" Then
            Rows(i).Copy
            Rows(i).Insert
            Range("A" & i).ClearContents
            Rows(i).Activate
        End If
    Next
    Application.CutCopyMode = False
End Sub

It works for 1 row, but can't figure out how to do it for 3 rows.
Any tips?

A: if i did clearly understand what you are looking for, the code below should do. The key is to use a range to include what you want to "play" with. 3 rows for example.
Let me know.
Private Sub NPaddlinebutton_Click()
    Dim i As Long
    Dim rng3rows As Range
    Dim rng3CellsColumn As Range
    For i = Range("A" & Rows.Count).End(xlUp).Row To 1 Step -1
        If Range("A" & i).Value = "~P~" Then
            Set rng3rows = Range(Rows(i), Rows(i + 2))' using a range to include the 3 rows you want to copy over
            rng3rows.Copy
            Rows(i).Insert
            Set rng3CellsColumn = Range(Cells(i, 1), Cells(i + 2, 1))' using a range to clear the the cells in the column A
            rng3CellsColumn.ClearContents
            Rows(i).Activate 'here i suggest Rows(i).select. I think that's what you want
        End If
    Next
    Application.CutCopyMode = False
    Set rng3rows = Nothing
    Set rng3CellsColumn = Nothing
End Sub

A: Private Sub Paddline_Click()
Dim i As Long
    Dim rng3rows As Range
    Dim rng3CellsColumn As Range
    For i = Range("A" & Rows.Count).End(xlUp).Row To 1 Step -1
        If Range("A" & i).Value = "~P~" Then
            Set rng3rows = Range(Rows(i), Rows(i + 2))  'using a range to include the 3 rows you want to copy over
            rng3rows.Copy
            Rows(i).Insert
            Set rng3CellsColumn = Range(Cells(i, 1), Cells(i + 2, 1))  'using a range to clear the the cells in the column A
            rng3CellsColumn.ClearContents
            Rows(i).Select
        End If
    Next
    Application.CutCopyMode = False
    Set rng3rows = Nothing
    Set rng3CellsColumn = Nothing
    'in randul 1
    Cells(ActiveCell.Row, 2).Value = Pclient.Value
    Cells(ActiveCell.Row, 3).Value = Pcodclient.Value
    Cells(ActiveCell.Row, 4).Value = ""
    Cells(ActiveCell.Row, 5).Value = Pnrcomanda.Value
    Cells(ActiveCell.Row, 7).Value = Pdesc1.Value
    Cells(ActiveCell.Row, 8).Value = Pperscontact.Value
    Cells(ActiveCell.Row, 28).Value = Pstatus.Value
    'in randul 2
    Cells(ActiveCell.Row + 1, 2).Value = Pclient.Value
    Cells(ActiveCell.Row + 1, 4).Value = ""
    Cells(ActiveCell.Row + 1, 8).Value = Pdesc2.Value
    Cells(ActiveCell.Row + 1, 10).Value = Pdurata.Value
    Cells(ActiveCell.Row + 1, 11).Value = Pdatadelay.Value
    Cells(ActiveCell.Row + 1, 27).Value = Pusername.Value
    Cells(ActiveCell.Row + 1, 28).Value = Pstatus.Value
    'in randul 3
    Cells(ActiveCell.Row + 2, 2).Value = Pclient.Value
    Cells(ActiveCell.Row + 2, 4).Value = ""
    Cells(ActiveCell.Row + 2, 8).Value = Pdesc3.Value
    Cells(ActiveCell.Row + 2, 10).Value = Pdurata.Value
    Cells(ActiveCell.Row + 2, 27).Value = PusernameV.Value
MsgBox "Datele au fost introduse in tabel."
    ActiveWindow.ScrollRow = 56
    Unload Me


text:
Q: How to save item in listview using sharedpreference I am just learning android studio.
then, I want to save my list item in my listview
only using shared preference.
I succeeded to Add and save item.
but it can save only one row!
then I input any key. it just changes key before adding the item.
so, how to adding list and save ? ! please help me
enter code here
// listview save sharedpreference
private void savePreferences () {
    String ten = editTen.getText().toString();
    String sdt = editSDT.getText().toString();
    SharedPreferences pref = getSharedPreferences("pref", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = pref.edit();
    editor.putString("list1", ten);
    editor.putString("list2", sdt);
    editor.commit();
}

// load sharedpreference
private void getPreferences() {
        SharedPreferences pref = getSharedPreferences("pref", Context.MODE_PRIVATE);
        String date = pref.getString("list1", null);
        String name = pref.getString("list2", null);
            arrSinhVien = new ArrayList<SinhVien>();
            arrSinhVien.add(new SinhVien(R.drawable.luan, date, name));
            myadapter = new CustomAdapter(this, R.layout.activity_diary_item, arrSinhVien);

    }

A: The Shared preferences is not use to save the list of items, Its just key value pair data structure to save small amount of data of your application.
 In your snippet you overwrite the previous data with new one.

But still if you want to save the list data, I suggest that to use the JSON array and put that Array into the shared preferences.
 The Code is like as follows.

JSONArray jsArr=new JSONArray();
JSONObject jsObj=new JSONObject();
jsObj.putString("ten",editTen.getText().toString());
jsObj.putString("sdt",editSDT.getText().toString());
//Add this object to your JSONArray
jsArr.add(jsObj);
//Serialize your Json Array and save to shared preferences.
savePreferences(jsArr);

private void savePreferences (JSONArray jsArr) {
SharedPreferences pref = getSharedPreferences("pref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("list", jsArr.toString());
editor.commit();
}

And use this as follows
private void getPreferences() {
    SharedPreferences pref = getSharedPreferences("pref", Context.MODE_PRIVATE);
    arrSinhVien = new ArrayList<SinhVien>();
    String jsArrList = pref.getString("list", null);
    JSONArray jsArr=new JSONArray(jsArrList);
    for(JSONObject obj:jsArr){
      String date=obj.getString("ten");
      String name=obj.getString("sdt");
      arrSinhVien.add(new SinhVien(R.drawable.luan, date, name));
    }
    myadapter = new CustomAdapter(this, R.layout.activity_diary_item, arrSinhVien);

}

Hope this will help you..


text:
Q: Load resources in angular with oclazyload and webpack I have a modular app who have multiple vendor plugins and I need to load only necessary in every view.
This is my routes:
(function() {
    'use strict';

    angular.module('app.empresas').config(config);

    function config($stateProvider, $ocLazyLoadProvider) {
        $stateProvider
            .state('app.empresas', {
                url: '/empresas?Filter',
                views: {
                    'main@': {
                        template: require('./empresas/empresas.html'),
                        controller: "AppController as App"
                    }
                },
                Params: {
                    title: 'Empresas',
                    bodyClass: '',
                    requiredLogin: true
                }
            })
            .state('app.empresas.view', {
                url: '/empresas/:ItemId',
                views: {
                    'main@': {
                        template: require('./empresas.view/empresas.view.html'),
                        controller: "AppController as App"
                    }
                },
                Params: {
                    title: 'Empresa',
                    bodyClass: '',
                    requiredLogin: true
                }
            })
    }
})();

I know how to include oclazyload resources without webpack, but now I need to include specific resources for every view. ¿How can do this?

A: I solved it using this snippet:
This is a sample of a state
.state('app.empresas.view', {
    url: '/empresas/:ItemId',
    views: {
        'main@': {
            templateUrl: '/app/main/apps/empresas/empresas.view/empresas.view.html',
            controller: "AppController as App"
        }
    },
    Params: {
        title: 'Empresa',
        bodyClass: '',
        requiredLogin: true
    },
    resolve: ['$q', '$ocLazyLoad', function ($q, $ocLazyLoad) {
        var deferred = $q.defer();

        var mod = importAll(require.context('./empresas.view/', true, /\.*$/));
        $ocLazyLoad.load({
            name: 'app.empresas.view'
        });
        deferred.resolve(mod);

        return deferred.promise;
    }]
})

I use this function with require to load entire folder with oclazyload and compile with webpack in a bundle separate file:
function importAll (r) {r.keys().forEach(r);}

I can load css, html, js files in one view without require files one by one


text:
Q: Increase a value every second iteration I want to increase a value every second iteration by a fixed value. The above code solves this, but I wonder if there's a better solution to this problem? In my real world problem the dataset is bigger and writing an if-statement is perhaps not an efficient solution. Can I use count in a better way?
iter= range(6)

start = 0.25
increase = 0.01

for count, i in enumerate(iter):
    print(count)
    if count in [1,3,5]:
        start = start + increase
        print(start)

A: You can use the operator % who tells you if it's even or odd:
print(1%2)  # 1
print(2%2)  # 0
print(3%2)  # 1
print(4%2)  # 0
print(5%2)  # 1

In the case, you use counter:
for count, i in enumerate(iter):
    print(count)
    if count % 2:  # It gives only 1 or 0
        start += increase
        print(start)

A: You could cycle between adding zero and your increment, and accumulate:
from itertools import cycle, accumulate, islice

length = 6
start = 0.25
increase = 0.01

xs = accumulate(cycle([0, increase]), initial=start)
for x in islice(xs, length):
    print(x)

Output:
0.25
0.25
0.26
0.26
0.27
0.27

A: You can use zip to skip iterations:
iter6 = iter(range(6))

start = 0.25
increase = 0.01

for _,i in zip(iter6,iter6):
    start += increase       # i is only every second value

there is also islice() in itertools:
for i in islice(iter6,1,None,2):
    start += increase       # i is only every second value

Or sum with either of those:
start += sum(increase for _ in zip(iter6,iter6))


text:
Q: Is there an easy way to do wrap this in sublime text? names = [Joey
Aurelio
Evan
Donny
Foster
Dwayne
Grady
Quinton
Darin
Mickey
Hank
Kim
Peter
Jeremy
Jess
Jimmie]

I want the names to appear as:
names = ['Joey', 'Aurelio','Evan', 'Donny',.....,'Jimmie']

A: *

*Manually select all the names inside the brackets.

*Select Selection → Split into Lines, which makes each name its own selection.

*Press the single quote ' key, which places a quote ' before each selection.

*Press the right arrow → key, which creates multiple cursors, one at the end of each word.

*Press the single quote ' then the comma , key, which adds the closing single quote and a comma , after each name. If you wish, you can then press Space followed by the forward delete Delete key to erase the newlines and put all the names on the same line.

*Manually navigate to the end of the list, remove the last comma, and re-add the closing bracket ].


text:
Q: Virtual vs. Physical Computer I am writing a little Lambda-calculus program in assembly. I ran it with VirtualBox and it worked perfectly, but when I copied the code into the bootsector of my USB-drive and booted my computer from it, it didn't work.
I've isolated the problem to be in the initial loading of an extra sector containing the function library. Here is the code snippet in question:
PUSH 0x2000
POP ES           ;segment 0x2000
MOV BX, 0x0000   ;offset
MOV CX, 0x0002   ;sector 2 and track 0
MOV DX, 0x0080   ;drive 80 and head 0
load:
MOV AX, 0x0201   ;read only one sector
INT 0x13         ;read sector
JC load          ;repeat until no error
MOV BX, 0x0007
MOV AH, 0x0E
MOV AL, [ES:0x0000]
INT 0x10         ;print a '!' character to test if the process is successful (purely for debugging reasons)

So with VirtualBox I get a nice ! to show that the loading process was successful, yet on my computer it gives me a black space (ASCII 0x00). Anyone any suggestions as to what might be the problem here.

A: I finally found the solution to my problem. It turns out that my code was located in the first two sectors of the logical disk. Although there is only one logical disk on my USB-drive, my hex editor excludes the first 2048 sector of the physical disk when opening as logical disk. Were windows sees this distinction, for the CPU it's just an array of bits. So when I loaded the second sector into memory, instead of loading the 2050th sector (for as far as I knew at the time Was the second sector) were the data was located, it loaded quite correctly the actual second sector containing, apart from some stray bits, only 0x00s.
Now that the data is in the correct sector, it works like a charm.