text:
Q: DATALENGTH() or ISNULL() to retrieve fields that are not null and not empty Quite simply, which of the following methods is better in a WHERE clause to retrieve records where the FIELD_NAME is NOT NULL and NOT Empty
WHERE DATALENGTH(FIELD_NAME) > 0

or
WHERE ISNULL(FIELD_NAME, '') <> ''

Update
I have been informed that the first method gives spurious results for some types of fields... Agree?

A: Firstly,
select *
from table
where column <> ''

will give exactly the same results as
select *
from table
where isnull(column, '') <> ''

because records where the condition is UNKNOWN rather than FALSE will still be filtered out. I would generally go with the first option.
DATALENGTH counts trailing spaces, which a comparison with '' does not. It is up to you whether you want ' ' to compare unequal to ''. If you do, you need DATALENGTH. If you don't, simply compare with ''.
Note that for TEXT/NTEXT types, comparisons are not supported, but DATALENGTH is.

A: ISNULL is the best approach instead of DATALENGTH.

A: I would use
WHERE ISNULL(FIELD_NAME, '') <> ''

One issue that might come up is that a record with a space in it would not be returned. Are you looking for records like that?
I'm not sure about unexpected results from DATALENGTH. I would use the ISNULL method so that SQL Server doesn't need to spend time calculating the length of the record being compared. I don't know the performance difference between the two, just a gut feeling.

A: I would use one of the following:
where coalesce(field_name, '') <> ''

or
where field_name <> '' or field_name is not null

or
where field_name <> ''

The first is standard SQL (coalesce() is standard, isnull() is not).  The last is not the most obvious, but NULL will fail the comparison and it allows the use of indexes.

A: if your "not empty" condition encompasses  spaces then i would use the nullif
select case when nullif('  ', '') is null then 'y' else 'n' end
y

declare @d varchar(50)
set @d = null
select case when nullif(@d, '') is null then 'y' else 'n' end
y

A: RTRIM(LTRIM(ISNULL(FIELD_NAME, ''))) <> '' will handle spaces and NULLS


text:
Q: Working with big size drawable and custom views in Android I know this has been discussed over and over again but I  can't find a solution to suit my needs.
Scenario:  To keep the explanation simple, I have a custom view which displays two images a big one for the background and a smaller one as a Wheel. The user can rotate/scale the background image with onTouch events. He also can rotate the Wheel image to make some operations. Everything is done on a custom View not SurfaceView because I need it to be transparent.
The problem: With onDraw() I always need to check what Rotation/Scale has the background image, scale/rotate it and then draw it. If the background image is smaller, let's say 512x512 the Wheel image rotation is fine. If the background image is bigger, 1280x1707, the wheel image rotation is laggy. So my guess is, manipulation and rotation of a big image in background, for each onDraw() gives me performance issues, when basically the background image should be redrawn only the the user manipulates it.
The rotation is done in something like:
    canvas.save();
    float dx = (maxX + minX) / 2;
    float dy = (maxY + minY) / 2;
    drawable.setBounds((int) minX, (int) minY, (int) maxX, (int) maxY);
    canvas.translate(dx, dy);
    canvas.rotate(angle * 180.0f / (float) Math.PI);
    canvas.translate(-dx, -dy);
    drawable.draw(canvas);
    canvas.restore();

Possible solutions: I could make a new custom View which could only draw the background image and on top of it, put my current View and send touch events, when the case to my background image view. This will allow me to redraw the background image only when needed. Any other ideas ?

A: I was having similar performance problems and the solution I found is what I described here. Similar to what you already suggested, basically the background is only drawn once and the custom ImageView handles all transformations on its touch events.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to add email attachment to strapi provider email nodemailer I'm trying to send a confirmation email with attachments with strapi-provider-email-nodemailer. The plugin clearly supports attachments, but I don't know where in the strapi backend am I suppose to add these attachments. Does anyone know how to add attachments to an email sent via strapi-nodemailer?

A: In the end the solution was quite complicated. Probably there is an easier, undocumented way to do this with Strapi, but I don't know it.
In the end, I had to create an whole new API according to the quick start guide, so create a new content type 'Register' and create my own custom controller and service that uses the strapi.plugins['email'] and strapi.plugins[users-permissions].
Strapi automatically generates the models and documentations and routes for you, but you gotta edit the controllers and services.
register/config/routes.json
{
      "method": "POST",
      "path": "/registers",
      "handler": "Register.create",
      "config": {
        "policies": [],
        "description": "Register a user"
      }
    },

register/controllers/Register.js
module.exports = {
  create: async ctx => {
    try {
      let addUser = await strapi.services.register.registerUser(
        ctx.request.body
      );
      let sendEmail = await strapi.services.register.sendEmail(
        ctx.request.body
      );
      ctx.send({
        user: addUser,
        email: sendEmail
      });
    } catch (err) {
      console.log(err);
    }
  }
};

register/services/Register.js (make sure there is an image in the public folder)
'use strict';
const path = require('path');

module.exports = {
  registerUser: async data => {
    let result = await strapi.plugins['users-permissions'].services.user.add({
      username: data.username,
      email: data.email,
      password: data.password
    });
    return result;
  },
  sendEmail: async data => {
    console.log(__dirname);
    let result = await strapi.plugins['email'].services.email.send({
      to: data.email,
      from: 'whatever@whatever.com',
      replyTo: 'whatever@whatever.com',
      subject: 'Use strapi email provider successfully',
      text: 'Hello world foo!',
      html: 'Embedded image: <img src="cid:my_logo@nodemailer.com"/>',
      attachments: [
        {
          filename: 'surmile_logo.PNG',
          path: path.join(
            __dirname + '/../../../public/uploads/my_logo.png'
          ),
          cid: 'my_logo@nodemailer.com'
        }
      ]
    });
    return result;
  }
};

Then strapi build and strapi start
Make a POST to http://localhost:1337/registers
with json body
{
  "username": "sausage",
  "email": "blah@gmail.com",
  "password": "123456"
}

Make sure that you grant permissions for everyone to access the route in the admin panel

Make sure your client is properly configured


text:
Q: How to slow down a rotation animation with CSS? I have a spinning keyframe to spin this world image:
@keyframes App-world-spin {
    from {
        transform: rotate(0deg);
    }
    to {
        transform: rotate(360deg);
    }
}

which is called by this:
.App-world {
    animation: App-world-spin infinite 20s linear;
    height: 200px;
}

Which produces this:

I want to slow it down so as to produce a more realistic speed at which the world turns.

A: Change 20s to 200s(econds), for example:
animation: App-world-spin infinite 200s linear;

The 200s tells the browser to animate the element for 200 seconds.  So it will take 200 seconds for it to complete a full rotation.  Of course the Earth takes longer so adjust for your purpose :)


text:
Q: How do I update model value in javascript from asp.net core view I am trying to drag and drop child entities (unit) to different parents (user). How can I access the corresponding child entity and update its parent in the javascript drop event?
@foreach (var user in Model.Users)
{

Units

                @foreach (var unit in user.Units)
                {

@unit.Id

                }

}

The variable "data" is not accessible like this, and I don't know if I can call into @Model in the first place.

A:
I don't know if I can call into @Model in the first place.

You cann't do that directly. The@Model.Units.First(u => u.Id == data).OwnerId = ev.target.parentElement.parentElement.ID; runs on server side. Before someone drags & drops the
 element, the server side code has already been executed (rendered). It's not possible to make them run on client side.
To achieve your goals, you need send a HTTP request to the server when someone drags & drops the
 element. In order to avoid too much HTTP requests, you could create a modelCache variables that stores the Unit-Owner map, and changes this modelCache in drop(ev) function:

Finally, you'll need a server side action/handler to receive the ajax request:
IActionResult UpdateUnitOwner(List<UnitOwnerMap> maps)
{
    // ...  update the databse
}

In this way, you could update the Unit-Owner relationship by simply dragging and dropping.


text:
Q: How can I write if and else statement in twig I want to make an if statement in twig.
I have this html:
  <input id="price" data-slider-id='priceSlider' type="text"
                                                             data-slider-min="10000" data-slider-max="50000"
                                                             data-slider-step="2000" data-slider-value="{{ app.request.get('price') }}"
                                                             data-slider-handle="square"/>

I want to write something like this:
if({{ app.request.get('price') }})  data-slider-value="{{ app.request.get('price') }}"
else  data-slider-value="10000"

How can I do this in twig?

A: {% if app.request.get('price') is defined %}
    data-slider-value="{{ app.request.get('price') }}"
{% else %}
    data-slider-value="10000"
{% endif %}

twig if-else documentation

A: Adding 3rd variant:
{% set sliderVal = app.request.get('price') is defined ? app.request.get('price') : 10000 %}
data-slider-value="{{ sliderVal }}"

A: Use:
data-slider-value="{{ app.request.get('price') is defined  ? app.request.get('price'):"10000" }}"

twig defined


text:
Q: Почему не вводятся данные в масив char (память выделялась динамически) , язык С Объясните, пожалуйста, почему не вводятся данные (символы) в массив char (память под него выделялась динамически). С массивом int все работает. Массив int:
#include <stdio.h>
#include <conio.h>
#include <locale.h>
#include <malloc.h>
#include <process.h>

void big_init(int**,int);

void main(){
    setlocale(LC_CTYPE, "Russian");
    int *a;
    int n;
    system("cls");
    puts("Введите длинну массива");
    scanf_s("%d",&n);
    big_init(&a,n);
    for(int i=0;i<n;i++){
        puts("Заполните массив");
        scanf_s("%d",a+i);
    }
    printf(" [%d ] \n",*(a+0));
}

void big_init(int**arr,int sz){
    *  arr=(int  * )calloc(sz,sizeof(int));
    if(arr==0){
        puts("Ошибка");
    }
}

А массив char не работает:
#include <stdio.h>
#include <conio.h>
#include <locale.h>
#include <string.h>
#include <malloc.h>

void new_arr (char **,int);

void main(){
    setlocale(LC_CTYPE,"Russian");
    int n;
    char *arr;
    puts("Введите длинну массива:");
    scanf_s("%d",&n);

    new_arr(&arr,n);
    gets(arr);  // эту строчку компилятор пропускает
    puts(arr);  //и эту строчку  пропускает тоже
}
void new_arr(char **arr,int n ){
    *  arr=(char * )calloc(n,sizeof(char));
    if(arr==NULL){
        puts("Ошибка");
    }
}

A: 99% за то, что вы вводите число и нажимаете Enter. При считывании scanf выбирает из потока цифры, встречает \n, понимает, что чсло кончилось... оставляет \n в потоке. Затем gets читает \n, и полагает, что введена пустая строка...
Так что если предполагается раздельный ввод числа и строки - то рекомендовал бы после считывания строки игнорировать все последующие символы до \n включительно.

