Q: Полнотекстовый поиск в таблице, БД MySQL Таблица в которой происходит поиск
CREATE TABLE `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `category` int(11) NOT NULL,
  `title` varchar(120) NOT NULL COMMENT 'Название',
  `power` decimal(4,1) NOT NULL COMMENT 'Мощность',
  `luminous` int(5) NOT NULL COMMENT 'Световой поток',
  `price` decimal(10,2) NOT NULL COMMENT 'Цена',
  `hash` varchar(255) DEFAULT NULL COMMENT 'Хэш картинки',
  `width` int(4) DEFAULT NULL COMMENT 'Длина',
  `height` int(4) DEFAULT NULL COMMENT 'Ширина',
  `depth` int(4) DEFAULT NULL COMMENT 'Толщина',
  `weight` decimal(7,3) DEFAULT NULL COMMENT 'Вес',
  PRIMARY KEY (`id`),
  KEY `category` (`category`),
  FULLTEXT KEY `title` (`title`),
  CONSTRAINT `products_ibfk_1` FOREIGN KEY (`category`) REFERENCES `category` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=256 DEFAULT CHARSET=utf8

Мой запрос поиска
SELECT * FROM `products` `t` WHERE MATCH (title) AGAINST (:data) ORDER BY t.price ASC LIMIT 50

:data   Взрывозащищенный светильник Диора-450 Ех-Д/К30/К60/III

Как я понял, ищется каждое слово из строки запроса во всех названиях продуктов, и где есть совпадение - тот продукт считается соответсвующим запросу
Такое решение возвращает слишком много результатов, в таблице почти во всех названиях есть слово "светильник", результаты поиска практически равны количеству всех товаров. Не могу разобраться как правильно составить запрос, чтобы результаты были точнее.
Второстепенный вопрос, так же задаюсь вопросом как не использовать маркировку в поиске.(из примера - "Ех-Д/К30/К60/III")

A: Можно предварительно обработать поисковую строку перед вставкой её в запрос
// Поисковый запрос
$search = 'Взрывозащищенный светильник Диора-450 Ех-Д/К30/К60/III';

// Не важные для поиска слова
$not_important = [
    'светильник',
    'лампа',
];

// Символы заменяются на проблелы. Тире может быть частью слова, потому оно не заменяется
$search = str_replace(['/', ',', '.', '"', "'", '`', '+', '(', ')'], ' ', $search);
$search = preg_replace('#(\s+)#', ' ', $search);

// Фраза разбивается на слова
$search = explode(' ', $search);

foreach ($search as $pos => $word)
{
    // По умолчанию mysql настроен так, что в полнотекстовом поиске
    // участвуют только слова длиной от 4-х символов, потому короткие слова можно удалить
    if (mb_strlen($word, 'UTF-8') < 4)
    {
        unset($search[$pos]);
    }
    //  Если слово важное и должно быть в выдаче, перед ним добавляется плюс
    elseif (!in_array(mb_strtolower($word, 'UTF-8'), $not_important))
    {
        $search[$pos] = '+'.$word;
    }
}

// Слова собираются в строку
$search = implode(' ', $search);

// Поиск ведётся в режиме IN BOOLEAN MODE
$q = "SELECT * FROM `products` t "
    ."WHERE MATCH (t.`title`) AGAINST ('".$search."' IN BOOLEAN MODE) "
    ."ORDER BY t.`price` ASC "
    ."LIMIT 50";

echo $q;

A: MATCH/AGAINST, если что, выражение.
И оно возвращает релевантность.
И по ней можно упорядочить:
SELECT *,
       MATCH (title) AGAINST (:data) AS `relevance`
  FROM `products` `t`
  WHERE MATCH (title) AGAINST (:data) -- это условие было у вас
  ORDER BY `relevance` DESC
  LIMIT 50


Q: Where are SKNode positioned in the responder chain? SKNode inherits from NSResponder but I'm having trouble understanding how nodes are included in the responder chain and where they are inserted.
For example, how does a SKNode receive the mouseDown: message?
When a view is clicked, a hit testing process occurs to determine the deepest view at the hit location and then mouseDown: is sent up the responder chain from that point.
SKNodes are not views so they cannot get send this message directly (because it it handled by the SKView). So how are they included in the responder chain?


Q: Django: query filter I have two models that are related: one is a list of participants.  The other is a list of times they have checked in or out of an office.
The table (Checkin) has one record for every checkin/checkout pair.  So, there can be many records for any participant.
How can I retrieve only the very last (most recent) record for a participants checkin and then pass the participant and only that most recent Checkin record to my template?
From what I can tell there's no ability to do something like a last() in my template, so how would I go about filtering to get just that single record?
Thank you.
Models:
class Participant(models.Model):

    first_name = models.CharField(max_length=50)
    middle_initial = models.CharField(max_length=50, blank=True)

class CheckIn(models.Model):
    adult = models.ForeignKey(
        Participant, on_delete=models.CASCADE, blank=True, null=True, related_name='adult_checkin')

    checkin = models.DateTimeField(blank=True, null=True)
    checkout = models.DateTimeField(blank=True, null=True)

View snipit:
    p_checkins = Participant.objects.all().order_by('created')

    queryset = p_checkins

    context_object_name = "the_list"

    template_name = 'list_of_checkins.html'

A: You can fetch data through most recent checkin or checkout.
For checkin :
p_checkins = CheckIn.objects.all().order_by('-checkin')[0]

For checkout :
p_checkins = CheckIn.objects.all().order_by('-checkout')[0]

To get the participant name by :
name = p_checkins.adult.first_name

A: When you use (-) your latest update will be query from database.
p_checkins = CheckIn.objects.all().order_by('-checkin')

or
p_checkins = CheckIn.objects.all().order_by('-checkout')

A: you can annotate the latest value via a subquery to the participant
from django.db.models import OuterRef, Subquery
checkin_q = CheckIn.objects.filter(adult=OuterRef('pk')).order_by('-checkin')
queryset = Participant.objects.annotate(last_checkin=Subquery(checkin_q.values('checkin')[:1]))

see https://docs.djangoproject.com/en/4.0/ref/models/expressions/#subquery-expressions

A: Most of the answers so far are correct in several aspects. One thing to note is that if your check_in or check_out values (whichever you use) isn't chronological (and by "most recent", you mean the last added), you'll want to add a created_at datetime field with auto_now option True, or order by the pk.
In addition to the other answers provided and my comment above, you can also get the most recent check in by using the related manager on the participant object.


Q: Is there a way to show an Android dialog without graying out the back drop? I want to pop open a DatePickerDialog in a certain screen, but I am required to not grey out the rest of the screen (the view behind the dialog) when the DatePickerDialog window opens. Is there a way to achieve this?

A: You probably would want to create your own custom dialog.  You can extend DialogFramgent and change it accordingly.
See the Android doc HERE for a great example.
Or, use PopupWindow if you want a popover dialog with control of the background, see this SO post.


Q: format JSON object into array like structure I am quite new to Python but trying to do some machine learning with it.
My problem is to format a received JSON object into an array like structure to submit this to my predictor function of the ML model.
JSON object looks like when I do a print of it
{u'CRIM': 0.62739, u'ZN': 0, u'B': 395.62, u'LSTAT': 8.47, u'AGE': 56.5, u'TAX': 307, u'RAD': 4, u'CHAS': 0, u'NOX': 0.538, u'MEDV': 19.9, u'RM': 5.834, u'INDUS': 8.14, u'PTRATIO': 21, u'DIS': 4.4986}

what i need is
[0.62739, 0, 395.62, 8.47, 56.5, 307, 4, 0, 0.538, 19.9, 5.834, 8.14, 21, 4.4986]

Can anybody help here
thanks
Peter

A: try:
json_var = {u'CRIM': 0.62739, u'ZN': 0, u'B': 395.62, u'LSTAT': 8.47, u'AGE': 56.5, u'TAX': 307, u'RAD': 4, u'CHAS': 0, u'NOX': 0.538, u'MEDV': 19.9, u'RM': 5.834, u'INDUS': 8.14, u'PTRATIO': 21, u'DIS': 4.4986}
value_array = json_var.values()

A: What you are looking for is
d = {'a':1, 'b': 2, 'c': 3}
num_list = d.values()

# num_list = [1,2,3]


Q: SQL Query to match a subset of data I have a table that looks like:
CLASS   VALUE
1       A
1       B
1       C
2       A
2       C
3       B
3       D
4       A
5       C
5       A

I have a user-submitted data-set of values that I want to find any classes whose values are a subset of the user-submitted data-set.
For example,
If data-set was A, B, and C then the results would be class 1, 2, 4, and 5.
If data-set was A and C the results would be class 2, 4, and 5.
If data-set was A, then result would be class 4.
The platform I am on is SQL Server, but really any SQL-based answer would be best.

A: As per the comment It's passed as a table. - assuming the table is the variable @UserInput with a single column of Value, you can use a WHERE EXISTS clause to check for the existence of that value in the user-input fields, and pull the DISTINCT Class values.
Select  Distinct Class
From    YourTable   T
Where Exists
(
    Select  *
    From    @UserInput  U
    Where   T.Value = U.Value
)

Your SQL syntax will vary, but this should point you in the right direction, syntactically.
A full example of how to implement this would be as follows:
Creating the User-defined Table Type
Create Type dbo.UserInput As Table
(
    Value   Varchar (10)
)
Go

Creating the Stored Procedure
Create Proc dbo.spGetClassesByUserInput
(
    @UserInput dbo.UserInput ReadOnly
)
As Begin
    Select  Distinct Class
    From    YourTable   T
    Where Exists
    (
        Select  *
        From    @UserInput  U
        Where   T.Value = U.Value
    )
End
Go

Calling the Stored Procedure with user input
Declare @Input dbo.UserInput
Insert  @Input
Values  ('A'), ('B'), ('C')

Execute dbo.spGetClassesByUserInput @Input