A: Ваш код вполне успешно работает в Visual C. Вероятно проблема в том, как Вы задаете входные данные. Нужно передавать число и сразу же за ним строку (без пробелов и переводов строки), например: 20hello.
При этом в коде имеется ошибка: проверка результата выполнения calloc должна выглядеть иначе:
if(*arr==NULL){ // Добавлено разыменование

P.S. Вопрос о разумности использования gets оставлю за рамками текущего ответа.


text:
Q: Timer not executing which defined under UtilityClass constructor I would like to execute a C# method every 10 sec and I am using in a  UtilityClass class constructor, but method is not executing and I'm not getting any output.
class Program
{
    static void Main(string[] args)
    {
        UtilityClass utilityClass = new UtilityClass();
    }
}

public class UtilityClass : IDisposable
{
    private readonly System.Timers.Timer _Timer;

    public UtilityClass()
    {
        _Timer = new System.Timers.Timer(TimeSpan.FromSeconds(10).TotalMilliseconds);
        _Timer.Elapsed += (sender, eventArgs) =>
        {
            ExecuteEvery10Sec();
        };
    }

    private void ExecuteEvery10Sec()
    {
        Console.WriteLine($"Every 10 sec all at {DateTime.Now}");
    }

    public void Dispose()
    {
        _Timer.Dispose();
    }
}

A: There are two problems: one - the program immediately terminated, so the timer is destroyed. You should wait to something. For example, waiting 10 minutes:
class Program
{
    static void Main(string[] args)
    {
        using (UtilityClass utilityClass = new UtilityClass()) // To dispose after the use
        {
            System.Threading.Thread.Sleep(10000 * 60); // Waits X milliseconds
        }
    }
}

Edit:
You also can to execute an infinite loop, so the ser exit onlyy by the X button of the console (or by Ctrl+C). So:
class Program
{
    static void Main(string[] args)
    {
        using (UtilityClass utilityClass = new UtilityClass()) // To dispose after the use
        {
            while (true) { }
        }
    }
}

two - You should start the timer, by setting its Enabled property to true:
public class UtilityClass : IDisposable
{
    private readonly System.Timers.Timer _Timer;

    public UtilityClass()
    {
        _Timer = new System.Timers.Timer(TimeSpan.FromSeconds(10).TotalMilliseconds);
        _Timer.Enabled = true;
        _Timer.Elapsed += (sender, eventArgs) =>
        {
            ExecuteEvery10Sec();
        };
    }

    private void ExecuteEvery10Sec()
    {
        Console.WriteLine($"Every 10 sec all at {DateTime.Now}");
    }

    public void Dispose()
    {
        _Timer.Dispose();
    }
}


text:
Q: Why do I need to use class- instead of instancevariable here? Simple code, counting the number n in a given array, but I get an error which tells me to change my instancevariable to static.
public class Test{

   int []arr = {4, 21, 4};
   Counter c = new Counter();

   public static void main(String[] args) {
      System.out.println(c.counter(4, arr));
   }
}

public class Counter {

   public int counter(int n, int []ar){  //tried to change method to static - didn't help
       int counter = 0;
       for(int i = 0; i < ar.length; i++){
           if(n == ar[i]){
               counter++;
           }
       }
       return counter;
   }
}

The error appears in line 7: change int [] arr and Counter c to static.
Tried to make the counter method static but still it tells me to change my array to static. What's the reason?

A: You are referring the two variables from the inside of a static function, they need to be static themselves to avoid errors.
A static method is one that can be invoked without an object of the class. That means that there is no this reference and no instance variable allocated to access. Static variables, instead, are allocated when the class is loaded and are available to both static and non-static method.
In yout code, the problem is that you try to access the variable from inside the main method, which is always static.

A: The main method is in a static context, isn't it? Your array and counter declared in Test are not static.

You can never directly access non-static members in a static context.

That is why the IDE is suggesting that you make the fields static.
Changing the counter method to static doesn't really solve the problem because you are still trying to directly access arr in a static context.
Another way to fix this is to make both c and arr local variables:
public static void main(String[] args) {
    int []arr = {4, 21, 4};
    Counter c = new Counter();
    System.out.println(c.counter(4, arr));
}

A: A program's main method must not be tied to an instance of the class, so it's defined as static.
arr and c are declared as instance variables of Test, so they are members of each instance of that class. No such instance exists within the scope of the main method.
Any identifiers used in a static method must be one of:
a) static members of the same class
b) local variables, declared within the method
c) in the global namespace (e.g. another class's static member, like Math.pi)
The easiest solution is to simply move the definitions of arr and c inside the main method.  There's no reason for them to be members of the class given your usage.
public class Test{

    public static void main(String[] args) {
        int []arr = {4, 21, 4};
        Counter c = new Counter();
        System.out.println(c.counter(4, arr));
    }
}

If you need them to be members of the class, you can simply change your original code to make them static (i.e. static int []arr = {4, 21, 4};)
A more flexible solution might involve using command line arguments to specify the values, or if you want to use instance variables, instantiating the class inside the main method:
public class Test{

    int []arr = {4, 21, 4};
    Counter c = new Counter();

    public static void main(String[] args) {
        Test t = new Test();
        System.out.println(t.c.counter(4, t.arr));
    }
}

But ^ this is kind of gross.


text:
Q: Can we redirect a user into a VF page from an Apex trigger I have a scenario where a user if he/she uploads a file against a particular record, then the user will be redirected to a VF page after the file upload is successful.
I wrote a simple trigger in which I am redirecting to a VF page. The code is as following :-
  trigger CheckAttachmentName on ContentDocumentLink (after insert) {
    if(trigger.isAfter) {
        if(trigger.isInsert) {
            system.debug('test line');
            //pageReference pdf = Page.ss;
            //pdf.setRedirect(true);
            //PageReference pageRef = new PageReference('/apex/ss');
            PageReference pageRef = new PageReference('https://xxyyyaaaa-dev-ed--c.ap4.visual.force.com/apex/ss');
            pageRef.setRedirect(true);

        }
    }
}

As one can see I have tried a few known ways to redirect to the VF page but have been unsuccessful. Here "ss" is the simple VF page which has a hard coded text message.
Any suggestion can be very helpful for me.

A: Triggers cannot redirect you to a new page. You'll need to accomplish this with something like a button which brings your users into a visualforce page.

A: Let's take a step back ....
Triggers execute at the database layer of the software application stack.  As such, they occur whenever DML occurs to the database object. In Salesforce, this can happen in many ways:

*

*user action from the UX (e.g. clicking Save)

*DML from a scheduled flow or batchable

*DML within an APEX REST class

*DML from execution of a native SFDC REST or SOAP API

*Dataloader

*BulkAPI

*Downstream action from subscribing to a platform event

*DML from a LWC or Aura component

*...

As such, redirecting to a VF page from this layer in the software stack does not make architectural sense.
Redirection to VF pages should be done when the initial stimulus is from a UX action and the redirection should be done by the "controller" that directly responds to the stimulus.


text:
Q: How to get the due date 14 days before shipment date? have the requirement to set the payment term 14 days before shipment date. so my baseline date will be the shipment date. How to get the due date for 'baseline date - 14 days' because all the resource i searched it only showed for baseline date + days.
I tried to make the days = -14 in OBB8 but the system doesn't allow that.
This is how I changed NET_DUE_DATE_GET FM
    FUNCTION NET_DUE_DATE_GET.
*"----------------------------------------------------------------------
*"*"Lokale Schnittstelle:
*"       IMPORTING
*"             VALUE(I_ZFBDT) LIKE  BSID-ZFBDT
*"             VALUE(I_ZBD1T) LIKE  BSID-ZBD1T
*"             VALUE(I_ZBD2T) LIKE  BSID-ZBD2T
*"             VALUE(I_ZBD3T) LIKE  BSID-ZBD3T
*"             VALUE(I_SHKZG) LIKE  BSID-SHKZG
*"             VALUE(I_REBZG) LIKE  BSID-REBZG
*"             VALUE(I_KOART) LIKE  RFPOS-KOART DEFAULT 'D'
*"       EXPORTING
*"             VALUE(E_FAEDT) LIKE  RFPOS-FAEDT
*"----------------------------------------------------------------------

* ------ Initialisierung -----------------------------------------------
  CLEAR: E_FAEDT.

* ------ ZFBDT muß gesetzt sein ----------------------------------------
  CHECK NOT I_ZFBDT IS INITIAL.

* ------ REFEZ = späteste Tage aus Skontolinie -------------------------
  E_FAEDT   = I_ZFBDT.
  SEITZFBDT = SY-DATLO - I_ZFBDT.

*------- ... REFEZ = Späteste Tage aus Skontolinie ---------------------
  IF I_ZBD3T NE 0.
    REFEZ = I_ZBD3T.
  ELSE.
    IF I_ZBD2T NE 0.
      REFEZ = I_ZBD2T.
    ELSE.
      REFEZ = I_ZBD1T.
    ENDIF.
  ENDIF.

*------- REFEZ = 0 bei Gutschriften ohne Rechnungsbezug und ohne Valuta
if i_rebzg eq space.
  CASE I_KOART.
    WHEN 'D'.
      IF I_SHKZG = 'H'.
        REFEZ = 0.
      ENDIF.
    WHEN 'K'.
      IF I_SHKZG = 'S'.
        REFEZ = 0.
      ENDIF.
  ENDCASE.
endif.
*------- Fälligkeitsdatum setzen ---------------------------------------
  E_FAEDT = E_FAEDT + REFEZ.
ENDFUNCTION.

Is it a good idea change the FM to cater for my requirement?

A: You should never modify an standard function module. The leading practice if you want to do this via a FM is to make a copy of it to a Z function module and then change it as you like.
Alternatively and it depends on how you are using the FM, the calc is so basic that I would suggest you just make the calculation in your report or custom screen you are making. If you think you will use the calculation in several programs then it might make sense to do it with a function module but you'll know that based on what you are trying to achieve.
Later....


text:
Q: MySQL cross-selection limitation issue I have two tables.
T1 has one column which has 9000 unique records (varchar).
T2 has many columns with upwards of 1 million records. One of the columns T2.x of T2 has data from T1's column T1.x, however some T2 records have in their column T2.x data that doesn't exist in T1's column T1.x.  T2.x is also able to be NULL.
I want to list all records of T2, where T2.x has a record that matches T1.x
I tried = SELECT t1.column_x, t2.* from t1, t2 WHERE x = t1.x

However, this only lists 9000 records disregarding the many others that exist in T2.
How can I achieve what I seek?
e.g.

**t1 [x]
===**
a
b
c

**t2
===**     [x]
1 .. .. .. a
2 .. .. .. b
3 .. .. .. eee
4 .. .. .. NULL
5 .. .. .. c
6 .. .. .. a
7 .. .. .. c

I want to get: 1-2-5-6-7
Thank you.

A: Quite simply the following will work, though it will cause performance issues on that size of table considering both x columns are VARCHAR.
SELECT
    t2.*
FROM t2
INNER JOIN t1
ON t1.x = t2.x

Do you have an index on the x column already in both t1 and t2, as if so that would help improve query speed.  I would recommend NOT running this query in a production environment.  If unavoidable, I would have to recommend including LIMIT 10 (or however many rows you need) in order to limit the impact.


text:
Q: Shared preferences salvando inteiro errado Tô salvando o código de usuário(um inteiro) nas shared preferences:
      String a = Integer.toString(pUsuario.getCodigo());

    SharedPreferences.Editor editor_Codigo = oCodigo.edit();
    editor_Codigo.putString(pContext.getString(R.string.codigo_usuario), a);
    editor_Codigo.apply();

Pra recuperar eu uso:
   SharedPreferences oCodigo = pContext.getSharedPreferences(pContext.getString(R.string.codigo_usuario), Context.MODE_PRIVATE);
    String a = String.valueOf(oCodigo.getString(pContext.getString(R.string.codigo_usuario), "0"));
    return Integer.parseInt(a);

Mas não importa o código que salve, na hora de retornar sempre retorna o código "2"

A: Tente assim:
private String KEY_CODIGO = "KEY_CODIGO";

SharedPreferences.Editor editor_Codigo = oCodigo.edit();
editor_Codigo.putString(KEY_CODIGO , pUsuario.getCodigo());
editor_Codigo.commit();

Na busca do valor:
SharedPreferences oCodigo = pContext.getSharedPreferences("file.preferences", Context.MODE_PRIVATE);
String codigo = oCodigo.getString(KEY_CODIGO , ""));
return Integer.parseInt(codigo);

Aconselho utilizar o SharedPreferences em uma classe pra somente fazer essa busca pra facilitar problemas futuros como esse. Eu utilizo no meu app essa classe, fique livre pra copiar, editar, distribuir etc.
public class Preferences {

    private Context mContext;

    private SharedPreferences preferences;
    private SharedPreferences.Editor editor;

    private String FILE_NAME = "app.Preferences";
    private int MODE = Context.MODE_PRIVATE;

    private String KEY_LOGGEDUSERID = "KEY_LOGGEDUSERID";
    private String KEY_LOGGEDUSERNAME = "KEY_LOGGEDUSERNAME";
    private String KEY_EMERGENCYID = "KEY_EMERGENCYID";
    private String KEY_EMERGENCYNAME = "KEY_EMERGENCYNAME";
    private String KEY_TIMEDELAY = "KEY_TIMEDELAY";

    public Preferences(Context context) {
        mContext = context;
        preferences = mContext.getSharedPreferences(FILE_NAME, MODE);
        editor = preferences.edit();
    }

    public void setLoggedUserId(String id) {
        editor.putString(KEY_LOGGEDUSERID, id);
        editor.commit();
    }

    public String getLoggedUserId() {
        return preferences.getString(KEY_LOGGEDUSERID, "");
    }

    public void setLoggedUserName(String name) {
        editor.putString(KEY_LOGGEDUSERNAME, name);
        editor.commit();
    }

    public String getLoggedUserName() {
        return preferences.getString(KEY_LOGGEDUSERNAME, "");
    }

    public void setEmergencyUserId(String id) {
        editor.putString(KEY_EMERGENCYID, id);
        editor.commit();
    }

    public String getEmergencyUserId() {
        return preferences.getString(KEY_EMERGENCYID, "");
    }

    public void setTimeDelay(String time) {
        editor.putString(KEY_TIMEDELAY, time);
        editor.commit();
    }

    public String getTimeDelay() {
        return preferences.getString(KEY_TIMEDELAY, "");
    }

    public void setEmergencyUserName(String name) {
        editor.putString(KEY_EMERGENCYNAME, name);
        editor.commit();
    }

    public String getEmergencyUserName() {
        return preferences.getString(KEY_EMERGENCYNAME, "");
    }

}

Quando eu preciso recuperar o valor apenas uso:
Preferences preferences = new Preferences(this);
String loggedUserId = preferences.getLoggedUserId();


text:
Q: Get mutplie values from a dict at once I have dictionary that contains values that I need in my function.
Currently, I extract the values one by one and store them in local variable for further processing. like so:
def func(the_dict):
    a=the_dict['a']
    b=the_dict['b']
    b=the_dict['c']

the problem is that its a bit verbose, is there a way to extract the variable in a more concise way?

A: You could use map and unpack:
a, b, c = map(the_dict.get,("a","b","c"))
print(a,b,c)

A: You can use operator.itemgetter to get multiple values at once:
>>> from operator import itemgetter
>>> the_dict = {'a':1, 'b':2, 'c':3}
>>> a, b, c = itemgetter('a', 'b', 'c')(the_dict)
>>> a
1
>>> b
2
>>> c
3


text:
Q: ajax can't stop propagation I read data using xhttpRequest from xml files to build a nested list. All data goes in

 are dynamic loaded from xml files.
the ajax and html structure is like below:

$("#category" ).on('click','.toggle',function(e){
    e.stopPropagation();
    if(!$(this).hasClass("opened")){
        $(this).children("i").removeClass("fa-plus-square");
        $(this).children("i").addClass("fa-minus-square");
        $(this).children('.sub').show();
        $(this).addClass("opened");
    }else{
        $(this).children("i").removeClass("fa-minus-square");
        $(this).children("i").addClass("fa-plus-square");
        $(this).children('.sub').hide();
        $(this).removeClass("opened");
    }
});

    category here

product here

The main menu is categories. The submenu is products in the category.
I want the submenu opens when I click on the main menu, and closes When I click on the main menu again. But what I got is, the submenu closes when I click on a node in the submenu, which should remain open when I do some actions on submenu rather than main menu.

Could any of you correct the bug for me? Thanks.

A: The problem is, that the event has already bubbled up before you catch it. Here's my small solution for that.

$("#category").on('click', '.toggle', function(e) {
  e.stopPropagation();
  if (e.target.classList.contains("product")) {
    // do nothing
  } else {
    if (!$(this).hasClass("opened")) {
      $(this).children("i").removeClass("fa-plus-square");
      $(this).children("i").addClass("fa-minus-square");
      $(this).children('.sub').show();
      $(this).addClass("opened");
    } else {
      $(this).children("i").removeClass("fa-minus-square");
      $(this).children("i").addClass("fa-plus-square");
      $(this).children('.sub').hide();
      $(this).removeClass("opened");
    }
  }
});

    category here

product here


text:
Q: nf_conntrack_ipv6 not tracking outgoing connections I'm trying to get outgoing IPv6 routing going, my issue is, that conntrack is not working correctly.
I've dumped the traffic via tcpdump, which shows me that the packets go outside (e.g. internal interface -> router -> isp) and that I receive a response (isp -> router).
I do have a general locking rule for all incoming traffic except 443, but I also do have a rule to allow all established or related traffic before:
-A PREROUTING -m state --state RELATED,ESTABLISHED -j ACCEPT
-A PREROUTING -i eth1 -j lockout

If I remove the locking rule, everything works as expected, but then I cannot block any other traffic going via the router.
When looking at the output of conntrack -L -f ipv6 no flows are listed there.
The modules are loaded:
lsmod shows:
nf_reject_ipv6         16384  1 ip6t_REJECT
nf_conntrack_ipv6      20480  3
nf_defrag_ipv6         36864  2 openvswitch,nf_conntrack_ipv6
nf_conntrack          110592  10 ip_vs,nf_conntrack_proto_gre,openvswitch,nf_nat,nf_nat_ipv4,xt_conntrack,nf_conntrack_netlink,xt_connmark,nf_conntrack_ipv4,nf_conntrack_ipv6

Kernel version:
Linux router 4.3.3-1.el7.elrepo.x86_64 #1 SMP Tue Dec 15 11:18:19 EST 2015 x86_64 x86_64 x86_64 GNU/Linux

OS:
CentOS 7
Am I mistaking something or it just not working? Where could I look to find what's the issue?


text:
Q: Elm submodule's init command not firing My app uses Navigate for routing, but, for some reason, the initial http command is not firing for one of the submodules. There could be something wrong in the way commands are wired between parent and child modules, but I could use some help locating the issue. The code and structure is modeled after the elm-taco (https://github.com/ohanhi/elm-taco) example. Below is an excerpt of the relevant parts of the code, and there is no compiler error.
Main.elm
init : Flags -> Location -> ( AppModel, Cmd Msg )
init flags location =
        (  startModel
        , Http2.get ("localhost:4000/graphql?query=" ++ encoded) HandleLogDataResponse decoder)

update :  Msg -> AppModel -> ( AppModel, Cmd Msg )
update  msg model =
        case msg of
             HandleLogDataResponse webData ->
                 updateLogData model webData
             RouterMsg routerMsg ->
                 updateRouter model routerMsg

updateLogData :  AppModel -> WebData LogData -> ( AppModel, Cmd Msg )
updateLogData  model webData =
    case webData of
        Success logdata ->
            case model.appState of
                NotReady time ->
                    let
                        initTaco =
                            { currentTime = time
                            , logdata = logdata
                            }
                        ( initRouterModel, routerCmd ) =
                            Router.init initTaco model.location
                    in
                        ( { model | appState = Ready initTaco initRouterModel }
                        , Cmd.map RouterMsg routerCmd
                        )

                Ready taco routerModel ->
                    ( { model | appState = Ready (updateTaco taco (UpdateLogData logdata)) routerModel }
                    , Cmd.none
                    )

Router.elm
init : Taco -> Location -> (Model, Cmd Msg)
init taco location =
    let
        ( chatModel, chatCmd) =
               Chat.initModel taco
    in
      ( { chatModel = chatModel
      , route = parseLocation location}
      , Cmd.map ChatMsg chatCmd
      )

update: Msg -> Model -> ( Model,Cmd Msg, TacoUpdate)
update msg model =
    case msg of
        ChatMsg chatMsg ->
            updateChat model chatMsg

updateChat : Model -> Chat.Msg -> (Model, Cmd Msg, TacoUpdate)
updateChat model chatMsg =
    let
        ( nextChatModel, chatCmd, tacoUpdate) =
            Chat.update chatMsg model.chatModel
    in
        ( {model | chatModel = nextChatModel }
        , Cmd.map ChatMsg chatCmd
        , tacoUpdate)

Chat.elm
initModel : Taco -> ( Model, Cmd Msg )
initModel taco =
    let
        startModel = { newMessage = ""
                    , messages = taco.messages
                    , response = "Waiting for a response..."
                    , logs = []
                    }
        cmd = Http.send FetchHNTopStories request

    in
            ( startModel
            , cmd
        )

A: In order to have the result of the execution of a command, you need to provide a way for it to get to the runtime.
This is done through main. If your Cmd do not get to the main of the app, they will never be executed.
In the code samples you gave, it is not obvious how the submodule init gets to the main. Traditionally, the init you have in your Main.elm should use the inits from the submodule, Cmd.map the submodule init Cmds and Cmd.batch them together with the rest of the main init Cmds.


text:
Q: Weird behavior with a RelativeLayout and the Galaxy S4 This is not the first time that such a thing occured with my galaxy S4.
Here is the situation :
I have a layout in which I want to center in parent a thin line and center horizontally above and below two other views.
I managed to achieve the desired effect on every android phone I could get my hands on except the galaxy S4.
Tested phones :

*

*Nexus 6 (Android 5.1.1) - WORKING

*Nexus 4 (Android 5.1.1) - WORKING

*Wiko Darkfull (Android 4.2.1) - WORKING

*Galaxy S4 GT-I9505 (Android 4.4.2) - NOT WORKING

Here is the effect that is working on every phone except the S4 :

And here is the effect I have on the S4 :

The relevant part of the code is :
 <RelativeLayout
        android:layout_width="64dp"
        android:layout_height="match_parent"
        android:background="@color/black_blur_12">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/separator"
            android:layout_centerHorizontal="true"
            android:layout_marginRight="8dp"
            android:src="@drawable/ic_group_white_24dp" />

        <ImageView
            android:id="@+id/separator"
            android:layout_width="32dp"
            android:layout_height="0.5dp"
            android:layout_centerInParent="true"
            android:background="@color/white"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/separator"
            android:layout_centerHorizontal="true"
            android:singleLine="true"
            android:textAppearance="@android:style/TextAppearance.Medium"
            android:textColor="@color/white"
            android:text="0"/>

 </RelativeLayout>