A: You can create a stored procedure an pass the user entry as it as string for ex. A,B,C
Create Procedure dbo.GetClasses
@v_UserEntry Varchar(200)
As
Begin
    Declare @SQLQuery AS NVarchar(1000)
    Declare @ParamDefinition AS NVarchar(300)

    SET @v_UserEntry= REPLACE(@v_UserEntry,',',''',N''')
    Set @SQLQuery ='Select Class'
    Set @SQLQuery = @SQLQuery + ' From TableName'
    Set @SQLQuery = @SQLQuery + ' Where Value in (N'''+@v_UserEntry+''')'
    Set @SQLQuery = @SQLQuery + ' Group By Class'
    Execute sp_executesql @SQLQuery
End
Go


Q: Can python read this type of config file? good morning. I want you help. I'm making a  project using python but i want know if python2 can read this type of config file. Example:
[SETTINGS]
{
  "Name": "SKY",
  "SuggestedBots": 50,
  "MaxCPM": 3000,
  "LastModified": "2019-11-03T23:24:24.0854425-03:00",
  "AdditionalInfo": "",
  "Author": "KATO",
  "Version": "1.1.4",
  "IgnoreResponseErrors": false,
  "MaxRedirects": 8,
  "NeedsProxies": true,
  "OnlySocks": false,
  "OnlySsl": false,
  "MaxProxyUses": 0,
  "BanProxyAfterGoodStatus": false,
  "EncodeData": false,
  "AllowedWordlist1": "",
  "AllowedWordlist2": "",
  "DataRules": [],
  "CustomInputs": [],
  "ForceHeadless": false,
  "AlwaysOpen": false,
  "AlwaysQuit": false,
  "DisableNotifications": false,
  "CustomUserAgent": "",
  "RandomUA": false,
  "CustomCMDArgs": ""
}

I tryed with tutorials from internet but doesn't work. I think it's JSON.

A: If you drop the first line, then it can be used in python.
import json

test = '''{
  "Name": "SKY",
  "SuggestedBots": 50,
  "MaxCPM": 3000,
  "LastModified": "2019-11-03T23:24:24.0854425-03:00",
  "AdditionalInfo": "",
  "Author": "KATO",
  "Version": "1.1.4",
  "IgnoreResponseErrors": false,
  "MaxRedirects": 8,
  "NeedsProxies": true,
  "OnlySocks": false,
  "OnlySsl": false,
  "MaxProxyUses": 0,
  "BanProxyAfterGoodStatus": false,
  "EncodeData": false,
  "AllowedWordlist1": "",
  "AllowedWordlist2": "",
  "DataRules": [],
  "CustomInputs": [],
  "ForceHeadless": false,
  "AlwaysOpen": false,
  "AlwaysQuit": false,
  "DisableNotifications": false,
  "CustomUserAgent": "",
  "RandomUA": false,
  "CustomCMDArgs": ""
}'''

json.loads(test)

# {u'AlwaysQuit': False, u'Author': u'KATO', u'LastModified': u'2019-11-03T23:24:24.0854425-03:00', u'DataRules': [], u'AlwaysOpen': False, u'Version': u'1.1.4', u'DisableNotifications': False, u'NeedsProxies': True, u'CustomInputs': [], u'EncodeData': False, u'BanProxyAfterGoodStatus': False, u'SuggestedBots': 50, u'ForceHeadless': False, u'RandomUA': False, u'AdditionalInfo': u'', u'Name': u'SKY', u'CustomUserAgent': u'', u'MaxRedirects': 8, u'CustomCMDArgs': u'', u'OnlySocks': False, u'MaxProxyUses': 0, u'IgnoreResponseErrors': False, u'AllowedWordlist1': u'', u'AllowedWordlist2': u'', u'OnlySsl': False, u'MaxCPM': 3000}


Q: pymodm can't find an object, while pymongo successfully finds it I have a problem getting an object from the mongodb instance. If I search for this object with pymongo interface, everything is fine - object can be found. If try to do the very same thing with pymodm - it fails with error.
Here is what I'm doing:
from pymodm import connect, MongoModel, fields
from pymongo import MongoClient

class detection_object(MongoModel):
    legacy_id = fields.IntegerField()

client = MongoClient(MONGODB_URI)
db = client[MONGODB_DEFAULT_SCHEME]
collection = db['detection_object']
do = collection.find_one({'legacy_id': 1437424})
print(do)

connect(MONGODB_URI)
do = detection_object.objects.raw({'legacy_id': 1437424}).first()
print(do)

The first print outputs this: {'_id': ObjectId('5c4099dcffa4fb11494d983d'), 'legacy_id': 1437424}. However, during the execution of this command: do = detection_object.objects.raw({'legacy_id': 1437424}).first() interpreter fails with the following error:
    Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/pymodm/queryset.py", line 127, in first
    return next(iter(self.limit(-1)))
StopIteration

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/konsof01/PycharmProjects/testthisfuckingshit/settings.py", line 29, in <module>
    do = detection_object.objects.raw({'legacy_id': 1437424}).first()
  File "/usr/local/lib/python3.7/site-packages/pymodm/queryset.py", line 129, in first
    raise self._model.DoesNotExist()
__main__.DoesNotExist

How can this be? I'm trying to query the very same object, with the same connection and collection. Any ideas, please?

A: you could try it as follows:
detection_object.objects.raw({'legacy_id': "1437424"} ).first()

probably the legacy_id is stored as string.
Othewise, make sure the db name is present at the end of the MONGO_URI as it is underlined in the docs.

A: Each document in your 'detection_object' collection requires to have '_cls' attribute. The string value stored in this attribute should be
    __main__.classname

(class name according to your code is detection_object).
For example a document in your database needs to look like this:
    {'_id': ObjectId('5c4099dcffa4fb11494d983d'), 'legacy_id': 1437424, '_cls': '__ main __.detection_object'}


Q: Django Elasticbeanstalk: Cannot access static files when Debug = False My static files are served with no issue when Debug = True.  I have read the documentation on https://docs.djangoproject.com/en/1.8/howto/static-files/deployment/ but still cannot get it to work when Debug = False.  These are my settings (works fine when Debug = True):
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

STATIC_URL = 'myapp/static/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR),"myapp","static","static-only")
STATICFILES_DIRS = (
os.path.join(os.path.dirname(BASE_DIR),"myapp","static"),
)

I have edited the config file to be:
container_commands:
   collectstatic:
      command: "myapp/manage.py collectstatic --noinput"

option_settings:
  "aws:elasticbeanstalk:application:environment":
     DJANGO_SETTINGS_MODULE: "myapp.settings"
     PYTHONPATH: "/opt/python/current/app/myapp:$PYTHONPATH"
  "aws:elasticbeanstalk:container:python":
     WSGIPath: "myapp/myapp/wsgi.py"
  "aws:elasticbeanstalk:container:python:staticfiles":
    "/static/": "myapp/static/"

I have been banging my head on this for some time so any help would be much appreciated!

A: I don't have a direct answer to your question, other than to ask you why are you trying to do it this way. The best practice is to move your static files to S3 or ideally, CloudFront (or another non-AWS solution).
Use django-storages-redux (https://github.com/jschneier/django-storages) to use static files from S3 for production. Google 'django s3 static' and you will find several blogs explaining the process. The documentation is here.

A: collectstatic command would have collected all your static file to STATIC_ROOT which you had set as "/PATH/TO/myapp/static/static-only.
So I suspect that you pointed your static files to the wrong directory in the config file.
Try "/static/": "myapp/static/static-only"


Q: running load testing on selenium and api tests in Visual studio Team Services I am trying to run load tests on my existing selenium web tests and my api(unit) tests. The tests run in Visual studio using load test editor but does not collect all the metrics like response time and requests per seconds. Are there any additional parameters that I need to add to collect all the metrics ?

A: Load testing; how many selenium clients are you running? One or two will not generate much load. First issue to think about; you need load generators and selenium is a poor way to go about this (unless you are running grid headless but still).
So the target server is what, Windows Server 2012? Google Create a Data Collector Set to Monitor Performance Counters.
Data collection and analysis of same is your second issue to think about.  People pays loads of money for tools like LoadRunner because they provide load generators and sophisticated data collection of servers, database, WANs and LANS and analysis reports to pinpoint bottlenecks.  Doing this manually is hard and not easily repeatable.  Most folks who start down your path eventually abandon it.  Look into the various load/performance tools to see what works best for you and that you can afford.


Q: Error al actualizar Referencia de Servicio a la nueva versión del SII de AEAT Estaba trabajando con un proto en VB.NET para registrar Facturas Emitidas y Recibidas para el SII de AEAT basados en la V_05.
La semana pasada, AEAT emitió una revisión V_06. Mi prototipo empezó a fallar ya que la propiedad IDVersionSii seguía conteniendo el valor de la revisión anterior.
Siendo novel consumiendo Servicios Web vi una opción en VBNet que permitía, desde las referencias a los servicios, cambiar la "Configuración de referencia de servicio". Cambié la dirección a la nueva versión:
http://www.agenciatributaria.es/static_files/AEAT/Contenidos_Comunes/La_Agencia_Tributaria/Modelos_y_formularios/Suministro_inmediato_informacion/FicherosSuministros/V_06/SuministroFactEmitidas.wsdl
Aparentemente las clases y tipos de ese servicio se han actualizado correctamente (ya incluyen los apartados referentes a operaciones de seguros y el valor permitido para SIIVersion ya es el que corresponde: 0.6.
Sin embargo, cuando hago la llamada al siiSOAPClient en lugar de devolverme un objeto Respuesta de Suministro me lanza una excepción:

Excepción producida: 'System.ServiceModel.ProtocolException' en mscorlib.dll
El tipo de contenido text/html del mensaje de respuesta no coincide con el tipo de contenido del enlace (text/xml; charset=utf-8). Si usa un codificador personalizado, asegúrese de que el método IsContentTypeSupported se implemente correctamente.
(...) Agencia Tributaria - Se ha producido un error (...)

Me temo que al actualizar las referencias algo no ha ido bien con el tema de los puertos o los Bindings del archivo app.config.
Me gustaría que alguien me pudiera concretar a qué se debe este error porque seguro que en los meses que quedan la AEAT vuelve a redefinir los servicios web y volveré a encontrarme con el mismo problema.
Nada de esto me pasa si, SIN modificar las referencias a los servicios, voy a la definición del tipo SIIVersion y cambio el literal "0.5" a "0.6". Pero claro, mis clases se quedan "obsoletas" con respecto a la versión actual (y subsiguientes) y entiendo que no es una solución válida.

A: Problema solucionado. Al actualizar las referencias al servicio web se modificaba el archivo app.config
El problema aparecía en el nodo <bindings>, donde Visual Studio borraba parte de la configuración de seguridad necesaria para los servidores de la AEAT.
La "auto-configuración" (resultado de actualizar referencias) incorrecta es:
<bindings>
    <basicHttpBinding>
        <binding name="siiBinding">
            <security mode="Transport" />
        </binding>
    </basicHttpBinding>
</bindings>

y la configuración correcta es:
<bindings>
    <basicHttpBinding>
        <binding name="siiBinding">
          <security mode="Transport">
            <transport clientCredentialType="Certificate" />
          </security>
        </binding>
    </basicHttpBinding>
</bindings>

Supongo que el html que me devolvía pretendía avisar de problemas de autentificación por certificado.

A: En Visual Studio, abres un proyecto nuevo de Winforms con Vb.Net.
El el explorador de soluciones seleccionas el proyecto y en el menú contextual seleccionas Añadir -> Referencia de Servicio
En la dirección pones la siguiente url:
"http://www.agenciatributaria.es/static_files/AEAT/Contenidos_Comunes/La_Agencia_Tributaria/Modelos_y_formularios/Suministro_inmediato_informacion/FicherosSuministros/V_06/SuministroFactEmitidas.wsdl"
y te abre un servicio con las siguientes funciones:

*

*AnulacionLRFacturasEmitidas

*ConsultaLRFacturasEmitidas

*SuministroLRFacturasEmitidas


Q: git remote /home/username/www/lorem.git
How can I use /home/username/www/example.git with remote add command?
if I use this:
git remote add origin user@example.com:/home/user/www/example.git
git push origin master

I got this error:
error: src refspec master does not match any.
error: failed to push some refs to 'user@example.com:/home/user/www/example.git'

A: Default behaviour of git push is just to push "matching refs", i.e. branches which are present both in the local and the remote repository. In your example, there are no such branches, so you need to tell git push which branches to push explicitly, i.e. via
git push origin branch-to-be-pushed

or, if you want to push all branches,
git push --all origin


Q: No runtime warning when content compression/hugging constraints conflict with specific width/height constraints Example
A UIButton that has:

*

*1000 priority width constraint (say width = 20)

*1000 priority horizontal compression resistance priority

*wide content that is bigger than 20

I don't get any runtime warning (the one in debugger), but for me it seems that i should. The content (button title) gets truncated. Why there is no warning and how do i enable it?


Q: Can you write a generic function that will compare any numeric type (e.g. int, float, double) against zero? We're trying to write a simple gain/loss function to return a color based on a value relative to zero.  If it's positive, we return green. If negative, we return red. If zero, we return gray.
The current function is written specifically to take a double, like so:
func getChangeColor(value:Double) -> UIColor {

    if value > 0 {
        return Theme.Colors.gain
    } else if value < 0 {
        return Theme.Colors.loss
    } else {
        return Theme.Colors.noChange
    }
}

But I'm wondering if it can be updated to take any numeric value?
My first thought was to write it against Comparable but the problem is we need to compare it against zero in that same type, whatever it is.
In other languages like C#, you can get the default value for a type, which in the case of numerics, is zero.  Does Swift have anything similar? If so, we could do this...
func getChangeColor<T:Comparable>(value:T) -> UIColor {

    let defaultValue = default(T.self)

    if value > defaultValue {
        return Theme.Colors.gain
    } else if value < defaultValue {
        return Theme.Colors.loss
    } else {
        return Theme.Colors.noChange
    }
}

...or is this approach wrong in the first place?

A: My solution adds a second protocol conformance: Numeric provides basic arithmetic operators for scalar types.
Then you are able to calculate the zero value in the generic type
func getChangeColor<T : Comparable & Numeric>(value:T) -> UIColor {

    let zero = value - value

    if value > zero {
        return Theme.Colors.gain
    } else if value < zero {
        return Theme.Colors.loss
    } else {
        return Theme.Colors.noChange
    }
}

or with a switch statement
func getChangeColor<T : Comparable & Numeric>(value:T) -> UIColor {

    let zero = value - value

    switch value {
    case zero:  return Theme.Colors.noChange
    case zero...: return Theme.Colors.gain
    default: return Theme.Colors.loss
    }
}

or with the ternary operator (added by OP)
func getChangeColor<T : Comparable & Numeric>(value:T) -> UIColor {

    let zero = value - value

    return value > zero
        ? Theme.Colors.gain
        : value < zero
            ? Theme.Colors.loss
            : Theme.Colors.noChange
}


Q: complement of a graph is non planar How to prove that the complement of $C_n$ is non planar for every $n\geq7$. I only know the definition of non planar.
Any help would be appreciated .
Thanks in advance.

A: The difficult part is doing it for $\overline{C_7}$. Writing $1...7$ for the vertices of $C_7$, the complement contains the edges $13,35,57,72,24,46,61$, which form a cycle. So any drawing must contain this cycle.
Now look at the other edges, and try to determine whether they go inside or outside the cycle. You'll find once you make the choice for one edge, that determines two others, and eventually leads to a contradiction.
Finally, if $n>7$ then $\overline{C_n}$ contains $\overline{C_7}$ as a subgraph, so if it is non-planar for $n=7$ it is non-planar for all $n\geq 7$.


Q: How do I access an Arabic letter least painfully in a mathematical text I write a mathematical text with the preamble
\documentclass[fleqn]{scrartcl}
\setkomafont{disposition}{\normalfont\bfseries}
\makeatletter\let\TTTemp\cap\makeatother
\usepackage[greek,english]{babel}
\usepackage{teubner}
\makeatletter\let\cap\TTTemp\makeatother
\usepackage{eurosym}
\usepackage{amssymb}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{lgreek}
\usepackage{graphicx}
\usepackage{textcomp}
\usepackage{cancel}
\usepackage{soul}
\usepackage{cjhebrew}
\usepackage{mathtools}
\usepackage{rotating}
\usepackage{esvect}
\usepackage{natbib}
\usepackage{MnSymbol}

\usepackage{hyperref}
\usepackage{tocbibind}
\allowdisplaybreaks

I would like to access the Arabic letter Noon. How can I do it least painfully?

A: I would use fontspec with option nomath, so that the usual packages take care of math typesetting,  and compile with xelatex or lualatex. The  problem is to have a font that has arabic characters. All you have to know is theU-code of the character you want to use. Here is a example, in which I use Arial:
\documentclass[a4paper,12pt]{article}

\usepackage{fontspec}

\newfontfamily\arabfont{Arial}
\newcommand\arabtext[1]{{\arabfont#1}}

\begin{document}
Here is the letter nun,  regular and boldface: \medskip

\arabtext{\LARGE\char"0646\quad\bfseries\char"0646}

\end{document}

A: To avoid working with Unicodes, I would recommend using the arabtex package (lookup table here). Here's a working example:
\documentclass[14pt]{article}
\usepackage{arabtex}

\begin{document}
\setarab

\begin{RLtext}
n
\end{RLtext}

\end{document}


Q: Is it possible to upload a document from SharePoint Mobile site? I need a function to upload few documents to my SharePoint 2010 mobile site using a mobile browser. But I do not see the function anywhere. Anyone knows how to do it?

A: On a windows mobile , there are some enhanced activeX controls for IE that supports SP 2010 ribbon upload functionality.
Let us know , what mobile and browser type you are using.


Q: SQL Query Return Entries with no Occurences in Other Table I have two tables, orders and customers, and I am trying to return the customerID and name of customers with no orders.
customers
customerID: integer
name: string

orders
orderID: integer
itemID: integer
customerID: integer
date: date

What I currently have is not returning any results:
SELECT customers.customerID, customers.fName, orders.date
FROM orders INNER JOIN customers
ON orders.customerID = customers.customerID
GROUP BY orders.customerID
HAVING COUNT(*) = 0

A: You need a LEFT OUTER JOIN to accomplish this:
SELECT customers.customerID, customers.fName
FROM customers LEFT OUTER JOIN orders on customers.customerID = orders.customerID
WHERE orders.customerID IS NULL


Q: Nearby Messages using an IntentService Initially I setup a BroadcastReceiver to receive intents from the Nearby Messages API.
class BeaconMessageReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {
        Nearby.getMessagesClient(context).handleIntent(intent, object : MessageListener() {
            override fun onFound(message: Message) {
                val id = IBeaconId.from(message)
                Timber.i("Found iBeacon=$id")
                sendNotification(context, "Found iBeacon=$id")
            }

            override fun onLost(message: Message) {
                val id = IBeaconId.from(message)
                Timber.i("Lost iBeacon=$id")
                sendNotification(context, "Lost iBeacon=$id")
            }
        })
    }

    private fun sendNotification(context: Context, text: String) {
        Timber.d("Send notification.")
        val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        val notification = NotificationCompat.Builder(context, Notifications.CHANNEL_GENERAL)
                .setContentTitle("Beacons")
                .setContentText(text)
                .setSmallIcon(R.drawable.ic_notification_white)
                .build()

        manager.notify(NotificationIdGenerator.nextID(), notification)
    }

}

Then registered this receiver in my MainActivity after location permissions have been granted.
class MainActivity : AppCompatActivity() {

    // ...

    private fun onLocationPermissionsGranted() {
        val filter = MessageFilter.Builder()
                .includeIBeaconIds(UUID.fromString("B9407F30-F5F8-466E-AFF9-25556B57FEED"), null, null)
                .build()

        val options = SubscribeOptions.Builder().setStrategy(Strategy.BLE_ONLY).setFilter(filter).build()

        Nearby.getMessagesClient(context).subscribe(getPendingIntent(), options)
    }

    private fun getPendingIntent(): PendingIntent = PendingIntent.getBroadcast(
            this, 0, Intent(context, BeaconMessageReceiver::class.java), PendingIntent.FLAG_UPDATE_CURRENT)

}

This worked well while the app was open, but does not work when the app is closed. So I found this example, that demonstrates how to setup an IntentService to receive messages while the app is in the background.
The example does use the Nearby.Messages class, which was deprecated in favor of the MessagesClient. So I replaced the deprecated code with the MessagesClient implementation.
class MainActivity : AppCompatActivity() {

    // ...

    private fun onLocationPermissionsGranted() {
        val filter = MessageFilter.Builder()
                .includeIBeaconIds(UUID.fromString("B9407F30-F5F8-466E-AFF9-25556B57FEED"), null, null)
                .build()

        val options = SubscribeOptions.Builder().setStrategy(Strategy.BLE_ONLY).setFilter(filter).build()

        Nearby.getMessagesClient(context).subscribe(getPendingIntent(), options)
            .addOnSuccessListener {
                Timber.i("Subscribed successfully.")
                startService(Intent(this, BeaconMessageIntentService::class.java))
            }.addOnFailureListener {
                Timber.e(exception, "Subscription failed.")
            }
    }

    private fun getPendingIntent(): PendingIntent = PendingIntent.getBroadcast(
            this, 0, Intent(context, BeaconMessageIntentService::class.java), PendingIntent.FLAG_UPDATE_CURRENT)

}

And this is the IntentService (which is almost identical to my BroadcastReceiver).
class BeaconMessageIntentService : IntentService("BeaconMessageIntentService") {

    override fun onHandleIntent(intent: Intent?) {
        intent?.let {
            Nearby.getMessagesClient(this)
                    .handleIntent(it, object : MessageListener() {
                        override fun onFound(message: Message) {
                            val id = IBeaconId.from(message)
                            Timber.i("Found iBeacon=$id")
                            sendNotification("Found iBeacon=$id")
                        }

                        override fun onLost(message: Message) {
                            val id = IBeaconId.from(message)
                            Timber.i("Lost iBeacon=$id")
                            sendNotification("Lost iBeacon=$id")
                        }
                    })
        }
    }

    private fun sendNotification(text: String) {
        Timber.d("Send notification.")
        val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        val notification = NotificationCompat.Builder(this, Notifications.CHANNEL_GENERAL)
                .setContentTitle("Beacons")
                .setContentText(text)
                .setSmallIcon(R.drawable.ic_notification_white)
                .build()

        manager.notify(NotificationIdGenerator.nextID(), notification)
    }

}

onHandleIntent is called, and the Intent is not null; yet for some reason onFound() and onLost() are never called. Why would this be the case?

A: It's not really a solution but what I found is this (credit to this answer):
I've tried a few configurations including a BroadcastReceiver and adding a JobIntentService to run the code in the background, but every time I got this the onExpired callback which you can set to the SubscribeOptions:
options.setCallback(new SubscribeCallback() {
    @Override
    public void onExpired() {
        super.onExpired();
        Toast.makeText(context.get(), "No longer Subscribing!", Toast.LENGTH_SHORT).show();
    }
}

When the subscribe occurred in the background it was delayed, but it was still called.
Notes:
1. When I've tested with Strategy.BLE_ONLY I did not get the onFound callback.
2. From Google's documentation:

Background subscriptions consumes less power than foreground
  subscriptions, but have higher latency and lower reliability

When testing I found this "lower reliability" to be an understatement: onFound was rarely called and I never got the onLost.

A: I know this is a late reply, but I had the same problem and found out by debugging that it is an issue related to this error: "Attempting to perform a high-power operation from a non-Activity Context". This can be solved when calling Nearby.getMessagesClient(this) by passing in an activity context instead of this.
In my case I added a class extending Application which helps in returning this context (the below is in java but should be translatable to kotlin easily)
public class MyApplication extends Application {
    private Activity currentActivity = null;

    public Activity getCurrentActivity(){
        return currentActivity;
    }
    public void setCurrentActivity(Activity mCurrentActivity){
        this.currentActivity = mCurrentActivity;
    }
}

And in my base activity, from which all activities extend, I set the current activity by calling ((MyApplication) this.getApplicationContext()).setCurrentActivity(this); in the constructor.
My service can then call getMessagesClient with the correct context like below:
final Activity context = ((MyApplication)getApplicationContext()).getCurrentActivity();
Nearby.getMessagesClient(context).[...]

Do not forget to register your Application class in the AndroidManifest:
<application
android:name="com.example.xxx.MyApplication"`


Q: Scanf doesn't work with fork in a loop after the second iteration I don't understand why scanf won't wait for input the second time in the loop. it only works in the first iteration. Also somewhat wait(&Status) won't print the correct Status.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
    int x ;
    int Status =-99;
    char* cmds[5];
    cmds[1] = "who";
    cmds[2] = "ls";
    cmds[3] = "date";
    cmds[4] = "kldsfjflskdjf";
    int i=10;
    while (i--) {
        printf("\nMenu:\n");
        printf("1)who \n"); printf("2)ls  \n");printf("3)date\n");
        printf("choice :");
        scanf("%d", &x);

        int child = fork();
        if (child != 0) {
            execlp(cmds[x], cmds[x], NULL);
            printf("\nERROR\n");
            exit(99);
        } else {
            wait(&Status);
            printf("Status : %d", Status);
        }
    }
}

A: Like the comment posted above says, there are two problems here:

*

*You're running the command in the parent, rather than the child. See the fork manual.

*wait does not give you the return code. It gives you an integer that you need to decode. See the wait manual.
Here's the corrected code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
    int x ;
    int Status =-99;
    char* cmds[6];
    cmds[1] = "who";
    cmds[2] = "ls";
    cmds[3] = "date";
    cmds[4] = "kldsfjflskdjf";
    int i=10;
    while (i--) {
        printf("\nMenu:\n");
        printf("1)who \n"); printf("2)ls  \n");printf("3)date\n");
        printf("choice :");
        scanf("%d", &x);

        int child = fork();
        if (child == 0) {
            execlp(cmds[x], cmds[x], NULL);
            printf("\nERROR\n");
            exit(99);
        } else {
            wait(&Status);
            printf("Status : %d", WEXITSTATUS(Status));
        }
    }
    return 0;
}


Q: SQL: name without a login name I have noticed that when I open SQL server enterprise manager and I navigate to the list of users under a specific DB, I found users with"Name" but some have no "Login Name" value. What does this means? Does it means that the
1)users cannot log into the server at all?
2)its a system ID(or application ID so no user will be able to use it to log on and only applications can use it to access the database?)
3)there is a single sign on so once the user sign into the server, they can access the db without authentication again?
My second question pertains to the users under the "Security" group in enterprise manager.When lets say "a" is here and "a" is also present in the db users, it means that "a" can access and change data in the db right? But if "b" is in the security group but not in the db users, it means that it cannot log onto the db but only make changes to the server only?
My third question: If default database is master, it means that that user can make changes to all the database?
A huge thanks to anyone who answers my questions!

A: Database logins and database users are different.  Basically a login is granted permissions the server, a user is granted permissions to database.  Logins are mapped to databases.
My guess the reason you have users in a database that aren't mapped to logins is that you've restored a database from another SQL Server and not copied the logins across.  There are basically 2 ways of fixing orphaned users.  You can use sp_change_users_login, or you can copy the logins between servers so the sid's match.
If you want to use a single sign-on method then you can do this by integrating with Active Directory by creating a windows login instead of using a sql login.
Yes, you can map a login to more than one database. You can GRANT access to different objects for each database to the user, or add the user to a database role.  There are also serverwide roles that will give a login access to a database, good example of this is the sysadmin role.
Setting a default database for the login doesn't give that login any permissions in the database.  You'll find that a login by default is in the public group, and that gives them so very low level access to master & tempdb.
You need to explicity grant access for a login to the database.  You do this with sp_adduser. If you create the users in Enterprise Manager then yes, the login name will match the user name, but it doesn't have to, the sproc allows you to set a different username.
This code sample demonstrates the difference:
SELECT USER  --database user
SELECT SYSTEM_USER  --login

I don't know about DB2, but Oracle does not have the concept of login's and user's.


Q: undefined reference yaml-cpp I'm on Manjaro Linux using gcc and codelite to compile my code.
It's a project with sfml and yaml-cpp in C++.
My GCC version is 4.9.2 (20150304)
GCC compiler flags are -pg;-g;-O0;-O2;-Wall;-std=c++14
My yaml-cpp version is 0.5.1-1
When I compile I have the followings errors:
/bin/sh -c '/usr/bin/make -j4 -e -f  "MyProject.mk"  all'
----------Building project:[ MyProject - Debug ]----------
/usr/bin/g++   -c  "/home/myuser/.codelite/MyProject/MyProject/sprite.cpp" -pg -g -O0 -O2 -Wall -std=c++14  -o ./Debug/sprite.cpp.o -I. -I/usr/include/
/usr/bin/g++   -c  "/home/myuser/.codelite/MyProject/MyProject/tile.cpp" -pg -g -O0 -O2 -Wall -std=c++14  -o ./Debug/tile.cpp.o -I. -I/usr/include/
/usr/bin/g++   -c  "/home/myuser/.codelite/MyProject/MyProject/main.cpp" -pg -g -O0 -O2 -Wall -std=c++14  -o ./Debug/main.cpp.o -I. -I/usr/include/
/usr/bin/g++   -c  "/home/myuser/.codelite/MyProject/MyProject/grid.cpp" -pg -g -O0 -O2 -Wall -std=c++14  -o ./Debug/grid.cpp.o -I. -I/usr/include/
/usr/bin/g++   -c  "/home/myuser/.codelite/MyProject/MyProject/loader.cpp" -pg -g -O0 -O2 -Wall -std=c++14  -o ./Debug/loader.cpp.o -I. -I/usr/include/
/usr/bin/g++  -o ./Debug/MyProject @"MyProject.txt" -L. -L/lib/  -lsfml-graphics -lsfml-window -lsfml-system -lsfml-network -lsfml-audio
./Debug/loader.cpp.o: in function « Mercenaries::Loader::Loader(std::string, std::vector<std::string, std::allocator<std::string> >) »:
/home/myuser/.codelite/MyProject/MyProject/loader.cpp:10: undefined reference to « YAML::LoadFile(std::string const&) »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::set_null() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:34: undefined reference to « YAML::detail::node_data::set_null() »
./Debug/loader.cpp.o: in function « YAML::Node::AssignNode(YAML::Node const&) »:
/usr/include/yaml-cpp/node/impl.h:270: undefined reference to « YAML::detail::memory_holder::merge(YAML::detail::memory_holder&) »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::mark_defined() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
./Debug/loader.cpp.o: in function « YAML::detail::memory_holder::create_node() »:
/usr/include/yaml-cpp/node/detail/memory.h:30: undefined reference to « YAML::detail::memory::create_node() »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::mark_defined() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
./Debug/loader.cpp.o:/usr/include/yaml-cpp/node/detail/node_ref.h:29: more undefined reference follow to « YAML::detail::node_data::mark_defined() »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::set_null() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:34: undefined reference to « YAML::detail::node_data::set_null() »
./Debug/loader.cpp.o: in function « YAML::Node::AssignNode(YAML::Node const&) »:
/usr/include/yaml-cpp/node/impl.h:270: undefined reference to « YAML::detail::memory_holder::merge(YAML::detail::memory_holder&) »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::mark_defined() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
./Debug/loader.cpp.o: in function « YAML::detail::memory_holder::create_node() »:
/usr/include/yaml-cpp/node/detail/memory.h:30: undefined reference to « YAML::detail::memory::create_node() »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::mark_defined() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
./Debug/loader.cpp.o: in function « YAML::detail::memory_holder::create_node() »:
/usr/include/yaml-cpp/node/detail/memory.h:30: undefined reference to « YAML::detail::memory::create_node() »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::mark_defined() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::set_null() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:34: undefined reference to « YAML::detail::node_data::set_null() »
/usr/include/yaml-cpp/node/detail/node_ref.h:34: undefined reference to « YAML::detail::node_data::set_null() »
./Debug/loader.cpp.o: in function « YAML::detail::memory_holder::create_node() »:
/usr/include/yaml-cpp/node/detail/memory.h:30: undefined reference to « YAML::detail::memory::create_node() »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::mark_defined() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
./Debug/loader.cpp.o:/usr/include/yaml-cpp/node/detail/node_ref.h:29: more undefined reference follow to « YAML::detail::node_data::mark_defined() »
./Debug/loader.cpp.o: in function « YAML::detail::node& YAML::detail::node_data::get<std::string>(std::string const&, boost::shared_ptr<YAML::detail::memory_holder>) »:
/usr/include/yaml-cpp/node/detail/impl.h:89: undefined reference to « YAML::detail::node_data::convert_to_map(boost::shared_ptr<YAML::detail::memory_holder>) »
./Debug/loader.cpp.o: in function « YAML::detail::memory_holder::create_node() »:
/usr/include/yaml-cpp/node/detail/memory.h:30: undefined reference to « YAML::detail::memory::create_node() »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::mark_defined() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::set_scalar(std::string const&) »:
/usr/include/yaml-cpp/node/detail/node_ref.h:35: undefined reference to « YAML::detail::node_data::set_scalar(std::string const&) »
./Debug/loader.cpp.o: in function « convert_to_node<std::basic_string<char> > »:
/usr/include/yaml-cpp/node/detail/impl.h:162: undefined reference to « YAML::detail::memory_holder::merge(YAML::detail::memory_holder&) »
./Debug/loader.cpp.o: in function « YAML::detail::memory_holder::create_node() »:
/usr/include/yaml-cpp/node/detail/memory.h:30: undefined reference to « YAML::detail::memory::create_node() »
./Debug/loader.cpp.o: in function « YAML::detail::node& YAML::detail::node_data::get<std::string>(std::string const&, boost::shared_ptr<YAML::detail::memory_holder>) »:
/usr/include/yaml-cpp/node/detail/impl.h:102: undefined reference to « YAML::detail::node_data::insert_map_pair(YAML::detail::node&, YAML::detail::node&) »
./Debug/loader.cpp.o: in function « YAML::detail::memory_holder::create_node() »:
/usr/include/yaml-cpp/node/detail/memory.h:30: undefined reference to « YAML::detail::memory::create_node() »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::mark_defined() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::set_null() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:34: undefined reference to « YAML::detail::node_data::set_null() »
./Debug/loader.cpp.o: in function « YAML::detail::memory_holder::create_node() »:
/usr/include/yaml-cpp/node/detail/memory.h:30: undefined reference to « YAML::detail::memory::create_node() »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::mark_defined() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::set_null() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:34: undefined reference to « YAML::detail::node_data::set_null() »

Loader.cpp
#include <yaml-cpp/yaml.h>
#include <fstream>
#include <iostream>
#include "loader.hpp"

namespace Mercenaries
{
    Loader::Loader(std::string config_path, std::vector<std::string> fields_list) : m_config_path(config_path), m_fields_list(fields_list)
    {
        m_config_file = YAML::LoadFile(m_config_path);
    }

    void Loader::parse_file()
    {
        // if the file exist
        if(!m_config_file.IsNull())
        {
            //the first node is the file
            YAML::Node current_node = m_config_file;

            // we get the next node
            YAML::Node node = move_into_node(current_node, "Grid");

            // get the data inside the node
            auto data = node;
        }
        else
        {
            // the file doesn't exist
            std::cout << "Failed to load " << m_config_path << " settings file.";
        }
    }

    YAML::Node Loader::move_into_node(YAML::Node current_node, std::string next_node)
    {
        YAML::Node node;

        // we verify that the node exist
        if(current_node[next_node])
        {
            node = current_node[next_node]; // get the value
        }
        else
        {
            // the node doesn't exist in the yaml file
            std::cout << next_node << " node is not found in " << m_config_path << " goal file";
        }

        return(node);
    }
}

Loader.hpp
#ifndef DEF_LOADER
#define DEF_LOADER

#include <yaml-cpp/yaml.h>

namespace Mercenaries
{
    class Loader
    {
        public:
            Loader(std::string config_path, std::vector<std::string> fields_list);
            void parse_file();
            YAML::Node move_into_node(YAML::Node current_node, std::string next_node);

        private:
            std::string m_config_path;
            YAML::Node m_config_file;
            std::vector<std::string> m_fields_list;
    };
}

#endif

Do you think that it's an yaml-cpp issue ?
Is there an error in my code that make it bug ?
Should I report it if it's a yaml issue ?

A: It looks like you're not linking to yaml-cpp; you need to add the argument -lyaml-cpp (to the command that begins /usr/bin/g++  -o ./Debug/MyProject).

A: If you are considering a CMakeLists.txt project ...
cmake_minimum_required(VERSION 3.10)
project(Test_yaml_cpp)

set(CMAKE_CXX_STANDARD 14)
# In case of third party library
#find_package(yaml-cpp PATHS ./thirparty/yaml-cpp/build)

# In case of installed library
find_package(yaml-cpp)
add_executable(yaml_exec main.cpp)
target_link_libraries(yaml_exec yaml-cpp)

In case of the third-party approach, the yaml-cpp library should be already built inside build folder and recommended by their documentation.

A: Try add following to your cmakelist:
find_package(PkgConfig REQUIRED)


Q: C# MySQL Connection problems I'm trying to connect a C# application (using Visual C# 2008 Express Edition) to a remote MySQL server. I have the drivers for this, but when I followed the tutorials (including adding the pooling and connection reset properties), I get an error that: Object reference not set to an instance of an object. I've included the two lines of code that should be making a connection. The error is thrown on the second line.
        MySqlConnection connect = new MySqlConnection("database=d*******;Data Source=mysql.netfirms.com;user id=*******;pwd=*****;pooling=false;connection reset=false");
        connect.Open();

A: I'd try setting the connection string outside of the constructor to help narrow down the issue:
MySqlConnection connect = new MySqlConnection();
//Do you get the null exception in this next line?
connect.ConnectionString = "your conn string here";
connect.Open(); //-> If you get the exception here then the problem is with the connection string and not the MySqlConnection constructor.

If you do get the exception in the connect.ConnectionString = ... line, then the problem is with the driver and sounds like you need to reinstall it.
I would also try a simpler connection string, without the pooling and reset keys.

A: Can you post more code? The exception line is probably a bit off due to compiler optimization or related. Constructors must return an object or throw an exception. It is impossible to say
MyType item = new MyType();
Debug.Fail(item == null); // will never fail.

The null reference is probably on the line just above your instantiation.


Q: Attempt to insert non-property list object Есть структура
struct Items {
    let photo: UIImage
    let descriptionText: String

init(photo: UIImage, descriptionText: String) {
    self.photo = photo
    self.descriptionText = descriptionText
}

}
Хочу вставить фото из PhotoLibrary в массив
var items:[Items] = []`
 В результате чего получаю такое исключение:

2019-07-03 21:58:59.681860+0600 WASH![13610:1879078] [User Defaults] Attempt to set a non-property-list object (
    "WASH_.Items(photo: >, descriptionText: \"eeeee\")"
) as an NSUserDefaults/CFPreferences value for key data
2019-07-03 21:58:59.685969+0600 WASH![13610:1879078] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to insert non-property list object (
    "WASH_.Items(photo: >, descriptionText: \"eeeee\")"
) for key data'

 Помогите
, пожалуйста, исправить проблему

A: Вы пытаетесь сохранить свою кастомную модель в UserDefaults, это нельзя сделать в лоб так просто.По умолчанию сохранять в UserDefaults можно объекты стандартных классов (String, Bool, Int и.т.п), и то там надо перегонять большую часть типов в NSNumber. Кастомные классы для сохранения должны реализовывать интерфейс NSCoding.
Вот пример реализации.
@objc(Language)
class Language: NSObject, NSCoding {

    var shortIndex: String?
    var languageName: String?

    override init() {
        super.init()
    }

    init(withShortIndex shortIndex: String, andLanugageName languageName: String) {
        super.init()
        self.shortIndex = shortIndex
        self.languageName = languageName
    }

    // MARK:Serialization via UserDefaults
    func encode(with aCoder: NSCoder) {
        aCoder.encode(self.shortIndex, forKey: "shortIndex")
        aCoder.encode(self.languageName, forKey: "languageName")
    }

    required init?(coder aDecoder: NSCoder) {
        super.init()
        self.shortIndex = aDecoder.decodeObject(forKey: "shortIndex") as? String
        self.languageName = aDecoder.decodeObject(forKey: "languageName") as? String
    }

    // Implement Equatable
    static func ==(lhs:Language, rhs:Language) -> Bool {
        return (lhs.shortIndex == rhs.shortIndex && lhs.languageName == rhs.languageName)
    }
}

Пример обращения:
let encodedLanguageFrom = defaults.object(forKey: "defaultLanguageTranslateFrom") as? NSData

        if (encodedLanguageFrom != nil)
        {
            let lang = NSKeyedUnarchiver.unarchiveObject(with: encodedLanguageFrom! as Data) as? Language
            if (lang != nil)
            {
                defaultLanguageTranslateFrom = lang;
            }
        }

Пример записи:
let encodedLanguageTranslateFrom = NSKeyedArchiver.archivedData(withRootObject: defaultLanguageTranslateFrom!)
defaults.set(encodedLanguageTranslateFrom, forKey: "defaultLanguageTranslateFrom")


Q: g:submitButton- onclick doesn't work I have the following g:submitButton:
 <g:submitButton name="next" class="signup-button skyblue-btn pull-right pl-pr-36" value="${message(code:"buttons.ok")}" onclick="return showSpinnerSignUp()"/>

I define the showSpinnerSignUp() in the JS file:
$(function() {
    function showSpinnerSignUp(){
        $('.spinner-ctn').show();
        return true;
    }
});

The spinner is not displayed (the onclick doesn't work).

A: This is the default behaviour of a form submission in the browser. You have registered a showSpinnerSignUp() method on the click of a button while the click on that same button is responsible for submitting the enclosing form.
Since the browser's built-in behavior for submitting forms works by making a full roundtrip to the server, that immediately interrupts your code execution of onclick event because your browser is navigating away from your current page.
This can be simulated as if you had clicked your button and refreshed the page immediately. Your current setup might work when you deploy this to the production server, but the possibility of working this setup locally is low because a local development server used to run on a faster machine  so the page refresh time of form submission is quite faster.
To verify this happening, open your browser's console and call the method showSpinnerSignUp() directly (remember to remove it from $(function() {}) temporarily) and see if the spinner is showing up.
Also, there is an option to Preserve Logs which keeps the Javascript console logs even after page refresh. So, put a simple console.log() inside your method call and then try hitting that button. You'll see your method is called but no spinner is displayed due to form submission.


Q: iPhone/iPod Touch: application executable contains unsupported architeture(s): armv7s i'im seeing a problem releasing on AppStore my App!
The validation process say: "iPhone/iPod Touch: application executable contains unsupported architeture(s): armv7s"
this is my library linked:
CoreLocation (required)
Twitter (optional)
QuartzCore (required)
MapKit (required)
UIKit (required)
Foundation (required)
CoreGraphics (required)
libGoogleAnalytics.a (required)
libsqlite3.dylib (required)
CFNetwork (required)
I've also tryed to remove GoogleAnalytics Library but the problem is the same! Do you have any idea?
Thanks

A: Based on discussions at the Apple dev forums (https://devforums.apple.com/message/749949) it looks like this is a bug affecting a lot of people.  Probably due to a change in Apple's validations servers.
I was able to work around it by changing the build architecture in Build Settings from Standard(armv7,armv7s) to armv7 and rebuilding.  This should only have the effect that the compiled code is not optimized for iPhone 5.  It will still run, but may not be quite as fast as if it were compiled for armv7s.  I suspect the performance difference would be negligible in most cases.

A: This helped me:

Project -> Build Settings -> remove the architecture from "valid
  architectures" as well as setting the "Build Active Architecture Only"
  to Yes in the Project

A: I had the same problem today. My app has no third-party libraries.
12 days ago I submitted a build from Xcode 4.5.1 that was subsequently reviewed and released to the App Store. Today I tried to submit a new build and suddenly received this error.
I then tried to validate the same executable (not a rebuild) from within Xcode that I had submitted 12 days ago and that had passed validation and is now available for download in the App Store, but this time it failed validation with the above error.
Performing step 4 above allowed me to submit the new build. But the executable is smaller even though I have added a small amount of code and three small png/jpegs. This makes me think that armv7s code is missing from the archive.
What is happening? Why should step 4 above 'work'? Why does an executable that previously submitted OK and was released suddenly no longer pass validation?
Note: this is not a duplicate of any previous post that I was able to find 15 hours ago. This is the first time I have seen any mention made of seeing this error when submitting to iTunes Connect rather than receiving a compiler warning. So please do not mark this as a duplicate. It is not.

A: Most of the answers here are ones that I did not find ideal, mainly because they essentially suggest that you remove armv7s support from your app. While that will make you app pass validation, that could potentially make your app run slower on the iPhone 5.
Here is the workaround I'm using (though, I must say that I wouldn't call this a solution).
Instead of using XCode Organizer, I'm uploading the binary using Application Loader.
To upload the binary using Application Loader
Open Organizer > Right Click on Archive > Reveal in Finder.
Right Click the Archive file > Show Archive Content
Go to Products > Application > YourAPP.app
Compress YourAPP.app and upload using Application Loader.

A: My problem was the fact I was using an old version of Application Loader.
The solution for me was to download the latest version of Application Loader iTunes Connect > Manage Your Applications > Download Application Loader and try again.

A: Try this:
1.Select your project in Xcode (with the blue icon)
2.Select Build Settings
3.Set the view to All/Combined
4.Set "Build Active Architecture Only" to Yes


Q: Is it possible to change the default WP post table's data source? I was wondering if there was a function to change the default MySQL data source (to JSON or REST data) for a post table without having to make a custom Wp_List_table?
I know how to make a custom WP LIST TABLE to run on JSON DATA, but I am want to just change the source tech.


Q: Appropriate usage I have always come across phrases like, 'have/take a seat'. Is it normal to say 'have the/this/that seat' or 'take the/this/that seat' while pointing at a particular seat?

A: "Take this seat" would be fine if you want the other person to sit in a specific seat; you might want to add a "please". If the choice of seat doesn't matter, or there is only one seat available, "take a seat" sounds more natural to me. Also, "take a seat" is a gesture to someone to have/take a seat so as to not keep him/her standing or it is considered an act of kindness.
Credit: nnnnnn


Q: Values from checkbox group are correct in querystring, but are not arrays in the $_GET variable I have a form, with a checkbox group which looks like this:
<input type="checkbox" name="countries" value="US" class="chkcountries" checked="checked" /> United States

<input type="checkbox" name="countries" value="FR" class="chkcountries" checked="checked" /> France

<input type="checkbox" name="countries" value="CA" class="chkcountries" checked="checked" /> Canada

<input type="checkbox" name="countries" value="AU" class="chkcountries" checked="checked" /> Australia

<input type="checkbox" name="countries" value="UK" class="chkcountries" checked="checked" /> United Kingdom

<input type="checkbox" name="countries" value="DE" class="chkcountries" checked="checked" /> Germany

<input type="checkbox" name="countries" value="Ja" class="chkcountries" checked="checked" /> Japan

<input type="checkbox" name="countries" value="IT" class="chkcountries" checked="checked" /> Italy

<input type="checkbox" name="countries" value="IN" class="chkcountries" checked="checked" /> India

<input type="checkbox" name="countries" value="ES" class="chkcountries" checked="checked" /> Spain

<input type="checkbox" name="countries" value="BR" class="chkcountries" checked="checked" /> Brazil

<input type="checkbox" name="countries" value="NL" class="chkcountries" checked="checked" /> Netherlands

<input type="checkbox" name="countries" value="MX" class="chkcountries" checked="checked" /> Mexico

When I select more than one country and run the form and print_r both the query string and the $_GET array, the querystring looks like this:

report=rawdata&sales=sales&kenp=kenp&startdate=&enddate=&format=table&track=unit&countries=US&countries=CA&countries=AU&countries=UK&allchannels=All&channels=2&channels=1&books=5&submit=Get+Report

and the $_GET array looks like this:

Array ( [report] => rawdata [sales] => sales [kenp] => kenp [startdate] => [enddate] => [format] => table [track] => unit [countries] => UK [allchannels] => All [channels] => 1 [books] => 5 [submit] => Get Report [SQLiteManager_currentLangue] => 2 )

As you can see, it's only selecting the last item in the countries array. (The same thing happens in checkbox groups on this form, e.g. channels).
I'm working in a test environment running MAMP on my Mac, FWIW.
What's weird is that it was working properly. (I've tried rebooting MAMP and then rebooting my entire system to see if that makes a difference, and it doesn't seem to.)
It's possible I've missed something dumb somewhere, but I've now been looking at it so long, I'm going cross-eyed. Any assistance would be greatly appreciated.

A: I think that you need to do an array for your select :
<select name="countries[]" multiple>

And then deal with the array in your php code.

A: PHP determines if form data should be presented as a string or an array based on the name of the field, not the number of times it appears.
Append [] to the name attribute in the HTML.


Q: How can I fire a jQuery event once getBlocks() actually returns the post's blocks instead of null? In the editor, I am trying to loop through all the current post's blocks as soon as everything is loaded and ready for me.
wp.data.select("core/block-editor").getBlocks();

is able to successfully get all the blocks if I call it manually (via a link/button), but I'd like to have it run automatically.
When that snippet is inside of domReady, a la
wp.domReady( function() {...

getBlocks always returns null.
I also tried using this Promise
wp.domReady( function() {

window._wpLoadBlockEditor.then( function() {
console.log( "_wpLoadBlockEditor Promise resolved" );

var blocks = wp.data.select("core/block-editor").getBlocks();
console.log( blocks );

});
} );
But even it returns null for blocks. It makes me wonder if the Promise is only for the Editor itself being ready; not the actual post content?
If I add a two second delay (via setTimeout), then getBlocks returns all my blocks. Obviously, I don't want to wait an arbitrary amount of time and hope everything is ready.  Is there some way I can ensure my script fires as soon as getBlocks() is ready to actually return the post's blocks?

A: You need to "subscribe" to changes (see this issue) with wp.data.subcribe.
A more modern version would have you use useSelect() to get the blocks. It will automatically update blocks if it changes (i.e. it will first return null, then an array of blocks once the API request completes).
import { useSelect } from '@wordpress/data';

const blocks = useSelect((select) => {
    return select('core/block-editor').getBlocks();
});

if (blocks && blocks.length > 0) {
    blocks.forEach((block) => {
        // Do whatever you want with the block
    });
}


Q: Import SQL File into existing DB-Table (phpmyadmin) I have an SQL-File defining a table with 2 columns - product-id and product-reference. I need to import that file into an existing table that has the same structure (plus some extra columns), where product-id corresponds to the product-id from the backup file. Is there a simple way to do that via phpmyadmin?

A: One approach is to use load data infile (see here) with the set option to assign column values.  Columns that are not being set will be given their default values, which is typically NULL.
Personally, I would load the data into a staging table with two columns and then insert the data from the staging table into the final table.  This makes it easier to validate the data before putting it into the "real" table.


Q: C++ gdb breakpooint in second thread causing core dump I have a C++ program I'm trying to debug in a new docker instance that is causing the program to crash when I try to hit a breakpoint in a created thread (but not the launch thread). Another version of the program run on a separate computer (different g++, gdb versions) works. I've created a test app to replicate the problem.
I'm using a ubuntu docker image (which is new to me). I've started a docker container with:
docker run -it -v "/home/test/":"/home/test" -w "/home/test" ubuntu

I've attached to this container in VS Code, in the /home/test/ folder. I've then installed g++ and gdb with: apt-get update then apt-get install g++ gdb.
This installs versions g++: 4:11.2.0-1ubuntu1 gdb: 12.0.90-0ubuntu1
I then create a main.cpp with the following code:
#include <iostream>
#include <chrono>
#include <thread>

void thread_runner()
{
    while (1) {
        std::cout << "Background Thread" << std::endl;                //Second Breakpoint
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    }
}

int main()
{
    std::cout << "Test App" << std::endl;                              // First Breakpoint
    std::thread ioc_thread = std::thread(thread_runner);                    // Create a separate (background) thread to run the io_context on
    ioc_thread.join();
}

And I set breakpoints on the 2 std::cout ... lines.
I create a tasks.json file to compile this, which looks like:
{
    "tasks": [
        {
            "type": "cppbuild",
            "label": "C/C++: g++ build active file",
            "command": "/usr/bin/g++",
            "args": [
                "-fdiagnostics-color=always",
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "options": {
                "cwd": "${fileDirname}"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": "build",
            "detail": "Task generated by Debugger."
        },
    ],
    "version": "2.0.0"
}

Then I run the command "Run and Debug" and use that task to compile. I hit the first breakpoint at "Test App" okay but it crashes before hitting "Background Thread", the terminal output is:
Test App
Aborted (core dumped)
[1] + Aborted (core dumped)      "/usr/bin/gdb" --interpreter=mi --tty=${DbgTerm} 0<"/tmp/Microsoft-MIEngine-In-mv2ltsxy.3ok" 1>"/tmp/Microsoft-MIEngine-Out-0zvvty3q.t43"

If I remove the second breakpoint the app runs printing "Background Thread" every second.
Apologies for the long winded description. I'm not sure where I'm going wrong so I looked to include everything. The other computer that appears to work (using my full original program) using g++ 9.3 and gdb 8.1.

A: I had a similar issue where my program would coredump when there was a breakpoint present in a thread. I found out that my instance of gdb (12.0.9) was not working, and installing 12.1 from launchpad fixed my issue.
Found solution here


Q: Azure giving subscription level resource group access to application I created a application in active directory and gave access to it at the resource group level and I am able to access the resources inside the resource group. But I don't see any option in preview portal to give access to the application at the subscription level.
When I am running the following code
ResourceManagementClient client =
testMain.createResourceManagementClient();
ResourceGroupOperations gpoperations = client.getResourceGroupsOperations();
ResourceGroup gp1 = new ResourceGroup("West US");
ResourceGroupCreateOrUpdateResult res = gpoperations.createOrUpdate("test123", gp1);
System.out.println("Resource group creation result" + res.getRequestId()+res.toString());

I am getting the following exception

Exception in thread "main"
  com.microsoft.windowsazure.exception.ServiceException:
  AuthorizationFailed: The client '2e027029-1019-46dc-b540-cbfe4a761647'
  with object id '2e027029-1019-46dc-b540-cbfe4a761647' does not have
  authorization to perform action
  'Microsoft.Resources/subscriptions/resourcegroups/write' over scope
  '/subscriptions/88335ad5-6fe2-4532-b3d5-1af946310f85/resourcegroups/test123'.
      at com.microsoft.windowsazure.exception.ServiceException.createFromJson(ServiceException.java:292)
      at com.microsoft.azure.management.resources.ResourceGroupOperationsImpl.createOrUpdate(ResourceGroupOperationsImpl.java:495)
      at com.mycompany.resourcegroup.testMain.main(testMain.java:70)

How can i give access to the application, so that it can create and manage any resource group in my subscription ?

A: *

*GO to your Azure Active Directory

*Click on Groups

*Click “+ New Group”

*Select the group type “Security”

*Enter group name (any name you want)

*Select Membership type “Assigned”

*In the owner select the owner of the application

*In the members select the application that you created/registered in the active directory.

*Now you are able to create your resources directly from your java client.


Q: CentOS 6 not displaying I installed CentOS on Oracle VirtualBox and it run perfectly fine on command line but then I installed desktop environment by typing the following command:
yum groupinstall "X windows system" "KDE Desktop", edit the initdefault id from 3 (command line) to 5 (GUI), save the file and reboot the system but it doesn't display the login screen, in fact it hangs on loading. . Please help me out in this.
I can't attach the image as the message pops up stating that i need at least 10 reputation to post images...
I will write down the last two lines when it hangs..
Starting postfix :      [OK]
Starting httpd:         [OK]
Starting crond:         [OK]

Thanks.

A: It seems that some yum commands are case sensitive (atleast install and groupinstall), so the correct command is
$ yum groupinstall "X Window System" "KDE Desktop"


Q: Select sub element based on classes it has Below is the HTML that I have

    See Stats

    See Stats

    See Stats

I want to find this unordered list, then tell which item has the starting qb class and then return the class that has their name (brady rodger manning) etc.
What's throwing me in a loop is the fact that the link is wrapped in the list element.
Here is what I am trying:
element = $("#qbs"); // pretty sure I want this vs getElementbyDocumentID
children = element.children();` // gets me all the list elements

for (i=0;i<children.length;i++) {
  grandchild = children[i].children();
  ???? How would I get the 3rd class on this element?
}

Sorry about the formatting.

A: How about this?
var allClasses = $("#QBS").find('li a[class^="qb_"]')
     .map(function () {
          return this.className.split(" ").pop();
}).get();
console.log(allClasses);

Fiddle
Provided the class started with qb_* is at the beginning and you want to take only the last class of the match.
if all your class names are qb_mode then:
var allClasses = $("#QBS").find('.qb_mode').map(function () {
    return this.className.split(" ").pop();
}).get();

if you want all of them then:
var allClasses = $("#QBS").find('.qb_mode').map(function () {
    var cls = this.className.replace(/qb_mode/,'');
    return cls.trim().split(/\W+/);
}).get();
console.log(allClasses);

Fiddle

A: If I understood you correctly, how about:
var name = $('#QBS a.qb_mode.starting').prop('class').replace(/\s*(qb_mode|starting)\s*/g,'');
console.log(name); // Rogers

See demo here.

A: a=document.getElementById('QBS');
var b=a.getElementsByClassName("qb_mode");
var i, j=b.length, result=[];
for(i=0;i<j;i++) {
  c=b[i].className.split(" ");
  result.push(c.pop());
}
return result;

A: fiddle http://jsfiddle.net/3Amt3/
var names=[];

$("#QBS > li a").each(function(i){
    var a=$(this).attr("class").split(" ");
    names[i]=a[(a.length-1)];
    console.log("Name  is " + names[i]);
 });

or a more precise selector
 $("#QBS > li a.qb_mode").each( ....


Q: How to fetch with method GET And Type script I'm true beginner with type script
can you help me with this simple fetch
this is function
export async function askForList(){
   return await fetch('http://127.0.0.1:3333/applist').then((res) => res.json())
}

this is expected data
interface RnMcharacter{
    id: number,
    img: string,
    name: string,
    number: number
};

I'v tried many combination but moast common error is
ERROR in src/transmission/apiserv.ts:27:4
@typescript-eslint/no-unsafe-return: Unsafe return of an any typed value.
Can you show me example of proper function so I can understad what mi doing wrong.
Thx

A: You can type the data prop as RnMcharacter.
You can also remove the then call as you're using async|await
export async function askForList(){
  const res = await fetch('http://127.0.0.1:3333/applist');
  const { data }: { data: RnMcharacter } = await res.json();
  return data;
}


Q: Akka cluster error Is it mandatory to use sbt for cluster usage in akka. I have tried to add a few jars to the classpath. While the compiling goes well, running the relevant class generates an error.

scala -cp
  ../akka-2.2.1/lib/akka/akka-cluster_2.10-2.2.1.jar:../akka-2.2.1/lib/akka/netty-3.6.6.Final.jar:../akka-2.2.1/lib/akka/akka-remote_2.10-2.2.1.jar:../akka-2.2.1/lib/akka/protobuf-java-2.4.1.jar:./
  TransformationFrontend 2551

here's the issue encountered:

java.lang.NoSuchMethodException:
  akka.cluster.ClusterActorRefProvider.(java.lang.String,
  akka.actor.ActorSystem$Settings, akka.event.EventStream,
  akka.actor.Scheduler, akka.actor.DynamicAccess)   at
  java.lang.Class.getConstructor0(Class.java:2800)  at
  java.lang.Class.getDeclaredConstructor(Class.java:2043)

This is the official Akka cluster example. Can someone throw some light on my query?

A: The issue here is probably that you have an akka-actor.jar in your scala distributuion that is Akka 2.1.x and you're trying to use Akka 2.2.x.
You'll have to run your code by running the java command and add the scala-library.jar and the correct akka-actor.jar and typesafe-config.jar to the classpath.

A: Are you using Scala 2.10? This is the Scala version you need for Akka 2.2.
What does the following yield?

scala -version

It should show something like

$ scala -version
Scala code runner version 2.10.3 -- Copyright 2002-2013, LAMP/EPFL


Q: How do you reset firefox without losing your bookmarks/logins? I've been getting these black-background text popups in the upper right corner when I have firefox running (they appear even when minimized) and when I click on them it takes me to pages. I'm not sure why this happens. I have 2 Extensions (Image Search Options from saucenao.com and https://github.com/bijij/ViewImage ) and 2 Plugins (OpenH264 Video Codec provided by Cisco Systems, Inc and Widevine Content Decryption Module provided by Google Inc.) so I don't know if any of these might have a reputation. They vanish on their own so it's hard to get a screenshot in time.
What seemed to fix it last time was:

delete your ~/.mozilla folder and ./config/mozilla/  and restart FF
  you just lose all plugins/malware/data
  this ~/. is just user data

This worked but I lost my bookmarks and logins so I'm wondering if anyone knows how to back that up ahead of time so I can add it back after deleting these folders.

A: Click the Bookmarks button (underlined ☆) in the top right corner and select Show All Bookmarks to open the Library window. From the toolbar on the Library window, click Import and Backup and choose Export Bookmarks to HTML.... In the window that opens, choose a location to save the file, which is named bookmarks.html by default and click the Save button.
To import the saved bookmarks back into Firefox follow the same navigation as above only select Import Bookmarks from HTML... instead of Export Bookmarks to HTML.... Don't delete the bookmarks.html file even after you are finished using it, because it is also useful for importing your Firefox bookmarks into other web browsers.

A: Try refreshing Firefox instead of deleting its config files.


Q: actionscript facebook get url of uploaded image using the latest facebook actionscript library, I upload an image using:
Facebook.api('me/photos', etc...)
it returns an ID, which method would I call to get the url of the uploaded image?
Thanks.

A: Looks like it's a simple REST service call:  https://graph.facebook.com/10150146071831729
Take a look at the "Example" at the bottom of this page:  https://developers.facebook.com/docs/reference/api/photo/


Q: My worker threads are not being picked up I'm implementing worker threads in my Node/Typescript application. Now I've come quite far except for the fact that it seems my worker threads are not being picked up/executed. I've added some loggers inside function which should be executed by the worker thread, but for some reason it doesn't show.
I'm calling a function to create a worker. Like this:
create_worker("./src/core/utils/worker.js", {
        term: "amsterdam",
        search_grid: chunked_maps_service![i],
        path: "../../adapters/worker.ts",
})

And this is the function to create a worker:
import { Worker } from "worker_threads";

const create_worker = (file: string, workerData: {}) =>
  new Promise<void>((resolve, reject) => {
    const worker = new Worker(file, {
      workerData: workerData,
    });

    worker.on("message", resolve);
    worker.on("error", reject);
    worker.on("exit", (code) => {
      if (code !== 0)
        reject(new Error(`Worker stopped with exit code ${code}`));
    });
  });

export default create_worker;

Because I'm using typescript I need to compile the typescript code to javascript code to make the worker understand it: Like this:
const path = require("path");
const { workerData } = require("worker_threads");

require("ts-node").register();
require(path.resolve(__dirname, workerData.path));

And then this is the function which should be executed in the worker thread:
import { parentPort } from "worker_threads";

async function worker() {
  console.log("started");
  parentPort.postMessage("fixed!");
}

Is there anything I'm forgetting?

A: You aren't ever calling the function in your worker.
This code in the worker:
import { parentPort } from "worker_threads";

async function worker() {
  console.log("started");
  parentPort.postMessage("fixed!");
}

Just defines a function named worker.  It never calls that function.
If you want it called immediately, then you must call it like this:
import { parentPort } from "worker_threads";

async function worker() {
  console.log("started");
  parentPort.postMessage("fixed!");
}

worker();

FYI, in the worker implementations I've built, I usually either execute something based on data passed into the worker or the worker executes something based on a message it receives from the parent.


Q: Issues with validation in rails I have a working validation on my user model. But since we're discovered that users tend to give up during their long registration form, we've split up registration form into steps so that user can give up any time and still use the site.
I'm having issues with the first step of user registration with validations. Here is the relevant bit of my User model :
with_options :if => lambda { |u| u.current_step == "get_started" } do |user|
    user.validates :firstname, presence: true, length: { maximum: 50 }
    user.validates :surname, presence: true, length: { maximum: 50 }
    user.validates :email, presence:   true,
              format:     { with: VALID_EMAIL_REGEX }

    user.validates :password_digest, presence: true
    user.validates :password, length: { minimum: 6 }
end

This validation works perfectly. However we now added facebook so its possible to login with facebook and we have hidden fields in our form facebook_uid. So I want to validate password only if these fields are nil.
Here is how I tried to modify my current validation :
with_options :if => lambda { |u| u.current_step == "get_started" } do |user|
   user.validates :firstname, presence: true, length: { maximum: 50 }
   user.validates :surname, presence: true, length: { maximum: 50 }
   user.validates :email, presence:   true,
        format:     { with: VALID_EMAIL_REGEX }

   with_options :if => lambda { |u| u.facebook_uid.nil? } do |user|
     user.validates :password_digest, presence: true
   end

   with_options :if => lambda { |u| u.user.password_digest_changed? && !u.password.nil? } do |user|
    user.validates :password, length: { minimum: 6 }
   end
end

Or inline (the relevant password part only) :
user.validates :password_digest, presence: true, if: lambda { |u| u.facebook_uid.nil? }
user.validates :password, length: { minimum: 6 }, if: lambda { |u| u.user.password_digest_changed? && !u.password.nil? }

None of these worked for me, whatever I tried I get this error :
undefined method `user' for #<User:0x00000008e924a8>

Again if I remove ifs and lambdas works as charm. Is there another way of accomplishing this or something I'm currently doing wrong with my code?

A: In your password validation lambda, you're calling
u.user.password_digest_changed? && !u.password.nil?

ie, you're sending a user method to the u object, which is your User instance. That object doesn't respond to user. You probably just want
u.password_digest_changed? && !u.password.nil?


Q: If $K\subset{\mathbb{R}}$ closed and bounded, then K compact Proof (without covers) I have already proved the reverse (Heine-Borel Theorem) by use of the Bolzano Weierstrass Theorem, but, reading several proofs of this forward direction, am yet to come across a (short) proof which shows this without the need for open covers - note, here I define a compact set to be a subset $K\subset{\mathbb{R}}$ such that every sequence in $K$ has a subsequence that converges to a limit that is also in $K$ Could someone please show thus this forwards direction (closed and bounded, then compact) without resorting to open covers (not for lack of knowledge, but as covers appear on the next page of this theorem in the book I'm studying).

A: Let $ x_n $ be a sequence in $ K $, which is a closed and bounded subset of $ \mathbb R $. It is a well known property of $ \mathbb R $ that any sequence has a monotone subsequence, so let $ x_{k_n} $ be a monotone subsequence. Then $ x_{k_n} $ is a monotone, bounded (as $ K $ is bounded) sequence in $ \mathbb R $. By the least upper bound property of $ \mathbb R $, $ x_{k_n} $ converges to some $ x \in \mathbb R $. Then as $ K $ is closed and $ x_n $ is a sequence in $ K $, $ x \in K $, which shows compactness of $ K $.

A: Let $(x_n)_{n \geq 1} \subseteq K$. Since $K$ is bounded, so is this sequence. By Bolzano-Weierstraß, there exists a convergent (in the whole space) subsequence $(x_{n_j})_{j \geq 1}$. Since $K$ is closed, this subsequence converges in $K$.


Q: error: invalid arch-independent ELF magic I had a Ubuntu guest OS(18.04) running on Windows 7. I upgraded my host OS to Windows 10. After installing the same Virtual Box software my Ubuntu OS didn't boot.
it shows:
error: invalid arch-independent ELF magic.
Entering rescue mode...
grub rescue>


Q: Navigation Drawer does not cover an activity I am writing an organiser app and I am stuck at this problem. Navigation drawer stacks itself with the listview in activity 1 . There is no exception and the app is working, but the listview elements and navigation drawer elements are clicked at the same time.
Here is the activity layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context=".EventActivity">

<androidx.drawerlayout.widget.DrawerLayout
    android:id="@+id/my_drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    tools:ignore="HardcodedText">

  <com.google.android.material.navigation.NavigationView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:menu="@menu/navigation_menu" />

</androidx.drawerlayout.widget.DrawerLayout>

<ListView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/list"/>

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="20dp"
    android:layout_alignParentEnd="true"
    android:layout_alignParentBottom="true"
    />

</RelativeLayout>

A: DrawerLayout should be the parent of your layout. Here`s my example:
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout 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:id="@+id/mDrawer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="false"
    tools:openDrawer="end">

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
   >
    //my code

</androidx.constraintlayout.widget.ConstraintLayout>

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/navrapoarte"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="start"

      >
    //my code
        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:minHeight="200dp"
            android:orientation="vertical">

        </androidx.constraintlayout.widget.ConstraintLayout>

    </com.google.android.material.navigation.NavigationView>
</androidx.drawerlayout.widget.DrawerLayout>


Q: Click “Accept Cookies” popup with Selenium in Python I've been trying to scrape some information of this E-commerce website with selenium. However when I access the website I need to accept cookies to continue. This only happens when the bot accesses the website, not when I do it manually. When I try to find the corresponding element either by xpath, as I find it when I inspect the page manually I always get this error message:

selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document

My code is mentined below.
import time
import pandas
pip install selenium
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
from bs4 import BeautifulSoup #pip install beautifulsoup4

PATH = "/Users/Ziye/Desktop/Python/chromedriver"
delay = 15

driver = webdriver.Chrome(PATH)
driver.implicitly_wait(10)

driver.get("https://en.zalando.de/women/?q=michael+michael+kors+taschen")
driver.find_element_by_xpath('//*[@id="uc-btn-accept-banner"]').click()

This is the HTML corresponding to the button "That's ok". The XPATH is as above.
<button aria-label="" id="uc-btn-accept-banner" class="uc-btn uc-btn-primary">
                          That’s OK
                      </button>

Does anyone know where my mistake lies?

A: You should add explicit wait for this button:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

driver = webdriver.Chrome(executable_path='/snap/bin/chromium.chromedriver')
driver.implicitly_wait(10)

driver.get("https://en.zalando.de/women/?q=michael+michael+kors+taschen")
wait = WebDriverWait(driver, 15)
wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="uc-btn-accept-banner"]')))
driver.find_element_by_xpath('//*[@id="uc-btn-accept-banner"]').click()

Your locator is correct.
As css selector, you can use .uc-btn-footer-container .uc-btn.uc-btn-primary


Q: Inverse process of :keys destructuring: construct map from sequence The more I write in Clojure, the more I come across the following sort of pattern:
(defn mapkeys [foo bar baz]
   {:foo foo, :bar bar, :baz baz})

In a certain sense, this looks like the inverse process that a destructuring like
(let [{:keys [foo bar baz]}] ... )

would achieve.
Is there a "built-in" way in Clojure to achieve something similar to the above mapkeys (mapping name to keyword=>value) - perhaps for an arbitrary length list of names?

A: No such thing is built in, because it doesn't need to be. Unlike destructuring, which is fairly involved, constructing maps is very simple in Clojure, and so fancy ways of doing it are left for ordinary libraries. For example, I long ago wrote flatland.useful.map/keyed, which mirrors the three modes of map destructuring:
(let [transforms {:keys keyword
                  :strs str
                  :syms identity}]
  (defmacro keyed
      "Create a map in which, for each symbol S in vars, (keyword S) is a
  key mapping to the value of S in the current scope. If passed an optional
  :strs or :syms first argument, use strings or symbols as the keys instead."
    ([vars] `(keyed :keys ~vars))
    ([key-type vars]
       (let [transform (comp (partial list `quote)
                             (transforms key-type))]
         (into {} (map (juxt transform identity) vars))))))

But if you only care about keywords, and don't demand a docstring, it could be much shorter:
(defmacro keyed [names]
  (into {}
        (for [n names]
          [(keyword n) n])))

A: I find that I quite frequently want to either construct a map from individual values or destructure a map to retrieve individual values.  In the Tupelo Library I have a handy pair of functions for this purpose that I use all the time:
(ns tst.demo.core
  (:use demo.core tupelo.core tupelo.test))

(dotest
  (let [m {:a 1 :b 2 :c 3}]
    (with-map-vals m [a b c]
      (spyx a)
      (spyx b)
      (spyx c)
      (spyx (vals->map a b c)))))

with result
; destructure a map into values
a => 1
b => 2
c => 3

; construct a map
(vals->map a b c) => {:a 1, :b 2, :c 3}

P.S.  Of course I know you can destructure with the :keys syntax, but it always seemed a bit non-intuitive to me.


Q: Is there .exe package of apache tomcat somewhere? I only see binary packages on apache website. Where can I find windows installer? I downloaded old version from some user of code.google.com, but that's definitely not the way they distribute it. I believe that I am just not seeing obvious things best then there is no tomcat installers in whole web. What I am doing wrong? Desperate already =)

A: You can download the Windows Service Installer for Tomcat 7 from this link. The link is taken from this page.
For Tomcat 8, look here.