As I said, it is not the first time I have a problem with layouts and the galaxy S4.
All the ROMS are official.
Thanks for your help.


text:
Q: Is a C .lib file platform specific? I'm trying to use an API for a proprietary interface device on an embedded system (Freescale HCS08), and the provided files include headers (.h) and libraries (.lib).  The header compiles fine with the rest of my code (standard C), but when trying to link against the library I get memory errors saying the file might be corrupted.
My understanding of libraries in C is somewhat limited as I work almost exclusively on embedded systems where magic things like stdio, files, and dlls don't exist; but would the (or any) library be platform specific?  Does it contain fully (if there is any sort of level there) compiled code?  Some of the other files provided are VS project files, so if it is the case that the .lib is platform-specific, it wouldn't be unexpected that linking a file meant for x86-Windows to an 8-bit compiler would fail; it could be just me.

A: Not only is a .lib file CPU specific (there would be no way to link HCS08 code to x86 code), it is toolchain specific (CodeWarrior won't talk to SDCC, GCC/binutils won't talk to Visual Studio).

A: Yes the .lib contains compiled code so it is platform-specific.  If you have the source you should be able to re-compile it to your platform.


text:
Q: How to DRY up shared scopes for Mongoid models? I have a few Mongoid model classes that all have a :datetime field. I would like to query these models to find out records that fall under today's date. The query would look like this:
scope today, where(:datetime.gt => DateTime.now.beginning_of_day, :datetime.lt => DateTime.now.end_of_day)

Currently, the above scope code are duplicated within all the model classes. How do I dry this up?

A: The simples thing is:
module TimeDepedentent
  field :datetime

  scope today, where(:datetime.gt => DateTime.now.beginning_of_day, :datetime.lt => DateTime.now.end_of_day)

  scope yesterday ...
  scope one_month_ago ...
end

class MyModel
  include TimeDepedentent
end


text:
Q: Expectation involving expnential I have an equation: $\mathbb{E}[\exp({\epsilon}) (x \epsilon + x)]$, where $\epsilon \sim p(0 | \sigma^2)$ is a normal distribution. I know what $\mathbb{E}[\epsilon] = 0$ and $\mathbb{E}[\epsilon^2] = \sigma^2$.
I would like to get rid of the expectation here. My initial thought was $\mathbb{E}[\exp({\epsilon}) (x \epsilon + x)] = x$, but I feel like this is not true. I would be grateful if you provide some insight.

A: Use the normal distribution function
$$f(t)=\frac{1}{\sqrt{2\pi\sigma^2}}e^{-\frac{t^2}{2\sigma^2}} $$
to evaluate,
$$E[e^t]=\int_{-\infty}^{\infty}e^tf(t)dt=\frac{1}{\sqrt{2\pi\sigma^2}}\int_{-\infty}^{\infty}e^{t-\frac{t^2}{2\sigma^2}}dt=e^{\frac12\sigma^2}$$
$$E[te^t]=\int_{-\infty}^{\infty}te^tf(t)dt=\frac{1}{\sqrt{2\pi\sigma^2}}\int_{-\infty}^{\infty}te^{t-\frac{t^2}{2\sigma^2}}dt=\sigma^2e^{\frac12\sigma^2}$$
Therefore,
$$E[e^\epsilon (x \epsilon + x)]=x(E[\epsilon e^\epsilon]+E[e^\epsilon])=xe^{\frac12\sigma^2}(\sigma^2+1)$$


text:
Q: Is there any way of changing LockScreen Wallpaper/photo in Android programmatically I want to change the lockscreen wallpaper of Android. I was able to change home screen wallpaper through WallpaperManager.setResource
But I am unable to set LockScreen Wallpaper
Also is there any way to change it over time automatically?

A: As of the latest Android API 24 it is possible to update the Lockscreen wallpaper by using the WallpaperManager and providing the FLAG_LOCK flag.
wallpaperManager.setBitmap(bitmap, null, true, WallpaperManager.FLAG_LOCK)
check this question for more details.
How can change lockscreen wallpaper in android with code?

A: Frist Create Bitmap source from drawable Resource
Bitmap icon = BitmapFactory.decodeResource(getViewContext().getResources(),
R.drawable.wall);
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
        WallpaperManager wallpaperManager =WallpaperManager.getInstance(getViewContext());
        try {
            wallpaperManager.setBitmap(icon, null, true, WallpaperManager.FLAG_LOCK);
        } catch (IOException e) {
            e.printStackTrace();
        }


text:
Q: How to get a callback from TextArea on each change? in my app, when editing a record, I've added an ActionListener to save a temporary copy of the edited values for each field automatically, so that if the app is put in the background and then stopped, the edited values can be recovered when the app is started up again.
However, with the TextAreas it doesn't work since actionListeners don't get called unless the user takes some action (like leaving the field). I need to use the TextArea since there can be multiple lines of text, so using a DataChangedListener for a TextField as suggested in this thread does not seem a viable solution. And being able to save the TextAreas is important to achieve good UX since the user likely loses more work when text is dropped than if for example a value set in a Picker is lost.
Is there another way to achieve this result?
Thanks in advance

A: TextField allows multiple lines using setSingleLineTextArea(false). When invoked it will function similarly to TextArea.


text:
Q: How to get full cmd of a process in linux? My process cmd is very long because there are lots of arguments. Now I would like to check the full cmd. By using cat /proc/PROCESS_NUMBER/cmdline, the cmd is not fully shown. Is there any other way to see exactly full cmd in linux?

A: How long is your command line?
If it is in the megabyte range, you might perhaps recompile your kernel with a bigger ARG_MAX in your linux-3.*/include/linux/limits.h file. I put there
#define ARG_MAX  2097152    /* # bytes of args + environ for exec() */

(there might also be a way to set that limit dynamically, but I forgot how, and I could be wrong)
I do like big ARG_MAX limit because I occasionally use the **/*.c global expansion feature of zsh which is my interactive shell.
Don't put a huge value in ARG_MAX; I would guess that you want to have it less than 2% of your available RAM.
Notice that /proc/*/cmdline contains null bytes. You might translate them, see this.
addenda
if for whatever reason you cannot afford a large command line, find some way and convention to avoid having such a large amount of program arguments. For instance, you could modify the invoked program to read some things from a file or some other source (database?). For example, some Unix programs (e.g. GCC) accept @filename to read options from some file named filename.


text:
Q: Making animation based on COVID-19 data There is an animation of the growth and spread of COVID-19 cases worldwide at http://www.healthmap.org/covid-19
My question is how do I make the same animation using Mathematica, also analyze the growth within specific territory like Melbourne.
(To be clear, I want to make a similar animation and related analysis with the data derived from the website or movie if it is possible.)
Here is the data used to make the movie:
https://github.com/beoutbreakprepared/nCoV2019/tree/master/latest_data

A:
There are many works to start from:

*

*Propagation risk of COVID-19 by local contact in Spain

*100 Days of COVID19 Over US Counties

*Maps for Visualizing Covid-19's Effect
Also see works of Hiroki Sayama:
CODE: https://github.com/hsayama/COVID-19-geographical-animations
VISUALS:

*

*https://twitter.com/HirokiSayama/status/1261623727772631047

*https://twitter.com/HirokiSayama/status/1262109704328810496

*https://twitter.com/HirokiSayama/status/1301977095111929862
GENERAL RESOURCES: http://wolfr.am/coronavirus


text:
Q: Function to count MySQL rows using WHERE am making function to count rows using "WHERE", but i get a mysql error
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in C:\AppServ\www\test\test\index.php on line 9
Unknown column '1' in 'where clause'
here is my function
    function CountRows($table, $field = NULL, $value = NULL){
        mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD);
        mysql_select_db(DB_NAME);
        if($field != NULL && $value != NULL){
            return mysql_num_rows(mysql_query("SELECT * FROM `".$table."` WHERE `".$field."` = `".$value."`"))or die(mysql_error());
        }else{
            return mysql_num_rows(mysql_query("SELECT * FROM `".$table."`"));
        }
    }

i've created this function to simplify counting rows mysql rows for banned members, inactive members etc, since all will be using WHERE
all help will be appreciated, thanks in advance

A: Backticks (`) are for enclosing table and column names.  Don't wrap $value in them, just use single-quotes (').
Also, there's no reason you need to pull the full data set from the DB and count the rows in it.  Just query for the count:
    if($field != NULL && $value != NULL){
        $cnt = mysql_fetch_assoc(mysql_query("SELECT COUNT(*) as cnt FROM `".$table."` WHERE `".$field."` = '".$value."'"))or die(mysql_error());
    }else{
        $cnt = mysql_fetch_assoc(mysql_query("SELECT COUNT(*) as cnt FROM `".$table."`"));
    }
    return $cnt['cnt'];

A: Additionally:

*

*Do not connect/select database in the function. This should be done one time at the beginning of every page, no more (unless multiple connections are desired).

*Do not SELECT * just so you can calculate the number of rows. Use MySQL's COUNT() function instead.
$result = mysql_query("SELECT COUNT(0) AS numRows FROM aTable");
$numRows = mysql_result($result, 0, 'numRows');

*Do NOT use your function with user input without taking appropriate actions to secure yourself against SQL injection.

A: *

*You should not connect to database each time you need to do a query.. Just keep a persistent connection or ideally use PDO.

*Value should be enclosed with simple single quotes. This is probably what is getting you an error, as anything enclosed in backticks kind of quotes is considered a database/table/field name.

*Use COUNT(*), it does not fetch all the database rows.

*If value is possibly supplied by user, make sure that it is safe by escaping it with mysql_real_escape_string if not using PDO.
Without using PDO code would be:
mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD);
mysql_select_db(DB_NAME);

function CountRows($table, $field = NULL, $value = NULL){

    if ($field != NULL && $value != NULL) {
        $query = "SELECT COUNT(*)
                  FROM `".$table."`
                  WHERE `".$field."` = '". mysql_real_escape_string($value) . "'";
    } else {
        $query = "SELECT COUNT(*) FROM `".$table."`";
    }

    $count = mysql_fetch_array(mysql_query($query));
    return $count[0];
}


text:
Q: The term 'scaffold-dbcontext' is not recognized as the name of a cmdlet, function, script file, or operable program (Entity Framework) I am trying to use database-first model to create a dbContext and database entities.
When I run this command
scaffold-dbcontext "Data Source=(local);Initial Catalog=MyDb;Integrated Security=True;"
         Microsoft.EntityFramework.sqlserver -outputdir Models

I get this error:

*

*scaffold-dbcontext "Data Source=(local);Initial Catalog=MyDB;In ...

*CategoryInfo          : ObjectNotFound: (scaffold-dbcontext:String) [], CommandNotFoundException

*FullyQualifiedErrorId : CommandNotFoundException

I know how to resolve this if I was using Entity Framework Core but I am using Entity Framework 6.0.0 and all the solutions I have found address the Entity Framework Core version.
Thank you.
I tried to add EntityFramework.Tools in the Nuget Package Manager but I could not find it. I also tried to include it in the .csproj file but it didn't work. It appears that there is no EntityFramework.Tools dll.

A: For EF 6 use the built in VS tooling


text:
Q: Как вернуть промежуточное значение? Как вернуть status = 2, не прерывая цикл [и функцию]?
package main

import (
    "fmt"
    "math/rand"
    "time"
)

// Значения status: 1 - "успешно"; 2 - "неудачно впервые"; 3 = "неудачны все попытки".
func SendMail() (status int) {
    for i := 1; i < 6; i++ { // максимальное количество попыток.
        isSuccess := rand.Intn(2) == 1 // случайное число true/false для теста

        if isSuccess {
            fmt.Println("Успешно! i =", i)
            return 1
        }

        if !isSuccess && i == 1 {
            fmt.Println("Неуспешно впервые. i =", i)
            status = 2
        }
        time.Sleep(2 * time.Second)
    }

    status = 3
    fmt.Println("Неудачны все попытки. i = 5")
    return
}

func main() {
    rand.Seed(time.Now().UnixNano())
    var my_status = SendMail()
    if my_status == 1 {
        fmt.Println("main: Успешно!")
    }
    if my_status == 2 {
        fmt.Println("main: Неуспешно впервые.")
    }
    if my_status == 3 {
        fmt.Println("main: Неудачны все попытки.")
    }
}

https://go.dev/play/p/X44qX3w4VYm

A: Как подсказали — пишите в канал. Вот работающий переделанный ваш пример
https://go.dev/play/p/-olSoQuWLuV
P.S: Ну и число попыток снаружи можно передать
package main

import (
    "fmt"
    "math/rand"
    "time"
)

type SendAttempt struct {
    status int
    first  bool
}

func main() {
    rand.Seed(time.Now().UnixNano())
    attempts := make(chan SendAttempt)

    go SendMail(attempts)

    for {
        select {
        case atm, ok := <-attempts:
            if !ok {
                fmt.Println("Исчерпаны все попытки")
                return
            }

            if atm.status == 1 {
                fmt.Println("Успешно!")
                return
            }

            if atm.status == 2 {
                msg := ""
                msg = msg + "Неуспешно"
                if atm.first {
                    msg = msg + " впервые"
                }

                fmt.Println(msg)
                continue
            }

            if atm.status == 3 {
                fmt.Println("main: Неудачны все попытки.")
                continue
            }
        default:
            continue
        }
    }
}

// Значения status: 1 - "успешно"; 2 - "неудачно впервые"; 3 = "неудачны все попытки".
func SendMail(attempts chan<- SendAttempt) {
    for i := 1; i < 6; i++ {
        isSuccess := rand.Intn(2) == 1

        if isSuccess {
            attempts <- SendAttempt{1, false}
            continue
        }

        if !isSuccess {
            attempts <- SendAttempt{2, i == 1}
            continue
        }

        time.Sleep(2 * time.Second)
    }

    attempts <- SendAttempt{3, false}
    close(attempts)
}


text:
Q: Microcontroller bit information for the Core and different peripherals Usually, from what I have seen, Microcontroller have this information of 8-bit, 16-bit and 32-bit.
In this Microcontroller S32K142, it is mentioned as 32-bit CPU. So, what does this actually mean?
I understand it like, the Processor core inside the microcontroller has the registers (ALUs) of 32-bit width for the computation. So, a single 32-bit information can be processed at a single time. Or 2x 16-bit information or 4x 8-bit information can be processed at a single time. Am I correct in understanding this?
If so, but the ADC specification is like 12-bit ADC and for timers it is like 16-bit. Why there is a difference like this for different peripherals? Any specific reason?

A: The 'bitness' of a cpu is a disputed topic. My take is the width of the ALU and data path. The fact that the Z80 is believed to be an 8bit cpu but had only a 4 bit ALU contradicts this. Your chip has an ARM Cortex M4 cpu. ARM declares this as a 32bit cpu - who am I to argue? Its alu can do a 32bit add in one clock, but not four 8bit adds or two 16bit adds.—correction— The cm4 has SIMD (single instruction, multiple data)instructions that do this from same source/destination registers.
Consider a 32 bit ADC - what is one four thousand millionth of 3V? A very very small voltage. So small it would be dwarfed by noise. With current technology it would be difficult if not impossible. A 12bit ADC on the other hand is relatively easy.
Timers - 16 bit. How about an 8 bit cpu with 24bit timers? You would need to do three 8 bit reads to get the timer value. Basically there is nothing set in stone that a 8 bit cpu can only have an 8 bit timer or a 32 bit cpu must have a 32bit timer.
For tasks like pwm, 16 bits is usually adequate for most tasks.

A: Your guess is correct, though I doubt many microcontrollers can do arbitrary processing on multiple 16- or 8-bit words at once.
Timers and ADCs are separate hardware from the processor, so they don't have any reason to have the same bit depth as the processor. For ADCs especially, anything higher than 12 or 16 bits gets extremely sensitive and either quite expensive or quite slow. You don't generally need more ADC resolution than 12 bits, and if you do, you usually will find yourself using a dedicated ADC, not whatever's included on your microcontroller.
As for timers, there's no reason to make them the same bit depth as the processor, but also, as far as I'm aware, no reason not to either. I'd have a hard time finding a use for a 32-bit timer, though; I can't imagine needing that much resolution. A 24-bit timer with a prescaler would be more than enough in my book (though 16-bit might be pushing it for resolution).


text:
Q: Can Rust macros expand like C preprocessor macros for hex numbers? I'm looking to create a Rust macro that can do what this does in C.
#define V(a,b,c,d) 0x##a##b##c##d

Which when called with:
V(7B,B0,B0,CB)

Will simply have the following hexadecimal number placed in the code at compile time:
0x7BaB0bB0cCDd

Trying something like this:
macro_rules! gen_hex_num {
    ($a:expr , $b:expr , $c:expr , $d:expr) => (
        0x($a)a($b)b($c)c($d)d
    )
}

Produces an error:
error: macro expansion ignores token `a` and any following
 --> src/main.rs:3:16
  |
3 |         0x($a)a($b)b($c)c($d)d
  |               ^
  |
note: caused by the macro expansion here; the usage of `gen_hex_num!` is
likely invalid in expression context

Documentation and other questions don't seem to cover this scenario.

A: Nope.
Rust macros can only process and generate whole tokens, not token fragments. Something like 7b is not a token, so you won't be able to write a macro that would match it.
It seems like the main reason to use this macro in C is to make the number more readable. That isn't really necessary in Rust, because underscores are allowed in numeric literals. So you can just write 0x7b_b0_b0_cb instead.
You can approximate the original macro by accepting numbers and doing math, something like the following:
macro_rules! gen_hex_num {
    ($a:expr, $b:expr, $c:expr, $d:expr) => {
        ($a << 24) | ($b << 16) | ($c << 8) | ($d)
    }
}

But you have to call it like gen_hex_num!(0x7B, 0xB0, 0xB0, 0xCB), which probably defeats the purpose.


text:
Q: Remove first instance of lines with duplicate field value I have sha1 summed all the image files on my storage server and put the results in a text file in the form of:
sha1sum filename
I've sorted the file and removed all all unique sha1sum entries. So what I am left with is a list of duplicate files. Some have two entries, some three, some even more.
What I want to do is to remove only the first entry of each duplicate sha1sum so I can use the resulting output to delete the duplicate files (and keep only one instance of each)
I don't really care which version gets kept as I will be moving all the files into some form of directory hierarchy later

A: With GNU utilities, as found on Linux or Cygwin, you can tell uniq to separate each block of files with the same hash. Calling uniq with the option --all-repeated removes unique files from the list in the process.
sha1sum * |
sort | uniq -w 40 --all-repeated=prepend |
sed -e '/^$/ { N; d; }' -e 's/^[^ ]*  //' |
tr '\n' '\0' | xargs -0 rm --

This isn't worth the effort over this simple, portable awk script: print each line if its first field is identical to the first field of the previous line. Again, this takes care of removing unique files from the list.
sha1sum * |
sort |
awk '$1==h {print}  {h=$1}' |
tr '\n' '\0' | xargs -0 rm --

Instead of doing this manually, you could call fdupes.
fdupes -f

A: You could also use awk 'a[$1]++'
$ gsha1sum *
86f7e437faa5a7fce15d1ddcb9eaeaea377667b8  file1
e9d71f5ee7c92d6dc9e92ffdad17b8bd49418f98  file2
86f7e437faa5a7fce15d1ddcb9eaeaea377667b8  file3
86f7e437faa5a7fce15d1ddcb9eaeaea377667b8  file4
$ gsha1sum *|awk 'a[$1]++'
86f7e437faa5a7fce15d1ddcb9eaeaea377667b8  file3
86f7e437faa5a7fce15d1ddcb9eaeaea377667b8  file4

Like the commands posted by Gilles, it also removes lines whose first field only appears once in the input.
a[$1]++ could be replaced with a[$1]++>0 or ++a[$1]>=2.


text:
Q: Uncaught GraphMethodException: Unsupported get request When I try to login with facebook from my website, this error occurs
Fatal error: Uncaught GraphMethodException: Unsupported get request. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api thrown in /home2/******/public_html/includes/facebook/base_facebook.php on line 1271
At the beginning, everything was alright. I haven't changed anything. What should I do to solve this?
/**
Analyzes the supplied result to see if it was thrown
because the access token is no longer valid.  If that is
the case, then we destroy the session.

@param $result array A record storing the error message returned
                    by a failed API call.
**/
protected function throwAPIException($result) {
$e = new FacebookApiException($result);
switch ($e->getType()) {
// OAuth 2.0 Draft 00 style
  case 'OAuthException':
  // OAuth 2.0 Draft 10 style
  case 'invalid_token':
    // REST server errors are just Exceptions
  case 'Exception':
    $message = $e->getMessage();
    if ((strpos($message, 'Error validating access token') !== false) ||
        (strpos($message, 'Invalid OAuth access token') !== false) ||
        (strpos($message, 'An active access token must be used') !== false)
    ) {
      $this->destroySession();
    }
    break;
}

throw $e;
}

A: require '../src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId'  => '344617158898614',
  'secret' => '6dc8ac871858b34798bc2488200e503d',
));
// Get User ID
$user = $facebook->getUser();
// We may or may not have this data based on whether the user is logged in.
// If we have a $user id here, it means we know the user is logged into
// Facebook, but we don't know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.

$user_profile = $facebook->api('/me');

}
catch (FacebookApiException $e)
{
    error_log($e);
$user = null;

}
}
// Login or logout url will be needed depending on current user state.
if ($user)
 {
$logoutUrl = $facebook->getLogoutUrl();
}
 else
{
$loginUrl = $facebook->getLoginUrl();
}
// This call will always work since we are fetching public data.
$naitik = $facebook->api('/naitik');
?>

<title>php-sdk</title>

php-sdk

<?php if ($user): ?>

  <a href="<?php echo $logoutUrl; ?>">Logout

<?php else: ?>

    Login using OAuth 2.0 handled by the PHP SDK:

    <a href="<?php echo $loginUrl; ?>">Login with Facebook

<?php endif ?>

PHP Session

<?php print_r($_SESSION); ?>

<?php if ($user): ?>

You

  <img src="https://graph.facebook.com/<?php echo $user; ?>/picture">

Your User Object (/me)

<?php print_r($user_profile); ?>

<?php else: ?>

  You are not Connected.

<?php endif ?>

Public profile of Naitik

<?php echo $naitik['name']; ?>


text:
Q: MS Access Report won't open in Office 365 C2R - Error 3761 'the decimal field's precision is too small' I have a report that works on all of our office computers except two that use office 365.  The majority of users have windows 10 pc's with access 2013 runtime, and the report runs without issue on these.  Access is our front end to a SQL express db.  On the two PC's with office 365, the report won't open, they just get:

Error 3761: the decimal field's precision is too small to accept the numeric you attempted to add.

There are 2 numeric fields on the report; Sum(ActivityValue), and %Complete.  These are calculated fields based on these query columns:
ProdActivityLength: DLookUp("SumofLength","qryProdActivitybyDept","itemserialno = " & [dbo_Production_Items].[ItemSerialNo])

ActivityValue: ([ProductionValue]/[ProdActivityLength])*[Length]

%complete: 1-((DSum("length","qryProdSchedCompletion","itemserialno = " & [ItemSerialNo])/[ProdActivityLength]))

The SQL fields Length and ProductionValue are decimal 18,2
Sum(ActivityValue) on the report is Currency, with 0 decimal places.
%Complete is Percentage with Auto decimal places.
I cannot think why the percentage field would be causing an issue, so I've been concentrating on the decimal fields.
The report is not trying to write the data back to anywhere, so I've tried changing the 0 decimal places to auto and to 2, but still get the error.
I have also tried changing the controlsource to int(sum(activityvalue) but the same error still occurs.
Does anyone have any idea what is causing this error in Office 365, or other ideas for how to resolve it?
Thank you.


text:
Q: Split csv(not uniform) into 2 lists I have a CSV with data in the format
1,2,3,4,A
2,3,B
1,4,5,6,C
5,D

and so on. How do i split it and assign each to python lists. The length of each line in csv is arbitrary. I need to split them into
   [[1,2,3,4],[2,3],[1,4,5,6],[5]]

and the rest into a python list
['A','B','C','D']

What is an efficient way to get this done. The below code is good enough to convert csv into list of lists but with the last elements. I want the last elements in a separate list
with open('dataset.csv', 'r') as fp:
  reader = csvreader(fp)
  li = list(reader)

A: You can iterate through the reader object and split/unpack the items into all items excluding the last and last item.
with open('dataset.csv', 'r') as fp:
  reader = csv.reader(fp)
  lst1, lst2 = [], []
  for row in reader:
      *others, last = row # Python 2: others, last = row[:-1], row[-1]
      lst1.append(others)
      lst2.append(last)

A: Try this:
import csv

with open('test.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',', skipinitialspace=True)
    list1 = []
    list2 = []
    for row in readCSV:
        list1.append(row[:-1])
        list2.append(row[-1])
print list1
print list2


text:
Q: Connection string for C# winapp with a SQL Server database file This is not the first time I have used databases using the C# in asp.net, but I can't seem to make it work in a Winforms app.
This is a test face, so there is not a real database but a SQL Server database file that I created.
What I have is this:
public AddControl SaveResearcher(string name)
{
   using(SqlConnection conn = new SqlConnection("")){
      SqlCommand cmd = new SqlCommand("INSERT INTO Personell VALUES (@name, @function)", conn);
      cmd.Parameters.Add("name",SqlDbType.VarChar).Value = name;
      cmd.Parameters.Add("function", SqlDbType.VarChar).Value = "Researcher";
      conn.Open();
      cmd.ExecuteNonQuery();
   }

   return AddControl.OK;
}

What do I have to put in the connection string?
Thanks in advance.

A: The connection string for at sql server db file without username/password
Server=.\SQLExpress;AttachDbFilename=c:\pathtodb\mydbfile.mdf;Database=dbname; Trusted_Connection=Yes;

You may find more connection string options at
http://www.connectionstrings.com/sql-server-2008

A: You can check there,
Connection strings for SQL Server 2005

A: Do you mean soemthing like this?
"Data Source[SERVER_NAME];Initial Catalog=[DATABASE_NAME];Integrated Security=True;MultipleActiveResultSets=True"

A: connectionString="Data Source=computerName\sqlexpress;Initial Catalog=DatabaseName;Integrated Security=True"


text:
Q: Yii2,I want to change my url like "aaaa.bbbb.cccc.dddd/app/web" to any name like "example.com" .How can I achieve this I'm implementing my site from godaddy to ASW server.
I want to change my url like aaaa.bbbb.cccc.dddd/app/web to any name like example.com.  How can I achieve this?


text:
Q: Проблема с типами QT 5.12.4 Есть такой код:
QByteArray  arrBlock;
        QDataStream out(&arrBlock, QIODevice::WriteOnly );

и такая ошибка

error: undefined reference to `QDataStream::QDataStream(QByteArray*, QIODevice::OpenModeFlag)'

error: no viable conversion from 'QIODevice::OpenModeFlag' to 'QIODevice::OpenMode' (aka 'QFlags<QIODevice::OpenModeFlag>')

что не так то? все по учебнику..
единственное это кросстул для nxp но я ж так понимаю что инклюды базовых классов для всех одинаковые
упд: чсх при этом приложение выпекается, а данная ошибка посвечивается не сплошной красной точкой, а красным кружком

A: При добавлении компилятора я указал тип кастом и указал пути к инклюдам, инклюды от кьют и инклюды с++ были в разных местах и подогнать их расположение под указанное в файлах кьюта оказалось дюже хлопотно, но зато если тип компилятора указать встроенный - например гцц сразу все ок.


text:
Q: Need help identifying SMD component This is a board from a Johnny Lightning V-bot, it has these SMD 6 pin components that just have a M03 and a dot on one of the terminals. Does anyone have a datasheet or any idea on how to ask for one to replace it? It helps with switching direction on a motor that transforms the upper half, and it's right on top of the hip motor connector.
This is the component, roughly 2.9 mm by 1.5 mm:

This is where it goes:

A: It's most likely an ROHM QS6M3 dual N+P channel MOSFET.


text:
Q: Knife Vsphere Password Plain text I'm using the knife-vsphere plugin for chef to interact with our vsphere hosts.
As part of the config for the knife-vsphere plugin it seems that you have to enter a plain text password which I think seems wrong.
When I set up the users within my recipe I've previously ran the passwords through openssl passwd -1 "plainTextPassword" to get the hash value and I set this as i'm creating the user, i'm not sure where this happens if it's on the node or if it's in knife.
Does anyone know if you can use the same hash method (or something else) to store my password locally to let me login to vsphere or do I have to leave it as plain text?
My current knife rb file is represented below:
log_level                :info
log_location             STDOUT
node_name                'a-user'
client_key               'C:/Users/user/.chef/a-user.pem'
validation_client_name   'chef-validator'
validation_key           'C:/Users/user/.chef/chef-validator.pem'
chef_server_url          'https://ourChefHost01:443'
syntax_check_cache_path  'C:/Users/user/.chef/syntax_check_cache'
cookbook_path [ 'C:/Work/chef/chef-repo/cookbooks' ]
ssl_verify_mode :verify_peer
knife[:vsphere_host]="VHost"
knife[:vsphere_user]="User"
knife[:vsphere_pass]="IWantThisToBeAHashIfPossiblePlease_ThanksInAdvance!"
knife[:vsphere_dc]="Region_1"
knife[:vsphere_insecure]=false

A: You cannot hash a password in order to later use that hash to login, as you cannot retrieve the original value (hashing is a one-way function). The thing you are searching for is encryption.
As the knife.rb is just a ruby file, you can also read the password from an environment variable (that you have to set once after starting the terminal session):
knife[:vsphere_user]="User"
knife[:vsphere_pass]=ENV['VSPHERE_PASS']

This will read the VSPHERE_PASS variable that you should have set with
export VSPHERE_PASS=mypassword

To my knowledge from using chef, there's no other way to store it encrypted on your machine (I mean.. Chef would still have to be able to decrypt it).


text:
Q: Redirect to security-trimmed menu node I've implemented SiteMap Security Trimming as described in this tutorial: ASP.NET Menu and SiteMap Security Trimming
The menu works as expected. I would like to take it one step further and redirect the user to the first node in the resulting trimmed menu. The menu will be different for every user based on their roles, so the redirect URL would need to be derived from the either the menu itself, or from the sitemap file.
Any suggestions on how to accomplish this?

A: I seem to have figured out one option, at least: I created an event handler for MenuItemDataBound, and redirected based on the Url of the first item bound to the menu, like so:
On the aspx, set the Menu's OnMenuItemDataBound="Menu1_MenuItemDataBound"
Then created the following method in the code-behind:
protected void Menu1_MenuItemDataBound(object sender, MenuEventArgs e)
{
    string Url = ((SiteMapNode)e.Item.DataItem).Url;
    Response.Redirect(Url);
}

Seems to work as expected. If you have a better solution, let me know.


text:
Q: Watir webdriver - Unable to flash on a heading with class attribute I am trying to flash the text contained within the h2 tag. However, I am unable to do so when the h2 tag has the class attribute.
I am able to retrieve the text contained within the h2 tag but I do not seem to be able to flash the text. Please help.
Source code:

Next to jump

Watir-webdriver code:
@browser.div(:class => "nextJump12 margin-bottom").flash
@nexttojump = @browser.div(:class => "nextJump12 margin-bottom")
puts @nexttojump.h2.text

A: As Željko mentioned, flash just changes the background-color of the element being flashed.
In html, element's inherit styles of their parents/ancestors. However, an element can override its parent's styles by specifying its own style (class or inline).
For example, say your element was:

Next to jump

Then the h2 would inherit the div element's background-colour - ie would be displayed with a blue background.
Now let's say the h2 specifies its own background-colour:

Next to jump

In the browser, you would only see a green background, not a blue background, around the h2. This is because the h2's styles take precedence over the styles inherited from the div.
This means that when you do:
browser.div.flash

You will see no change. The div's background would change between red and blue, but ultimately the h2's style would always override it.
Therefore you should try to flash the lowest elements in the DOM, in this case the h2. This way, regardless of what styles the h2 inherits or defines for itself, flash style change will take the highest precedence.
browser.div.h2.flash

So in your code, I would suggest trying:
browser.div(:class => "nextJump12 margin-bottom").h2.flash


text:
Q: How do I halt Maven when JUnit Fails? I am running Junit tests from Maven. The ant script has
<junit failureproperty="failproperty" errorproperty="errorproperty">
                     <classpath refid="classpath" />
                     <test name="${unit-test-suite}" />
                     <formatter type="brief" usefile="false" />
      </junit>

      <echo> ----------> ${failproperty} </echo>
      <echo> ----------> ${errorproperty} </echo>
      <fail message="something wrong" if="${failureproperty}"/>
      <fail message="something wrong" if="${errorproperty}"/>

I tried

*

*Halting on error or failure in Junit - This halts when I run the ant script only but the build succeeds in Maven and does not halt even thought JUnit has an error.

*

*I tried to send a fail message by setting the errorproperty and the failure property- This does not set the variables.

How do I tell Maven to stop everything when Junit fails?
Maven Details:
Maven version: 2.0.10
Java version: 1.6.0_17
OS name: "windows xp" version: "5.1" arch: "x86" Family: "windows"

A: This "fail fast" feature isn't currently supported by Maven 2, see SUREFIRE-580 (and maybe vote for it).

A: Are you sure you're setting the properties correctly?
Note that the if and unless attributes take property names, not expressions.  For example, try using:
<fail if="failproperty"/> instead of <fail if="${failproperty}"/>
The <fail/> tag works in this simple example.  Try mvn package and then mvn package -Dfailproperty=true
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>ant-test</groupId>
    <artifactId>ant-test</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.7</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-antrun-plugin</artifactId>
                <executions>
                    <execution>
                        <id>ant-test</id>
                        <phase>package</phase>
                        <configuration>
                            <tasks>
                                <junit failureproperty="fail">
                                    <classpath>
                                        <path refid="maven.plugin.classpath"/>
                                        <path refid="maven.test.classpath"/>
                                    </classpath>
                                    <formatter type="plain" />
                                    <batchtest>
                                        <fileset dir="src/test/java"/>
                                    </batchtest>
                                </junit>
                                <fail if="fail"/>
                            </tasks>
                        </configuration>
                        <goals>
                            <goal>run</goal>
                        </goals>
                    </execution>
                </executions>
                <dependencies>
                    <dependency>
                        <groupId>org.apache.ant</groupId>
                        <artifactId>ant-junit</artifactId>
                        <version>1.7.1</version>
                    </dependency>
                </dependencies>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <skipTests>true</skipTests>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Assuming a Test case in src/test/java:
import junit.framework.Assert;

import org.junit.Test;

public class FakeTestCase {

    @Test
    public void testThis() {
        Assert.fail("Failure");
    }

}


text:
Q: Spring Boot Hibernate CRUD REST API 404 Error I am simply trying to create a Spring boot Hibernate CRUD REST API through this code:

EmployeController.java

@RestController
@RequestMapping("/api")

    public class EmployeController {

        @Autowired
        private EmployeService employeService;

        @GetMapping("/employe")
        public List<Employe> get(){
            return employeService.get();
        }
    }

Employe.java

@Entity
@Table(name="employe")
public class Employe {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column
    private int id;
    @Column
    private String name;
    @Column
    private String gender;
    @Column
    private String department;
    @Column
    private Date dob;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    public String getDepartment() {
        return department;
    }
    public void setDepartment(String department) {
        this.department = department;
    }
    public Date getDob() {
        return dob;
    }
    public void setDob(Date dob) {
        this.dob = dob;
    }
    @Override
    public String toString() {
        return "Employe [id=" + id + ", name=" + name + ", gender=" + gender + ", department=" + department + ", dob="
                + dob + "]";
    }

}

EmployeService.java

public interface EmployeService {
    List<Employe> get();
    Employe get(int id);
    void save(Employe employe);
    void delete(int id);
}

EmployeServiceImplement.java

@Service
public class EmployeServiceImplement implements EmployeService {

    @Autowired
    private EmployeDAO employeDAO;

    @Transactional
    @Override
    public List<Employe> get() {
        return employeDAO.get();
    }
}

EmployeDAO.java

public interface EmployeDAO {
    List<Employe> get();
    Employe get(int id);
    void save(Employe employe);
    void delete(int id);
}

EmployeDAOImplement.java

@Repository
public class EmployeDAOImplement implements EmployeDAO {

    @Autowired
    private EntityManager entityManager;

    @Override
    public List<Employe> get() {
        Session currentSession = entityManager.unwrap(Session.class);
        Query<Employe> query = currentSession.createQuery("from Employe", Employe.class);
        List<Employe>list = query.getResultList();
        return list;
    }
}

I have write all the configuration related to MySQl database into the application.properties and when i run this project as Spring Boot App and go to the Postman and tried like this
and i a unable to understan why it always throws 404 error every time , can anyone tell me what i am missing in this code.

A: I checked your code.
where is @RestController  for your Controller file and where is @RequestMapping For your method in Controller class?
maybe you should write something like this according to your need.
tell me if you need more help.
@RestController
@RequestMapping("/api")
public class EmployeController {

   @RequestMapping(value = "/employ")
   public void employ()  {
   }
}

A: Try with this GET request, it may help you:
http://localhost:8080/api

A: Instead of this -
@Override
public List get()
Use this -
@RequestMapping(value = "/Employe", method = RequestMethod.GET)
public List get()


text:
Q: How to move all files excecpt one from parent folder into a new child folder using windows command? How to move all files except one from the parent folder into a new child folder using the windows command?
I need to move all files except one file named index.html from the parent folder into a new child folder.
I have tried the below command but it is not working.

move parent_folder ./parent_folder/child_folder

Please refer below
Current Folder Structure

Required Folder Structure

A: I have achieved the above requirement using 'robocopy' command.
Command
robocopy parent_folder parent_folder/child_folder/ *.* /E /XD child_folder /XF index.html /move

Referred URL - Windows batch command to move all folders in a directory with exceptions
Screenshot #1

Screenshot #2


text:
Q: How to deal with relative image path in subdirectories when using @import scss for IntelliJs autocompletion? I like the autocompletion feature of Webstorm, Phpstorm and Intellij and the other jetbrain-products. It doesn't work however if I have a structure like this:
img/my-img.jpg
sass/main.scss
sass/component/_component.scss

// sass/main.scss:
 @import "/component/component"

// _component.scss:
.class{
   //  => autocomplete doesn't work here as desired <=

   // how intellij completes it
   background: url(../../img/my-img.jpg)

   // what i would like to have instead
   background: url(../img/my-img.jpg)
}

Is there some way of telling IntellJ how to use the sass folder as base for the autocompletion of images and to get rid of the annoying error notice?

A: You can mark img folder as resourse root.
From jetbrains documentation:

Files under a folder marked as Resource Root can be referenced relative to this folder.


text:
Q: Allow ftp out through iptables I have been having difficulty allowing ftp through iptables. Right now my ftp looks like this.
Chain INPUT (policy DROP)
target     prot opt source               destination
ACCEPT     tcp  --  anywhere             anywhere             tcp ctstate NEW,RELATED,ESTABLISHED multiport dports http,https,ftp,ftp-data
ACCEPT     all  --  anywhere             anywhere             ctstate RELATED,ESTABLISHED

Chain FORWARD (policy DROP)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

I don't see anything wrong with it, but it doesn't work when I try to connect to it. (My ftp server is up, so that isn't an issue.)

A: It's not entirely clear to me whether these iptables rules are on your client or your server. Your statement "it doesn't work when I try to connect to it" is not at all helpful. Please update your question to clarify these issues.
If these rules are on your server you can't conect to it from elsewhere because you haven't defined any rules that permit this.
If this is on your client then the reason it's failing it because you haven't allowed the inbound related data connection. Remember it's from tcp/21 on the server to a arbitrary high port on your client. Your iptables INPUT rule is expecting a related inbound session to tcp/21.
These rules from devops-blog.net should work for an outgoing client:
-A INPUT -p tcp --sport 21 -m state --state ESTABLISHED -j ACCEPT
-A INPUT -p tcp --sport 20 -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p tcp --sport 1024: --dport 1024: -m state --state ESTABLISHED -j ACCEPT

-A OUTPUT -p tcp --dport 21 -m state --state NEW,ESTABLISHED -j ACCEPT
-A OUTPUT -p tcp --dport 20 -m state --state ESTABLISHED -j ACCEPT
-A OUTPUT -p tcp --sport 1024: --dport 1024: -m state --state ESTABLISHED,RELATED,NEW -j ACCEPT


text:
Q: Real time website information/content updating Since a year and a half I am trying to figure out how some websites update their content in real time without AJAX method.
Please see this example website: https://pro.btcturk.com/en/basic/exchange/BTC_TRY
That website is changing many texts within content in different timing.
It means that when the server is updated with new values in the database then the website is listening to database changes and then reflecting/delivering inside content without ajax calls.
Can someone give an example how to achieve such functionality possibly using Javascript or PHP normal hand-code appreciated?
Thank you

A: You can see the process here:

More information here: Websockets


text:
Q: In Python 2.* division which has more overhead? Let's say I want to divide two variables, in Python 2.* (mainly 6 and 7), that are considered integers. For instance:
a, b = 3, 2
print a/b
# Prints "1"

Now, there are at least two (non-redundant) ways I know of to cause this division to be normal, floating point division (without running a from __future__ import division). They are:
print a*1.0/b      # Of course you could multiply b by 1.0 also

and
print float(a)/b   # Here you could also have cast b as a float

Does one of these methods have an advantage (in speed) over the other? Does one have more overhead than the other?

A: >>> timeit.timeit(stmt="a*1.0/b",setup="a,b=3,2",number=100)
4.669614510532938e-05
>>> timeit.timeit(stmt="float(a)/b",setup="a,b=3,2",number=100)
7.18402232422477e-05

From the above, you can tell that simply using a*1.0/b is much faster then using float(a). This is because calling functions in Python are very costly. That being said though, you could do something like:
a,b=float(3),2
print a/b

and you would have the benchmark of:
>>> timeit.timeit(stmt="a/b",setup="a,b=float(3),2",number=100)
2.5144078108496615e-05

This is because you only call float() once, and that is on assignment of a. This in turn doesn't require the 1.0*a to be factored in, giving a much faster result.
Breaking this down further using the dis module, you can see the actual calls for this in a loop:
float during division
def floatmethod():
    a,b=3,2
    while True:
        print float(a)/b

float during division dis results
dis.dis(floatmethod)
  2           0 LOAD_CONST               3 ((3, 2))
              3 UNPACK_SEQUENCE          2
              6 STORE_FAST               0 (a)
              9 STORE_FAST               1 (b)

  3          12 SETUP_LOOP              25 (to 40)
        >>   15 LOAD_GLOBAL              0 (True)
             18 POP_JUMP_IF_FALSE       39

  4          21 LOAD_GLOBAL              1 (float)
             24 LOAD_FAST                0 (a)
             27 CALL_FUNCTION            1
             30 LOAD_FAST                1 (b)
             33 BINARY_DIVIDE
             34 PRINT_ITEM
             35 PRINT_NEWLINE
             36 JUMP_ABSOLUTE           15
        >>   39 POP_BLOCK
        >>   40 LOAD_CONST               0 (None)
             43 RETURN_VALUE

Reason for speed decrease
The reason that this method is much slower is because it must first LOAD_GLOBAL: float, then grab the value of a (LOAD_FAST: a) then it calls float(a) (CALL_FUNCTION). It then finally executes the division (BINARY_DIVIDE), all of which done over and over during the loop.
float on assignment
def initfloatmethod():
    a,b=float(3),2
    while True:
        print a/b

float on assignment dis results
dis.dis(initfloatmethod)
  2           0 LOAD_GLOBAL              0 (float)
              3 LOAD_CONST               1 (3)
              6 CALL_FUNCTION            1
              9 LOAD_CONST               2 (2)
             12 ROT_TWO
             13 STORE_FAST               0 (a)
             16 STORE_FAST               1 (b)

  3          19 SETUP_LOOP              19 (to 41)
        >>   22 LOAD_GLOBAL              1 (True)
             25 POP_JUMP_IF_FALSE       40

  4          28 LOAD_FAST                0 (a)
             31 LOAD_FAST                1 (b)
             34 BINARY_DIVIDE
             35 PRINT_ITEM
             36 PRINT_NEWLINE
             37 JUMP_ABSOLUTE           22
        >>   40 POP_BLOCK
        >>   41 LOAD_CONST               0 (None)
             44 RETURN_VALUE

Reason for speed increase
You can see that on the line in which the division is performed, it no longer has to call the float function, allowing immediate execution of the division. It simply calls LOAD_GLOBAL: float and calls CALL_FUNCTION once, which is on assignment, rather then in the loop. This means it can skip straight to the BINARY_DIVIDE call.
Stats used for this benchmark:
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32

A: Using Python 2.7.3:
In [7]: %timeit a*1.0/b
10000000 loops, best of 3: 165 ns per loop

In [8]: %timeit float(a)/b
1000000 loops, best of 3: 228 ns per loop

So the first method appears slightly faster.
That said, it is always worthwhile to profile your code before embarking on micro-optimizations.


text:
Q: How can I get rows from a table that matches all the foreign keys from another table Say I have two tables role and roleApp defined like this:
create table #tempRole(roleId int);

insert into #tempRole (roleId) values (1)
insert into #tempRole (roleId) values (2)

create table #tempRoleApp(roleId int, appId int);

insert into #tempRoleApp (roleId, appId) values (1, 26)
insert into #tempRoleApp (roleId, appId) values (2, 26)
insert into #tempRoleApp (roleId, appId) values (1, 27)

So, from #tempRoleApp table, I want to get only the rows that matches all the values of the #tempRole table (1 and 2), so in this case the output needs to be 26 (as it matches both 1 and 2) but not 27 as the table does not have 2, 27).
#tempRole table is actually the output from another query so it can have arbitrary number of values.
I tried few things like:
select *
from #tempRoleApp
where roleId = ALL(select roleId FROM #tempRole)

Which does not give anything... tried few more things but not getting what I want.

A: I believe this gives what you were looking for.
select tra.appId
from #tempRoleApp as tra
join #tempRole as tr on tra.roleId = tr.roleId
group by tra.appId
having count(distinct tra.roleId) = (select count(distinct roleId) from #tempRole)

It uses count distinct to get the total unique roleId's in the tempRole table and compares that with the unique count of these per appId, after confirming the roleIds match between the tables.
As you clarified in the comment, once you add another tempRole roleId, now no entry has all of the Ids so no rows are returned.


text:
Q: Something is consuming my Ctrl+C I inherited this Computer and it was originally set up with emacs as the default keyboard layout. I switched it to Windows, but now I cannot use Ctrl+C for anything.
In a terminal it does nothing (does not halt the execution), and in text editing it does not copy (even though if I write click the copy hint id Ctrl+C).
I'm not sure what is consuming my Ctrl+C, or how to fix it.  Ctrl+V, Ctrl+X, Ctrl+Y and Ctrl+Z work exactly as expected.

A: I solved my problem. While the computer was still using the emacs shortcuts, I tried to add a custom Ctrl+C shortcut - it hadn't worked. When I switched away from emacs shortcuts, my non-operational custom Ctrl+C shortcut was still in place! How annoying of me!
Thank you @Zacharee1, @mchid, @Hitechcomputergeek, @KGIII, and @chaskes!


text:
Q: Auto populate user to custom object on a trigger I'm having some issues with some code I've adapted to work for my instance that was posted by @Brian Mansfield.
We have invoices pushed into a custom object and they link through to accounts fine, but I'm trying to get it linked to a user where possible to allow easier reporting.
On the invoice item there is a field "Sales_Rep_1" which should match the alias of a user. The code is working to some degree, but it seems to be case-sensitive. E.g. if the invoice has Sales_rep_1 value of "TEST" and there's a user with an alias "test", it throws a wobbly and I get the following error:

Error:Apex trigger SetSalesRep caused an unexpected exception, contact your administrator: SetSalesRep: execution of BeforeUpdate
  caused by: System.NullPointerException: Attempt to de-reference a null
  object: Trigger.SetSalesRep: line 19, column 1

Would be grateful if someone can find a fix for this.
Many thanks
trigger SetSalesRep on Invoice_Item__c (before update, before insert) {
    Set<String> users = new Set<String>();

    for (Invoice_Item__c collectNumFromOrder : Trigger.new) {
        users.add(collectNumFromOrder.Sales_Rep_1__c);
    }

    List<User> UserList = [SELECT id, alias FROM USER WHERE alias IN :users];

    Map<String, User> InvoiceToUserMap = new Map<String, User>();

    for (User c : UserList) {
        InvoiceToUserMap.put(c.alias, c);
    }

    for (Invoice_Item__c o : Trigger.new) {
        if (!InvoiceToUserMap.Isempty() )  {

             o.User__c = InvoiceToUserMap.get(o.Sales_Rep_1__c).id;

        }
        else {
            o.User__c = null;
        }
    }
}

A: You should check whether value exist in your map using containskey Method and null for sales_rep_1__c
trigger SetSalesRep on Invoice_Item__c (before update, before insert) {
    Set<String> users = new Set<String>();

    for (Invoice_Item__c collectNumFromOrder : Trigger.new) {
         if(collectNumFromOrder.Sales_Rep_1__c!=null){
            users.add(collectNumFromOrder.Sales_Rep_1__c.tolowercase());
         }
    }

    List<User> UserList = [SELECT id, alias FROM USER WHERE alias IN :users];

    Map<String, User> InvoiceToUserMap = new Map<String, User>();

    for (User c : UserList) {
        InvoiceToUserMap.put(c.alias.tolowsercase(), c);
    }

    for (Invoice_Item__c o : Trigger.new) {
        if (!InvoiceToUserMap.Isempty() && o.Sales_Rep_1__c!=null && InvoiceToUserMap.containsKey(o.Sales_Rep_1__c.tolowercase()) )  {

             o.User__c = InvoiceToUserMap.get(o.Sales_Rep_1__c.tolowercase()).id;

        }
        else {
            o.User__c = null;
        }
    }
}


text:
Q: .net core 6.1 : impossible to send an email with SmtpClient or MimeKit On some branch the same code works and on other impossible.
With MimeKit I have this exception:
MailKit.Security.SslHandshakeException
  HResult=0x80131500
  Message=An error occurred while attempting to establish an SSL or TLS connection.

This usually means that the SSL certificate presented by the server is not trusted by the system for one or more of
the following reasons:

1. The server is using a self-signed certificate which cannot be verified.
2. The local system is missing a Root or Intermediate certificate needed to verify the server's certificate.
3. A Certificate Authority CRL server for one or more of the certificates in the chain is temporarily unavailable.
4. The certificate presented by the server is expired or invalid.
5. The set of SSL/TLS protocols supported by the client and server do not match.

See https://github.com/jstedfast/MailKit/blob/master/FAQ.md#SslHandshakeException for possible solutions.

Inner exception 1:
AuthenticationException: Authentication failed, see inner exception.

Inner exception 2:
Win32Exception: Unable to decrypt the specified data.

And with SmtpClient I have this exception:
System.Net.Mail.SmtpException
  HResult=0x80131500
  Message=Failure sending mail.
  Source=System.Private.CoreLib

Inner exception 1:
AuthenticationException: Authentication failed, see inner exception.

Inner exception 2:
Win32Exception: Unable to decrypt the specified data.

I don't know how to solve my problem.
Because on my computer, it works on one branch and not on another.
Can you help me please?
Thanks in advance


text:
Q: Is it possible to get a best-guess for the entire input-audio from Google Cloud Speech? We're running into an issue trying to use google cloud speech (GCS) for audio-indexing purposes. We've tried two different setups:

*

*A single audio-file containing multiple speakers (high SNR, only
speech + silence) is sent to GCS.

*The audio-file is split into separate speakers, the segments concatenated,
and one audio-file per speaker is sent to GCS.

The problem is that large parts (~22%) of the speech doesn't get any output hypotheses regardless of setup (1 or 2 above).
The documentation states that "If the Speech API determines that an alternative has a sufficient Confidence Value, then that alternative is included in the response." Is this also true for the best hypothesis (that it's only included if the confidence is high enough) – and is that why parts of the speech is missing?
And the actual question as per the title: Is it possible to get a best-guess for the entire input-audio from Google Cloud Speech?


text:
Q: Trying to find name of TFS DB Table containing custom field data I have a quick question, what is the name of the TFS 2010 database table that contains values for any custom fields.
I did a query against the TFS_Warehouse DB and the dbo.DimWorkItem table. However, I cannot find any of my custom work item fields under this table.
Can someone point me to the correct TFS 2010 table containing the custom field data? When I worked with Quality Center, the tables were pretty well defined so it was easy to do backend DB queries. TFS does not seem that intuitive.
Thanks

A: you have to add "reportable" to field definition.
Example - FIELD name="Scope" refname="xxx.Scope" type="String" reportable="dimension"
Wait few minutes and you'll see field in warehouse DB

A: look,
you need to go to your collection database, and to check a table called something like Fields.
there, you will find the new field properties and the type as well.
you can change the type to string and to be reportable.
go to the table of the WORKITEMLATEST, and check the field- you can see the name of the field like what was mentioned in the FIELDS table,.
open your work item normally, edit that field information, click save...
you can see your data updated in the WORKITEMLATEST table
BUT...
the problem is the STRING type is limited... I tried to add more text.. it keep telling me that number of character is over limit !


text:
Q: Wiring an EE42-1200w transformer I have a ferrite core transformer with 6 pins on on side and 4 on the other. How do I wire it for 110-240 VAC in to 12-24 V out?
The transformer is called EE42-1200w there is a picture on this page: https://m.made-in-china.com/product/Electric-SMPS-Flyback-Ferrite-Core-Power-Ee40-Ee42-Ee49-Ee19-High-Frequency-Transformer-791962642.html

A: Only a transformer with a core made up of silicon steel laminations would be suitable for 50/60 Hz operation in a linear power supply.
A ferrite core transformer, on the other hand, would be suitable for use in a switch mode power supply operating at 15 - 50 kHz.
Here's the block diagram of a linear regulated power supply.

Both the step-down transformer, that sources the output current, and the filter would be quite bulky as they would be operating at 50 / 60 Hz.
Here's the block diagram of a switch mode power supply.

In this case both the step-down transformer, that sources the output current, and the filter would be quite compact as they would be operating at 15 - 50 kHz.


text:
Q: Avoiding "BASH-isms" in shell scripts Does there exist a tool similar to Perl::Critic that will inspect your shell scripts and point out flaws, portability issues, uses of non-standard programs without fallbacks, depreciated program uses, etc?
I realize that set -o posix will disable non-POSIX usage, but that won't tell me things I want to know, such as zsh indexing shell arrays starting at 1, and bash, from 0, and ash not supporting arrays at all.

A: There's checkbashisms. On Debian, it's shipped as part of the package maintainer tools.
Test your scripts under dash and posh. Both have a few non-POSIX constructs, but if your script works in both, it's likely to work in most places. (With the caveat that it's difficult to test typical shell scripts as they tend to have a lot of corner cases.)
If you intend for your scripts to be portable to embedded Linux platforms, test them with BusyBox. Note that BusyBox can be more or less restricted, depending on how small an embedded system you want; it's quite normal to have scripts that rely on a feature that some BusyBox installations don't have.
Note that non-portability doesn't come from the shell alone, it also comes from external utilities. OpenBSD and Solaris tend to have utilities with POSIX features and not much more, so they're good for testing for portability.
You'll want to refer to the POSIX specification, and other resources mentioned in this thread (especially the autoconf manual); but that's documentation, it doesn't help if you use a feature accidentally.