text:
Q: es2015 modules - how to name exports dynamically I would like to create a module, h, which exports one function for every HTML element. Here's how it might be used:
import {div, p} from 'h'

const myDiv = div(p('some text'))

Here's how that module is defined:
const h = {}
for (let tagName of ['div', 'p', /* ... */]) {
  h[tagName] = (...children) => {
    // ...
  }
}

export const div = h.div
export const p = h.p
/* ... */

I don't like that every export has to be listed explictly. How do I make these dynamic?

A:
how to name exports dynamically

You can't. import and export statements are specifically designed this way because they have to be statically analyzable, i.e. the import and export names have to be known before the code is executed.
If you need something dynamic then do what you are already doing: Export a "map" (or object). People can still use destructuring to just get what they want:
const {div} = h;


text:
Q: Call method in Fragment from Activity return java.lang.NullPointerException error I get this error when call Progress_Limits method in Fragment below ,
How initialize Fragment properly?
LogCat
09-05 06:37:30.075: E/AndroidRuntime(8676): FATAL EXCEPTION: main
09-05 06:37:30.075: E/AndroidRuntime(8676): Process: developer.mohab.gymee, PID: 8676
09-05 06:37:30.075: E/AndroidRuntime(8676): java.lang.RuntimeException: Unable to start activity ComponentInfo{developer.mohab.gymee/developer.mohab.gymee.Cardio.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.ContentResolver android.support.v4.app.FragmentActivity.getContentResolver()' on a null object reference
09-05 06:37:30.075: E/AndroidRuntime(8676):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2345)
09-05 06:37:30.075: E/AndroidRuntime(8676):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2405)
09-05 06:37:30.075: E/AndroidRuntime(8676):     at android.app.ActivityThread.access$800(ActivityThread.java:149)
09-05 06:37:30.075: E/AndroidRuntime(8676):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1324)
09-05 06:37:30.075: E/AndroidRuntime(8676):     at android.os.Handler.dispatchMessage(Handler.java:102)
09-05 06:37:30.075: E/AndroidRuntime(8676):     at android.os.Looper.loop(Looper.java:211)
09-05 06:37:30.075: E/AndroidRuntime(8676):     at android.app.ActivityThread.main(ActivityThread.java:5333)
09-05 06:37:30.075: E/AndroidRuntime(8676):     at java.lang.reflect.Method.invoke(Native Method)
09-05 06:37:30.075: E/AndroidRuntime(8676):     at java.lang.reflect.Method.invoke(Method.java:372)
09-05 06:37:30.075: E/AndroidRuntime(8676):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1016)
09-05 06:37:30.075: E/AndroidRuntime(8676):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811)
09-05 06:37:30.075: E/AndroidRuntime(8676): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.ContentResolver android.support.v4.app.FragmentActivity.getContentResolver()' on a null object reference
09-05 06:37:30.075: E/AndroidRuntime(8676):     at developer.mohab.gymee.Cardio.Progress.getCursor(Progress.java:70)
09-05 06:37:30.075: E/AndroidRuntime(8676):     at developer.mohab.gymee.Cardio.Progress.Prgress_Limits(Progress.java:43)
09-05 06:37:30.075: E/AndroidRuntime(8676):     at developer.mohab.gymee.Cardio.MainActivity.onCreate(MainActivity.java:55)
09-05 06:37:30.075: E/AndroidRuntime(8676):     at android.app.Activity.performCreate(Activity.java:5933)
09-05 06:37:30.075: E/AndroidRuntime(8676):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
09-05 06:37:30.075: E/AndroidRuntime(8676):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
09-05 06:37:30.075: E/AndroidRuntime(8676):     ... 10 more

Fragment contain method i want call
public  class Progress extends Fragment {
TextView Abs ;
TextView Per ;
MainActivity mainActivity ;
Database database ;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mainActivity = (MainActivity) getActivity();
    database = new Database(getActivity());
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.progress,container,false);
    Abs = (TextView) view.findViewById(R.id.above);
    Per = (TextView) view.findViewById(R.id.below);
    Prgress_Limits();
    return view ;
}
public  void Prgress_Limits(){
    Cursor cursor ;
    cursor = getCursor();
    int LAST_INPUT ;
    int FIRST_INPUT ;
    if(cursor!=null&&cursor.moveToFirst()) {
        Log.e("mohab", "cursor not null");
        int VALUE_COLUMN = cursor.getColumnIndex(Contract.Cardio_chart.Values.VALUE);
        FIRST_INPUT = cursor.getInt(VALUE_COLUMN);
        cursor.moveToLast();
        LAST_INPUT = cursor.getInt(VALUE_COLUMN);
        int abs = LAST_INPUT-FIRST_INPUT ;
        Abs.setText(""+abs);
        int per = (abs*100)/FIRST_INPUT ;
        Per.setText(""+per+" %");
    }
    else {

        Abs.setText("null");

        Per.setText("null");
    }

}
public Cursor getCursor() {
    Cursor c;
    String Selection;
    Cursor check;
    ContentResolver hesolver = getActivity().getContentResolver();
    check = hesolver.query(DatabaseFilter.ValueTable(), null, null, null, null);
    Cursor check2;
    ContentResolver resolver = getActivity().getContentResolver();
    check2 = resolver.query(DatabaseFilter.LimitTable(), null, null, null, null);
    if (check != null && check.moveToFirst() && check2 != null && check2.moveToFirst()) {
        int Offset = offset();
        int Limit = limit();
        Selection = "SELECT * FROM " + DatabaseFilter.valueTable_Name() + " LIMIT " + Limit + " OFFSET " + Offset + ";";
        SQLiteDatabase db = database.getReadableDatabase();
        c = db.rawQuery(Selection, null);
    } else {
        ContentResolver sesolver = getActivity().getContentResolver();
        c = sesolver.query(DatabaseFilter.ValueTable(), null, null, null, null);
    }
    return c;
}
public int offset() {
    Cursor save;
    ContentResolver resolver = getActivity().getContentResolver();
    save = resolver.query(DatabaseFilter.LimitTable(), null, null, null, null);
    save.moveToLast();
    int high = save.getColumnIndex(Contract.Cardio_chart.Limits.HIGH);
    int Offset = save.getInt(high);
    save.close();
    return Offset;
}

public int limit() {

    Cursor h;
    ContentResolver resolver = getActivity().getContentResolver();
    h = resolver.query(DatabaseFilter.ValueTable(), null, null, null, null);
    h.moveToLast();
    int id = h.getColumnIndex(Contract.Cardio_chart.Values._ID);
    int last_chart_input = h.getInt(id);
    int Offset = offset();
    int Limit = last_chart_input - Offset;
    h.close();
    return Limit;
}

}
How i instantiate Fragment and call Progress_Limits Methode From Activity
  protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
     p = new Progress();
    getSupportFragmentManager().beginTransaction()
            .add(R.id.group, p)
            .commit();
    p.Prgress_Limits();
    database = new Database(this) ;
    setSpinner();
    addEntries(0, 0, true);
    addPlus();

}

A: Here:
p.Prgress_Limits();  //<<<<
database = new Database(this) ;

p.Prgress_Limits() causing issue becuase this method is called just after calling commit() method,which means probably Fragment is not ready. so call of getActivity() returning null.
To fix this issue call p.Prgress_Limits(); in onResume of Activity or use Handler to make some delay in accessing methods from live Fragment

A: The recommended and easiest way to communicate with fragments is with interfaces.
Define a interface in your activity, and let your fragment implement that interface.
Example:
To declare a interface
public interface ActivityToFragment{ void executeMethodInFragment(); }

And in your activity, declare a variable for this interface,
private ActivityToFragment mListener;

Now tie the listener to fragment
p = mListener

now implement the interface in your fragment
public  class Progress extends Fragment implements ActivityToFragment

redpajama_set_name: RedPajamaStackExchange


text:
Q: Одинаковые действия контроллов, datasource которых ссылается на один bindingsource Есть несколько Combobox и ListBox элементов на форме. Их свойства DataSource ссылаются на общий bindingsource, который в свою очередь ссылается на коллекцию некоторых объектов.
Но происходит такая вещь: при выборе из списка Combobox'a выделяется соответствующий элемент в ListBox (а на Select стоит обработчик событий, так что это приводит к тем действиям, к которым он не должен приводить).
Я знаю, что привязка данных привязывает данные, но связывает ли оно ещё и действия?

A: А что если сделать 2 разных DataBindings (для Combobox и ListBox соответственно), а уже им в DataSource навесить одну коллекцию? Что значит "добавляются динамически" и почему такой вариант "никак"? DataBindings ведь на одну коллекцию будут ссылаться.


text:
Q: Build/Test monitoring tool over teamcity This is my first team city based tool development project. I want to develop Java based web tool for reporting and monitoring of our build/test jobs running on teamcity.
Can you suggest any teamcity plugins which I can use for this development, I was planning to use springboot based framework and use team city rest api to query teamcity server. Having said that I keep hearing there are plugins available for writing such tools. Any pointers and suggestion is appreciated.

A: I recomment do not write the REST operations by yourself. Just use the teamcity-rest-client


text:
Q: Haskell Exercise Mooc FI Do notation This is the exercise from https://haskell.mooc.fi/ training
-- Ex 5: define the IO operation readUntil f, which reads lines from
-- the user and returns them as a list. Reading is stopped when f
-- returns True for a line. (The value for which f returns True is not
-- returned.)
--
-- Example in GHCi:
--   *Set11> readUntil (=="STOP")
--   bananas
--   garlic
--   pakchoi
--   STOP
--   ["bananas","garlic","pakchoi"]

readUntil :: (String -> Bool) -> IO [String]
readUntil f = todo

Would you be able to provide me a hint / solution using do notation ?
I am a beginning with the do notation and the "conditional logic" as well as looping is too complex for me at the  moment.
Thank you so much

A: With only do-notation and conditional statements I found the following solution:
readUntil :: (String -> Bool) -> IO [String]
readUntil f = do x <- getLine;
                 if f x then (return []) else (do xs <- readUntil f
                                                  return (x : xs))

The function first reads one line with getLine from prelude and then checks whether (f x) is true. It then returns just the empty list. We can't just write ... if f x then [] ... because [] has not the type IO [String] but just [String]. To make [] the type IO [String] we can use the function return or pure but with do-notation I use the return function, because it is included in the Monad typeclass.
If f x equals False we then use a second do-block to recursively call the function again and again until we get an Input for which f x == True and therefore returns the empty list. The do-notation is necessary because xs must have type [String], but readUntil has the type IO [String]. We can't use the : ("cons") operator with object of type IO String and therefore can't generate the list we want. We then add x to the list xs of all our other inputs and return it.
For a more general version of the function readUntil which is able to work with any monad and not just the IO Monad, see the comment of Will Ness


text:
Q: How to create a pojo file for json response in java with jackson Here is my json response from an API.
{
  "job_1": {
  "metaData": {},
  "extractedData": {
      "score_a": [1,2,3,4],
      "score_b": [40,40,72,136],
      "score_c": [3,3.5,3,2,3,9],
      "score_d": [1659752409254420,1659752416354536,1659752424695028,1659752431823242 ]
  }
  }
}

In response job_1 can be vary. maybe its job_3 or job_4.
How to create a pojo file for this response?
Thanks in advance.

A: I modified the request so that each job is unlabeled in request body to be considered as an object in the list
The request is like this :
{
"jobs":[
 {
    "metaData": {},
    "extractedData": {
        "score_a": [
            1,
            2,
            3,
            4
        ],
        "score_b": [
            40,
            40,
            72,
            136
        ],
        "score_c": [
            3,
            3.5,
            3,
            2,
            3,
            9
        ],
        "score_d": [
            1659752409254420,
            1659752416354536,
            1659752424695028,
            1659752431823242
        ]
    }
},
     {
    "metaData": {},
    "extractedData": {
        "score_a": [
            1,
            2,
            3,
            4
        ],
        "score_b": [
            40,
            40,
            72,
            136
        ],
        "score_c": [
            3,
            3.5,
            3,
            2,
            3,
            9
        ],
        "score_d": [
            1659752409254420,
            1659752416354536,
            1659752424695028,
            1659752431823242
        ]
    }
}
]
}

With the addition annotation @JsonSerialize to metadata to allow display of an object that does not contain elements
public class response {
  List<job> jobs;

  public static class job {

    MetaData metaData;
    ExtractedData extractedData;

  @JsonSerialize
  public static class MetaData {

    //insert code

  }

  public static class ExtractedData {

     List<Integer> score_a;
     List<Integer> score_b;
     List<Integer> score_c;
     List<Long> score_d;

  }
 }
}

I tried it like this
@Controller
public class test {

  @RequestMapping(value = "/test", method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
  public ResponseEntity<response> testPost(@RequestBody response res) {

    return ResponseEntity.ok(res);

  }

}

A: Use HashMap to handle dynamic keys job_1 can vary. maybe it's job_3 or job_4.
public class response {
  HashMap<String, job> jobs;

  public static class job {

    MetaData metaData;
    ExtractedData extractedData;

  @JsonSerialize
  public static class MetaData {

    //insert code

  }

  public static class ExtractedData {

     List<Integer> score_a;
     List<Integer> score_b;
     List<Integer> score_c;
     List<Long> score_d;

  }
 }
}


text:
Q: Python: Extracting multiple values from dict x = json.loads(y)
z1 = (x[0][0])
z2 = (x[0][1])
z3 = (x[0][2])
z4 = (x[0][3])

etc...
How do we check if [4],[5],[6] exists in dict, then print/assign the result if it does?

A: As @Antonio Margaretti indicated, you shall use x.get('key'). Your full code will be:
x = json.loads(y)
z1 = (x[0][0])
z2 = (x[0][1])
z3 = (x[0][2])
z4 = (x[0][3])

for i in (4,5,6):
    k= x[0].get(i)
    if k is not None:
        print(k)

A: You can use x.get("key") where x is your dict. So if  such key presented in your dict the data will be returned, else you will get None.
Small example:
data = x.get("some_key")
if data is not None:
    print(data)


text:
Q: How does Chromium browser determine the default keboard layout on Linux? I'm trying to figure out how the Chromium Browser sets up the default onscreen  keyboard layout / locale on Debian (and general Linux OS as well).
Does Chromium Browser sniff the OS settings and/or ask it for locale information? Or does Chromium Browser ask the user for their preference?
I haven't found any helpful documentation specific to Chromium Browser, only some for Chromium OS. Are they similar in their implementation?


text:
Q: I cannot catch exceptions in method annotated @Transactional I cannot catch exceptions in method annotated @Transactional.
I want to send mail to created user if save operation succeded.
When username is already in use PostgreSQL throws exception PSQLException which is extention of SQLExcpetion which is extention of Exception. I couldn't catch Exception and PSQLException then I tried to catch Throwable and this is working, but not resolve my problem and come to that catching Throwable is the cause of new problem.

*

*When I get DataIntegrityViolationException (this is an excpetion from Spring) I want to propagate its because I have handler for my controller which returns statement and status specified for this concrete exception. And when I catch Throwable I have to throw always RuntimeException.

*Very strange thing is that emailSender.sendEmail() is called even if some exception was thrown. But if userRepository is throwing an exception any method should not be called and exception should be caught in catch statement and then transaction should be rollback. Do I correct understand transactions or not?
Implementation of my service:
@Transactional
public UserEntity createUser(UserEntity user) {
    try {
        final UserEntity saved = userRepository.save(user);
        emailSender.sendEmail(saved);
        return saved;
    } catch (Throwable t) {
        throw new RuntimeException();
    }
    return null;
}

Come to that when I try debug this method using IDEA, debugger doesn't enter catch statement, but my handlers annotated @RestControllerAdvice are catching this exception.
Any idea what's wrong or maybe do you know similar questions?

A: Experienced the same issue. Fixed using saveAndFlush.
This make sense because with transactional, transaction is being committed(to db) after executing the function. But with saveAndFlush, it is not the case.


text:
Q: Why can't I assign a property to an object using bracket notation + a variable? I'm very new to Vuex, and trying to assign a value to a Vuex state, (state.map.status.isReady for this one).
However, I want to make my code reusable, so I created a function changeMapStatus(state, key, value) in order to achieve that.
This function modifies the property state.map.status.key to value it received.
However, when I call the mutation with this.$store.commit('changeMapStatus', 'isReady', true) from a component file, it simply removes the state.map.status.isReady and that property becomes undefined.
On the another hand, if I change the function to
changeMapStatus(state, value) {
  state.map.status.isReady = value;
}

it somehow works.
Can you help me which point I get it wrong?
Thanks so much!

store.js (Vuex)

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    map: {
      status: {
        isReady: false,
      },
    },
  },
  mutations: {
    changeMapStatus(state, key, value) {
      state.map.status[key] = value;
    }
  },
});

A: You could pass an object as parameter that contains key and value as follows :
changeMapStatus(state, myObj) {
  state.map.status[myObj.key] = myObj.value;
}

and call it like:
this.$store.commit('changeMapStatus', {key:'isReady', value:true})

A: According to Vuex official docs, mutation takes 2 parameters state and payload. You can use the spread operator to get values from the payload.
changeMapStatus(state, {key, value}) {
  state.map.status[key] = value;
}

this.$store.commit('changeMapStatus', {key: 'isReady', value: true})

Or else you can use it like this
changeMapStatus(state, payload) {
  state.map.status = {
      ...state.map.status,
      ...payload,
  }
}

this.$store.commit('changeMapStatus', { isReady: true });


text:
Q: Paste multi-cursor copy/paste WITHOUT newlines in sublime text Is there a way to paste a multi-cursor (Ctrl+d, Ctrl+d, ... Ctrl+C) select, stripped of its newlines?
If [...] represents the highlight, and ⦙ the cursor:
The ⦙[red].
The ⦙[blue].
The ⦙[green].

And if I pasted I'd get:
red
blue
green⦙

but instead I want
redbluegreen⦙

Is this possible?

A: Save the following script @:
/Packages/Paste Without NewLines/paste_without_newlines.py

import sublime, sublime_plugin

class paste_without_newlines( sublime_plugin.TextCommand ):
    def run( self, edit ):

        clipboard = sublime.get_clipboard()
        clipboard = clipboard.replace( "\n", "" )
        sublime.set_clipboard( clipboard )
        self.view.run_command( "paste" )

To execute via Command Palette > Paste Without NewLines, add the following code @:
/Packages/Paste Without NewLines/Default.sublime-commands

[
    {
        "caption": "Paste Without NewLines",
        "command": "paste_without_newlines",
    },
]

To execute via Ctrl + Shift + Alt + V, add the following code @:
/Packages/Paste Without NewLines/Default.sublime-keymap

[
    {
        "keys": ["ctrl+shift+alt+v"],
        "command": "paste_without_newlines",
    },
]

A: For anyone else stumbling across this, there's a sublime text package that solves this exact problem, it's called Paste PDF Text Block.
You can then Ctrl+Alt+v the text you want to copy from a pdf file into a new file in Sublime Text.
Worked a treat, and is a good solution if you don't know enough about making your own packages in sublime text, like me :(


text:
Q: SQL; Full left, right, upper, inner, backwards joins Can't seem to get my head around this.  I have three tables (stock,sales,POs) relating to products with one common field which can join them all toghether.  I have a fourth table which has all the products in it.  The product may or may not have information in these tables (stock,sales,POs) but will have a record in the Product table.
I need to end with up one row per product which has information in one of the three tables (stock, sales and POs).
A simplified view of the tables are below:
Product Table, Ref, Description
Stock Table, Ref, Current_Stock
Sales Table,Ref, Qty_Sold
POs Table, Ref, Qty_Outstanding
I need to end with the following:
Ref, Description, Current_Stock, Qty_Sold, Qty_Outstanding
Thanks
Nig

A: Perhaps, the easiest and most straightforward way to do this would be to left-join all the detail tables to the Product table, then filter out the products that have no matches at all.
So, this would essentially be @Santhosh's solution with a small tweak (emphasized):
SELECT
  pr.Ref,
  pr.Description,
  st.Current_Stock,
  sa.Qty_Sold,
  po.Qty_Outstanding
FROM Product pr
LEFT JOIN Stock st ON st.Ref = pr.Ref
LEFT JOIN Sales sa ON sa.Ref = pr.Ref
LEFT JOIN POs   po ON po.Ref = pr.Ref
WHERE st.Ref IS NOT NULL
   OR sa.Ref IS NOT NULL
   OR so.Ref IS NOT NULL
;

There's also a somewhat less obvious alternative: union all the detail tables, then pivot the detail data. The resulting set will only contain references to the products that have at least some detail information. So, you could then just inner join the resulting set to Product to access the product descriptions for the output.
If your SQL product supports the PIVOT clause, you could do it like this:
SELECT
  p.Ref,
  p.Description,
  s.Current_Stock,
  s.Qty_Sold,
  s.Qty_Outstanding
FROM (
  SELECT
    Ref,
    Current_Stock,
    Qty_Sold,
    Qty_Outstanding
  FROM (
    SELECT
      Ref,
      'Current_Stock' AS Attribute,
      Current_Stock   AS Value
    FROM Stock
    UNION ALL
    SELECT
      Ref,
      'Qty_Sold',
      Qty_Sold
    FROM Sales
    UNION ALL
    SELECT
      Ref,
      'Qty_Outstanding',
      Qty_Outstanding
    FROM POs
  ) d
  PIVOT (
    SUM(Value) FOR Attribute IN (
      Current_Stock,
      Qty_Sold,
      Qty_Outstanding
    )
  ) p
) s
INNER JOIN Product p ON p.Ref = s.Ref
;
There's also an older and more universal method of pivoting, for which you need to employ grouping and conditional aggregation:
SELECT
  p.Ref,
  p.Description,
  SUM(CASE Attribute WHEN 'Current_Stock'   THEN d.Value END) AS Current_Stock,
  SUM(CASE Attribute WHEN 'Qty_Sold'        THEN d.Value END) AS Qty_Sold,
  SUM(CASE Attribute WHEN 'Qty_Outstanding' THEN d.Value END) AS Qty_Outstanding
FROM (
  SELECT
    Ref,
    'Current_Stock' AS Attribute,
    Current_Stock   AS Value
  FROM Stock
  UNION ALL
  SELECT
    Ref,
    'Qty_Sold',
    Qty_Sold
  FROM Sales
  UNION ALL
  SELECT
    Ref,
    'Qty_Outstanding',
    Qty_Outstanding
  FROM POs
) d
INNER JOIN Product p ON p.Ref = d.Ref
GROUP BY
  p.Ref,
  p.Description
;

A: SELECT P.REF, P.DESCRIPTION, S.CURRENT_STOCK, SALES.QTY_SL, POS.QTY_OUTSTANDING
FROM PRODUCTS P
LEFT JOIN STOCK S
ON S.REF = P.REF
LEFT JOIN SALES SALES
ON SALES.REF = P.REF
LEFT JOIN POS
ON POS.REF = P.REF

A: Assuming REF is unique and is used like a foreign key in all tables
Maybe you can try
SELECT pt.REF, pt.DESCRIPTION, st.CURRENT_STOCK, sat.QTY_SOLD, pot.QTY_OUTSTANDING
FROM PRODUCTTABLE pt
INNER JOIN STOCKTABLE st
ON st.REF = pt.REF
INNER JOIN SALESTABLE sat
ON sat.REF = pt.REF
INNER JOIN POSTABLE pot
ON pot.REF = pt.REF

I just love this Graphical summary of join operations very usefull!


text:
Q: Why aren't data repositories static? I was looking at the repository method for an ASP.NET MVC app and noticed a static class wasn't used.
Since the repo is CRUD, why not make it static?

A: 1) It's difficult to do unit testing with static classes (if you are testing a class that depends on your repository, you want that test to work against a fake 'mocked' repository object instead of your real one)
2) You often want to have 1 repository instance per-request to make it easier to ensure that uncommited changes from one user don't mess things up for another user.

A: Repository pattern increase testability, static classed decreases it.


text:
Q: How can I sync music with my iPhone 3G? What is the best way to sync music with my iPhone 3G?

A: I'm not sure if it's the best way, but Rhythmbox with libimobiledevice (both installed by default in lucid) works for me. There are a couple of glitches to be aware of, however:

*

*There's no full-library sync.  You have to manually drag individual songs to the iPhone.

*About 10 seconds or so after Rhythmbox transfers the songs, the iPhone screen switches to "Sync in Progress." You have to wait until after that screen goes away before you eject the iPhone, or the music won't actually get synced. This usually takes 5-10 minutes for me (more if I transfer a lot of songs)

*The first time you go to the "Music" app on the iPhone, you have to wait for it to rebuild the library.

A: I am using gtkpod ipod Manager to sync my music and videos. Sadly, you have to do some manual stuff to sync videos, in this case you have to set the video length by hand.


text:
Q: multi-dimensional array type as template argument The kokkos scientific computing library implements the multi-dimensional array (which they call View) such that it knows which dimensions are fixed at compile time and which dimensions are runtime variable. For example, to create a 3-dimensional array data of shape (N0, N1, N2), you can do one of the followings:
View<double***> data(N0, N1, N2); // 3 run, 0 compile
View<double**[N2]> data(N0, N1);  // 2 run, 1 compile
View<double*[N1][N2]> data(N0);   // 1 run, 2 compile
View<double[N0][N1][N2]> data();  // 0 run, 3 compile

If I want to implement something like View, how should I handle the the template arguments? i.e. How should I count number of asterisks and square brackets (and get the numbers in those square brackets) of the template argument in my implementation?

A: This question can be split into two parts.

*

*Get the dimensions from the input template parameter T.

*Constructor accepts different numbers of values as run-time dimensions.

Let's look at it one by one.

To solve the first problem, a non-type typelist is used to represent the dimensions.
template <size_t... Ns>
struct Dimension {
    template <size_t N>
    using prepend = Dimension<N, Ns...>;
};

0 means the dimension is determined at run-time. Now we construct a template class hoping to decompose its template parameter into the dimensions we want.
template <typename>
struct Analysis;

// Analysis<int**> -> Dimension<0, 0>
// Analysis<int[1][2] -> Dimension<1, 2>
// Analysis<int*[3]> -> Dimension<0, 3>

Using alias template nested inside specialization to decompose the pointers / [] layer by layer recursively. Compile-time dimensions and run-time dimensions are represented separately and joined together.
Whenever meeting a *, prepend a 0 in the dynamic dimension. Whenever meeting a [N], prepend an N in the static dimension.
template <typename T>
struct Analysis {
    using sdim = Dimension<>; // static
    using ddim = Dimension<>; // dynamic
    using dim = Dimension<>;  // all
};

template <typename T, size_t N>
struct Analysis<T[N]> {
    using nested = Analysis<T>;
    using sdim = typename nested::sdim::template prepend<N>;
    using ddim = typename nested::ddim;
    using dim = join_t<ddim, sdim>;
};

template <typename T>
struct Analysis<T*> {
    using nested = Analysis<T>;
    using sdim = typename nested::sdim;
    using ddim = typename nested::ddim::template prepend<0>;
    using dim = join_t<ddim, sdim>;
};

T[] is similar to T*, not shown here. Now we have,
static_assert(std::is_same_v<
            Analysis<int[1][2][3]>::dim,
            Dimension<1, 2, 3>>);
static_assert(std::is_same_v<
            Analysis<int***>::dim,
            Dimension<0, 0, 0>>);
static_assert(std::is_same_v<
            Analysis<int*[1][2]>::dim,
            Dimension<0, 1, 2>>);

Demo

Since we've got the dimensions, constructing a View-like thing is simple. Its constructor accepts a bunch of parameters with a default value as run-time dimensions.
template <typename T>
struct View {
    using dim = typename Analysis<T>::dim;
    View(size_t dim0 = -1, size_t dim1 = -1, size_t dim2 = -1) { // you could write more
            if (get_v<dim, 0> == 0 && dim0 != -1) {
                // run-time
            }
            if (get_v<dim, 1> == 0 && dim1 != -1) {}
            if (get_v<dim, 2> == 0 && dim2 != -1) {}

        }
};

Demo


text:
Q: Mysql error when running Hive Query I see the below error when running hive query. Not able to fix it even after reinstalling hive.Please suggest.
select col1, col2, col3, col4 from y2014_01 order by col4 DESC limit 10;
Job Submission failed with exception 'java.io.FileNotFoundException(File file:/usr/local/hadoop/apache-hive-1.0.0-bin/lib/mysql-connector-java-5.1.21-bin.jar does not exist)
FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.mr.MapRedTask

A: The below points may help you

*

*Check whether the jar is present in the correct location or not.

*Ensure that the jar is not corrupted. Try executing the following command
jar -tf /usr/local/hadoop/apache-hive-1.0.0-bin/lib/mysql-connector-java-5.1.21-bin.jar

*Ensure that this jar is present in the hive metastore host

*Restart the hivemetastore service after placing this jar.


text:
Q: If the center $Z(G)$ has index $n$ in $G$, then every conjugacy class of $G$ has at most $n$ elements. I am looking at a proof for this, which basically starts off by looking at the conjugacy class of $x$, where $|cl_{G}(x)|=n$ and then claims we can complete the proof if we can create a surjective map from $cl_{G}(x)$ to the set of cosets of $Z(G)$.
I don't understand why doing this will complete the proof? The mapping, by the way, will be defined as $\phi(gZ(G))=gxg^{-1}$. Can someone please explain how this surjective mapping solves the problem?

A: The size of the conjugacy class of $g \in G$ is the index of the centralizer of $g$:
$$
C(g)=\{x\in G : xg=gx \}
$$
The result follows because the center of $G$ is clearly contained in the centralizer of $g$.


text:
Q: convert polynomial to list type I am trying to convert a polynomial
for example
2x^2

and turn it into a list
[2,0,0]

where it can be used for the numpy poly1d function
here is my current code
def convert_poly_to_list_type(poly):
    # sort list and split
    poly = sorted(str(poly).split())
    poly1 = []
    for i in poly:
        if i == "+":
            pass
        else:
            poly1.append(i)
    # take out "+"
    exponents = []
    for i in poly1:
        x = i.split("^")
        if len(x) == 1:
            exponents.append(0)
        else:
            print(x)
            exponents.append(int(x[1]))
    # find largest exponent
    integers_in_list = int(max(exponents)) + 1
    numpy_list = [0] * integers_in_list
    # create a list
    for i in poly1:
        i = i.split("^")
        if len(i) == 1:
            numpy_list[len(numpy_list) - 1] += int(i[0])
        else:
            z = i[0]
            z = int(z[:len(z) - 1])
            y = int(i[1])
            numpy_list[len(numpy_list) - 1 - y] += z
    return numpy_list

but it gets the error:
z = int(z[:len(z) - 1])
ValueError: invalid literal for int() with base 10: ''

Can someone please give me some code to fix this?  I have searched for 2 hours now and haven't found a solution

A: This produces your error:
In [31]: int('')
Traceback (most recent call last):
  File "<ipython-input-31-e4f84bb32d50>", line 1, in <module>
    int('')
ValueError: invalid literal for int() with base 10: ''

So
z[:len(z) - 1]

must be producing an empty string ''.  And z must then either be '' or '1' (one character).
Code like this needs some debugging print statements while tracking down problems.  There's nothing mysterious about that; you just have to be careful and pay attention to the details!

A: One can almost get sympy to do all the work, including grouping the like terms. Annoyingly, we need to do some string manipulation to get from "2x^2" to "2*x^2". Maybe there is a better way.
from sympy import sympify, Poly, var
import re

s = "2x^2 + 7x^2 + 11x - 20"
# see here: https://stackoverflow.com/questions/2763750/how-to-replace-only-part-of-the-match-with-python-re-sub
s2 = re.sub(r"(\d)([a-z])", r"\1*\2", s)

# define a variable x
x = var("x")
# construct a sympy polynomial from string
# WARNING: this may call eval
expr = Poly(sympify(s2), x)
# get the coefficients
coefs = expr.coeffs()
print(coefs)
# [9, 11, -20]


text:
Q: how to programmatically clear TextInput using useRef I'm trying to automatically clear the TextInput after the form has been submitted using useRef.
const inputRef = useRef()

This shows a list of properties. However, following does not work:
    const clearInput = () => {
        inputRef.current.value = ""
    }

It shows that value does not exist.
I'm currently using react-native-google-places-autocomplete:
<GooglePlacesAutocomplete
    ref={inputRef}
    placeholder='Search'
    minLength={1}
    autoFocus={false}
    returnKeyType={'search'}
    keyboardAppearance={'light'} /keyboardAppearance https://facebook.github.io/react-native/docs/textinput.html#keyboardappearance
    listViewDisplayed={focus}
    fetchDetails={true}
    textContentType={'fullStreetAddress'}
    autoCapitalize={'words'}
    selectionColor={'red'}
    clearButtonMode={'always'}
    // other properties
/>

A: Your ref, inputRef doesn't refer to the text input, but the GooglePlacesAutocomplete component instead. The text input inside that component is what you need a ref to.
If you look at the code you can see that its ref is defined as "textInput" (line 717), and that it is selected by the autocomplete component with this.refs.textInput (line 166)
Considering this, you should be able to access the text input ref via the autocomplete component like this:
inputRef.current.refs.textInput

A: You can also use  inputRef.current?.clear();


text:
Q: На каком этапе компиляции обрабатываются шаблоны? Если директивы препроцессора обрабатывает препроцессор, то на каком этапе компиляции обрабатываются шаблоны?
Я отчего то думал, что этим то же занимается препроцессор, но посмотрев в его вывод, обнаружил, что шаблоны не были заменены.

A: В большинстве популярных реализаций никакого отдельного этапа для обработки шаблонов в последовательности фаз трансляции не требуется. Шаблоны обрабатываются на этапе... компиляции, т.е. когда компилируется все остальное.
Доминируют сейчас реализации (MSVC, GCC, Clang), которые независимо и безусловно транслируют все требуемые инстанцирования шаблонных сущностей в каждой единице трансляции, возможно порождая множественные копии одного и того же объектного кода (и данных), разбросанные по разным объектным файлам. Затем линкеру поручается задача по удалению дубликатов.
Однако существуют и такие "необычные" реализации, как, например, "родной" компилятор С++ в Sun Solaris: сначала компилятором собирается предварительная информация о требуемых инстанцированиях шаблонов, затем она обрабатывается глобально линкером, и только затем снова вызывается компилятор и один раз делается трансляция требуемых определений шаблонов.


text:
Q: How to add template url to custom directives in codeigniter I Want to load a view file in angular custom directives as a template. my directive code
I want to know a proper way to use templates in codeigniter using angularjs.
If any farther information needed please let me know . this is my first question to this site.. thanks
My Controller for cooks
class Cooks extends MX_Controller {

    /**
     * Renders an angular view.
     * @param string $pageName
     */
    function getpage($pageName){
             $this->load->view($pageName);
      }

}

routing
$route['cooks/getPage/(:any).html']='cooks/getPage/$1';

directive
app.directive('profileSettings',function () {
      return {
        restrict: 'E',
        require:'ngModel',
        templateUrl: 'cooks/getPage/profileSettings',

      }
  });

A: Lets assume you have a controller called Ng_pages. And this controller has the index method that takes one parameter - $pageName.
class Ng_pages extends CI_Controller
{

    /**
     * Renders an angular view.
     * @param string $pageName
     */
    public function index($pageName)
    {
        // put here the code to check whether the requested page exists
        // and load the requested view
        $this->load->view($pageName);
    }

}

And the routing rule for the controller:
$route['ng-pages/(:any).html'] = 'Ng_pages/index/$1';

Also you will need to change templateUrl in your directive. Note you might need to set an absolute url.
templateUrl: 'ng-pages/profileSettings.html'


text:
Q: AngularJS page navigation What approach do you recommend to navigate pages from nav menu using angularjs?
Pages will have footer and header html using ng-include to have common templates. I found ng-view to navigate between pages.

A: In this example, there's a module named navList and a controller and a method navClass inside it. Using a special service in angular.js, $location which parses the URL in the browser and makes the URL available in the application. Finally, just match the URL hash with the parameter passed.

var navList = angular.module('navList', []);

navList.controller('navCtrl', ['$scope', '$location', function ($scope, $location) {
    $scope.navClass = function (page) {
        var currentRoute = $location.path().substring(1) || 'home';
        return page === currentRoute ? 'active' : '';
    };
}]);

Home

About Us

Contact Us

JsFiddle Link

A: Angular router is what you need:
https://github.com/angular-ui/ui-router/blob/master/README.md


text:
Q: LinkedIn API feeds I'm looking into an issue where a clients LinkedIn feeds on their website have stopped showing. Debugging the problem I've found that I get a 403 error shown below:

Member xxxxxx does not have permission to get company xxxxx

As the LinkedIn authentication process can be quite difficult to comprehend, I had a look online to see if others have had the same problem, and managed to find this. It suggests there have been recent changes to the LinkedIn API and users are now required to be the administrator of the company. What exactly does this mean?
From the very beginning we have simply been accessed the feeds by generating a url like this:

https://api.linkedin.com/v1/companies/xxxx/updates?oauth2_access_token=ACCESS_TOKEN

This has worked in the past. Do we need to regenerate the Secret and API keys?
Update
Looking at the announced changes here:
https://developer.linkedin.com/support/developer-program-transition
It suggests that the following endpoint will still work (which is exactly what I have):

/v1/companies/{id}

So I'm not sure what I'm missing.

A: is the access token generated by a account witch is Admin of that company page?
If not hen you will get 403.
The requester needs to be admin of that comapny page in order to get company updates.


text:
Q: What is the exact meaning of "rather"? What is the meaning of rather in the following sentence?

I can speak english rather fluently.

From online dictionaries, I found different definitions: quite, to a slight degree, to some degree, fairly ,and so on. So I am a little bit confused with the exact meaning of "rather".
Consider the following degrees from 1 to 10, which number do you give to "rather fluent"?

1. very little: beginner english learner
5. not fluent, not influent!
10. very much: a native english speaker

Does rather have a negative or positive connotation, or is it neutral?

A: Cambridge explains that

We use rather to give emphasis to an adjective or adverb. It has a similar meaning to quite when quite is used with gradable words. It is more formal than quite.

From your sentence, we could understand that the speaker is not 100% fluent in English, but rather close to it.
However, rather fluently can mean very fluently, too. People often use it in a self-effacing way out of modesty, moderating or attenuating their skill. Not in a professional environment, though -  there, not modesty, but rather honesty and accuracy is required.


text:
Q: imported apiService undefined in typescript We are using typescript and exporting one class as following (we are using nuxt and class style component if this relates to webpack issue).
export class ApiService {
  static apiHost = '/';
}

When we try to import it as following, it gives ApiService as undefined and so gives error on apiHost access as ApiService gets undefined.
import { ApiService } from '../services/api-service';
my tsconfig is as following.
{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": false,
    "removeComments": true,
    "noLib": false,
    "allowSyntheticDefaultImports": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowJs": true,
    "target": "esnext",
    "resolveJsonModule": true,
    "sourceMap": true,
    "outDir": "./dist",
    "esModuleInterop": true,
    "moduleResolution": "node",
    "baseUrl": "./",
    "skipLibCheck": true, // TODO: Remove. Temporary. https://github.com/nuxt/typescript/issues/49
    "paths": {
      "~/*": ["server/*"],
      "@/*": [
        "client/*"
      ],
    },
    "types": [
      "node",
      "@types/node",
      "@nuxt/vue-app",
      "vuex-class-component/dist",
    ]
  },
  "include": [
    "server/**/*",
    "client/**/*"
  ],
  "exclude": [
    "node_modules"
  ]
}

my webpack.config.js
const webpack = require('webpack');
const path = require('path');
const nodeExternals = require('webpack-node-externals');
const WebpackShellPlugin = require('webpack-shell-plugin');

module.exports = {
  entry: ['webpack/hot/poll?1000', './server/main.ts'],
  watch: true,
  target: 'node',
  externals: [
    nodeExternals({
      allowlist: ['webpack/hot/poll?1000'],
    }),
  ],
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
    ],
  },
  mode: 'development',
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new WebpackShellPlugin({ onBuildEnd: ['node dist/main.js'] }),
  ],
  output: {
    path: `${__dirname}/dist`,
    publicPath: '/',
  },
};

Command I am running
ts-node -r tsconfig-paths/register server/main.ts

A: Actually I didn't post entire code as I thought it wasn't necessary.
But service was also calling back the class where service was imported.
import { AuthConfig } from '../config/auth-config';
export class ApiService {
  static apiHost = '/';

  static mgr = new Oidc.UserManager(
    new AuthConfig().IdentityServerOAuth2Config, // This was causing issue as it was causing cyclic imports.
  );
}

Follwing is the code where cyclic dependency was happening.
import ApiService from '../services/api-service';
export class AuthConfig {
   `${ApiService.apiHost}api/callback` // This was again calling back the apiService resulting in cyclic dependency.
}


text:
Q: finding exact variable in tho list on prolog I think this question must be solved :))
concert(dtatu, [jack, volker, rachel]).

concert(tmegadeth, [volker, rachel]).

concert(ssoad, [kurt, rachel]).

concert(trbeyonce, [kurt,jack,volker]).

I want to implement the predicate audiance(L1, L2). returns the list of all people(L2) who have watched all the concerts in L1. The lists L1 and L2 must not contain any duplicates.
audiance([tatu,beyonce],X). returns X=[jack,volker]

audiance(X,[volker,rachel]). returns X=[tatu,megadeth]

audiance(X,[kurt,volker,rachel])

audiance([tatu, beyonce],[jack, volker]) returns true

audiance(X,Y). returns X=[tatu], Y=[jack, volker, rachel]; X=[megadeth, soad], Y=[rachel];...

this is very hard for me. But I think If I know how to do it, I would not have any problem with prolog :)))

A: To avoid duplication, first you can extract all performers from the clause database and find corresponding audiences for a specific set of performers. A solution could be as follows:
subset([], []).
subset(Xs, [_|Ys]) :- subset(Xs, Ys).
subset([X|Xs], [X|Ys]) :- subset(Xs, Ys).

allPerformers(Ts) :- findall(T, concert(T, _), Ts).
performers(T) :- allPerformers(Ts), subset(T, Ts).

audience1([T], L) :- concert(T, L).
audience1([T|Ts], L) :- concert(T, L0), audience1(Ts, L1), intersection(L0, L1, L).

audience(X, Y) :- performers(X), audience1(X, Y).


text:
Q: Change figure limits without changing zoom I have a GUIDE GUI containing axes on which I initially set appropriate limits:
set(axes,'YLim',[ymin ymax]);

At one point I programatically set the axes to adjust limits dynamically with
axes.YLimMode = 'auto';

At another point I want to programatically set the axes to have fixed limits again with
axes.YLimMode = 'manual';
set(axes,'YLim',[ymin ymax]);

Problem: At this point I want to maintain the currently visible part of the axes via an appropriate zoom (that can be zoomed out by the user via the zoom out tool). How can this be accomplished?

A: Turns out it was pretty simple in the end:
axes.XLimMode = 'manual';
axes.YLimMode = 'manual';

% save current "zoomed in" limits (not needed if you want to set other values later)
xcur = axes.XLim;
ycur = axes.YLim;

% set axes limits to desired "zoomed out" state
set(axes,'XLim',[xmin xmax]);
set(axes,'YLim',[ymin ymax]);
zoom(figure,'reset'); % sets and remembers current state as "zoomed out state"

% restore (or set freely) "zoomed in" limits
set(axes,'XLim',xcur);
set(axes,'YLim',ycur);

The important part is zoom(figure,'reset');, which internally sets the current limits as the maximally zoomed out state. One can then (programmatically) zoom in by setting arbitrary values for XLim/YLim. However the user is still able to zoom out manually until reaching the maximally zoomed out state as set before (which would not be possible when leaving out the zoom command).


text:
Q: Complex aggregation using Java 8 streams Given a class Item:
public class Item {
    private String field1;
    private String field2;
    private String field3;
    private Integer field4;

    // getters, constructor...
}

And another class Group (field1 and field2 store the equivalent fields from Item):
public class Group {
    private String field1;
    private String field2;
}

I have a List<Item> which I need to aggregate into a map of the following structure:
Map<Group, Map<Field3, List<Field4>>>

Example data:
Field1 | Field2 | Field3 | Field4
------ | ------ | ------ | ------
"f1"   | "f2"   | "a"    | 1
"f1"   | "f2"   | "a"    | 2
"f1"   | "f2"   | "a"    | 3
"f1"   | "f2"   | "b"    | 4
"f1"   | "f2"   | "b"    | 5
"f1"   | "f2"   | "c"    | 6
"f1a"  | "f2a"  | "a"    | 7
"f1a"  | "f2a"  | "a"    | 8

The expected result would look like:
Group(field1=f1a, field2=f2a)={b=[7, 8]}, Group(field1=f1, field2=f2)={a=[1, 2, 3], b=[4, 5], c=[6]}

So far I have been able to aggregate by Field1, Field2 and Field3, such that I have the following structure (where GroupEx represents a POJO that holds Field1, Field2 and Field3):
Map<GroupEx, List<Field4>>

The code to aggregate in this way is:
Map<GroupEx, List<Integer>> aggregated = items.stream()
    .collect(Collectors.groupingBy(item -> new GroupEx(x.getField1(), x.getField2(), x.getField3())
           , Collectors.mapping(Item::getField4, Collectors.toList())));

I'm struggling to get the syntax correct to allow me to group by Field1 and Field2, and to then group by Field3 and Field4 into a map in the way I need.
The "long hand" syntax is:
Map<Group<String, String>, Map<String, List<Integer>>> aggregated = new HashMap<>();
for (Item item : items) {
    Group key = new Group(item.getField1(), item.getField2());
    Map<String, List<Integer>> field3Map = aggregated.get(key);
    if (field3Map == null) {
        field3Map = new HashMap<>();
        aggregated.put(key, field3Map);
    }

    List<Integer> field4s = field3Map.get(item.getField3());
    if (field4s == null) {
        field4s = new ArrayList<>();
        field3Map.put(item.getField3(), field4s);
    }

    field4s.add(item.getField4());
}

Is someone able to show me how my target grouping can be achieved?

A: This is where the downstream collectors feature comes handy.
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.mapping;
import static java.util.stream.Collectors.toList;

...

List<Item> list = ....
Map<Group, Map<String, List<Integer>>> map =
    list.stream().collect(groupingBy(i -> new Group(i.getField1(), i.getField2()),
                                     groupingBy(Item::getField3, mapping(Item::getField4, toList()))));

First, you group the items by their Group field (you a Map<Group, List<Item>> at this point), then you map each value (List<Item>) to a map again where you group by the field3 (Map<Group, Map<Field3, List<Item>>).
Then you map the values in the second map by the field4 and you collect them into a list, to finally get a Map<Group, Map<Field3, List<Field4>>.
Given your input, it outputs:
{Group{field1='f1a', field2='f2a'}={a=[7, 8]}, Group{field1='f1', field2='f2'}={a=[1, 2, 3], b=[4, 5], c=[6]}}


text:
Q: How to draw from a thread, but smarter?     private void DisplayThread()
    {
        while (RunDisplayThread)
        {
            Thread.Sleep(30);
            MPLastMessage.Text = MPTemplate.MPRET[(int)MP.MPReturn];
            Invoked();
            TickCount++;
            TickCountLabel.Text = string.Format("Tick Count: {0}", TickCount);
        }
    }

    private void Invoked()
    {
        while (MP.Drawing) { };
        g.DrawImage(MP.offscreen, 50, this.Height-300);
    }

So, this works, but after reading this,
Draw image on a form from a separate thread
I am clearly doing this in a less-than-intelligent way. Can anyone explain what the difference is between the suggested answer and what I'm doing? I've been teaching myself C#, and I'm at a loss for how that answer works.

A: Although the link you provided is named "draw (...) from a separate thread", the drawing itself still happens on the Gui thread, using Control.Invoke() (http://msdn.microsoft.com/en-us/library/zyzhdc6b.aspx).
Your Invoked() method runs on the "DisplayThread". I don't know where the g variable comes from though, is this a class variable set in the OnPaint method? If so chances are the DrawImage would fail if it would take more time than the code in OnPaint.


text:
Q: Creating a type definition for a property named "type" using JSON schema I'm trying to create a JSON schema for an existing JSON file that looks something like this:
{
  "variable": {
    "name": "age",
    "type": "integer"
  }
}

In the schema, I want to ensure the type property has the value string or integer:
{
  "variable": {
    "name": "string",
    "type": {
      "type": "string",
      "enum": ["string", "integer"]
    }
  }
}

Unfortunately it blows up with message: ValidationError {is not any of [subschema 0]....
I've read that there are "no reserved words" in JSON schema, so I assume a type of type is valid, assuming I declare it correctly?

A: The accepted answer from jruizaranguren doesn't actually answer the question.
The problem is that given JSON (not JSON schema, JSON data) that has a field named "type", it's hard to write a JSON schema that doesn't choke.
Imagine that you have an existing JSON data feed (data, not schema) that contains:
"ids": [ { "type": "SSN", "value": "123-45-6789" },
         { "type": "pay", "value": "8675309" } ]

What I've found in trying to work through the same problem is that instead of putting
"properties": {
                    "type": {                 <======= validation chokes on this
                        "type": "string"
}

you can put
"patternProperties": {
                    "^type$": {
                        "type": "string"
}

but I'm still working through how to mark it as a required field. It may not be possible.
I think, based on looking at the "schema" in the original question, that JSON schemas have evolved quite a lot since then - but this is still a problem. There may be a better solution.

A: According to the specification, in the Valid typessection for type:

The value of this keyword MUST be either a string or an array. If it is an array, elements of the array MUST be strings and MUST be unique.
  String values MUST be one of the seven primitive types defined by the core specification.

Later, in Conditions for successful validation:

An instance matches successfully if its primitive type is one of the types defined by keyword. Recall: "number" includes "integer".

In your case:
{
  "variable": {
    "name": "string",
    "type": ["string", "integer"]
  }
}


text:
Q: distortion correction with gpu shader bug So I have a camera with a wide angle lens. I know the distortion coefficients, the focal length, the optical center. I want to undistort the image I get from this camera. I used OpenCV for the first try (cv::undistort), which worked well, but was way too slow.
Now I want to do this on the gpu. There is a shader doing exactly this documented in http://willsteptoe.com/post/67401705548/ar-rift-aligning-tracking-and-video-spaces-part-5
the formulas can be seen here:
http://en.wikipedia.org/wiki/Distortion_%28optics%29#Software_correction
So I went and implemented my own version as a glsl shader. I am sending a quad with texture coordinates on the corners between 0..1.
I assume the texture coordinates that arrive are the coordinates of the undistorted image. I calculate the coordinates for the distorted point corresponding to my texture coordinates. Then I sample the distorted image texture.
With this shader nothing in the final image changes. The problem I identified through a cpu implementation is, the coefficient term is very close to zero. The numbers get smaller and smaller through radius squaring etc.. So I have a scaling problem - I can't figure it out what to do differently! I tried everything... I guess it is something quite obvious, since this kind of process seems to work for a lot of people.
I left out the tangential distortion correction for simplicity.
#version 330 core

in vec2 UV;

out vec4 color;

uniform sampler2D textureSampler;

void main()
{
    vec2 focalLength = vec2(438.568f, 437.699f);
    vec2 opticalCenter = vec2(667.724f, 500.059f);
    vec4 distortionCoefficients = vec4(-0.035109f, -0.002393f, 0.000335f, -0.000449f);

    const vec2 imageSize = vec2(1280.f, 960.f);

    vec2 opticalCenterUV = opticalCenter / imageSize;

    vec2 shiftedUVCoordinates = (UV - opticalCenterUV);

    vec2 lensCoordinates = shiftedUVCoordinates / focalLength;

    float radiusSquared = sqrt(dot(lensCoordinates, lensCoordinates));
    float radiusQuadrupled = radiusSquared * radiusSquared;

    float coefficientTerm = distortionCoefficients.x * radiusSquared + distortionCoefficients.y * radiusQuadrupled;

    vec2 distortedUV = ((lensCoordinates + lensCoordinates * (coefficientTerm))) * focalLength;

    vec2 resultUV = (distortedUV + opticalCenterUV);

    color = texture2D(textureSampler, resultUV);
}

A: I see two issues with your solution. The main issue is that you mix two different spaces. You seem to work in [0,1] texture space by converting the optical center to that space, but you did not adjust focalLenght. The key point is that for such a distortion model, the focal lenght is determined in pixels. However, now a pixel is not 1 base unit wide anymore, but 1/width and 1/height units, respectively.
You could add vec2 focalLengthUV = focalLength / imageSize, but you will see that both divisions will cancel out each other when you calculate lensCoordinates. It is much more convenient to convert the texture space UV coordinates to pixel coordinates and use that space directly:
vec2 lensCoordinates = (UV * imageSize - opticalCenter) / focalLenght;

(and also respectively changing the calculation for distortedUV and resultUV).
There is still one issue with the approach I have sketched so far: the conventions of that pixel space I mentioned earlier. In GL, the origin will be the lower left corner, while in most pixel spaces, the origin is at the top left. You might have to flip the y coordinate when doing the conversion. Another thing is where exactly pixel centers are located. So far, the code assumes that pixel centers are at integer + 0.5. The texture coordinate (0,0) is not the center of the lower left pixel, but the corner point. The parameters you use for the distortion might (I don't know OpenCV's conventions) assume the pixel centers at integers, so that instead of the conversion pixelSpace = uv * imageSize, you might need to offset this by half a pixel like pixelSpace = uv * imageSize - vec2(0.5).
The second issue I see is
float radiusSquared = sqrt(dot(lensCoordinates, lensCoordinates));

That sqrt is not correct here, as dot(a,a) will already give the squared lenght of vector a.


text:
Q: Add to cart button function I have a problem where I want to add a product from the catalogue to cart. I manage to do it for a single product but when I refresh back and add another product, the previous product disappear and only show the latest product that I choose. I'm stuck here and don't know how to do it. I hope someone could help me
Below is the code that I have tried
Product.java
package Model;

public class Product {

    private int id;

    private String prodName;

    private String desc;

    private double pricePerUnit;

    private int qtyInStock;

    public Product(int id, String prodName, String desc, double pricePerUnit, int qtyInStock) {

        this.id = id;

        this.prodName = prodName;

        this.desc = desc;

        this.pricePerUnit = pricePerUnit;

        this.qtyInStock = qtyInStock;

    }

    public String getProdName() {

        return prodName;

    }

    public double getPricePerUnit() {

        return pricePerUnit;

    }

    public int getQtyInStock() {

        return qtyInStock;

    }

    @Override

    public String toString() {

        return "ProductModel{" + "id=" + id + ", prodName=" + prodName + ", desc=" + desc + ", pricePerUnit=" + pricePerUnit + ", qtyInStock=" + qtyInStock + '}';

    }

}

ListOf.java
package Model;

import java.util.ArrayList;

import java.util.List;

public final class ListOf {

    public static List<Product> products = new ArrayList();

    static{

        products.add(new Product(1,"Academic Book","Learn to program",50.00,100));

        products.add(new Product(2,"Notebook","Latest notebook in the market",5500.00,10));

        products.add(new Product(3,"Travel Charger","Travel Adapter",15.00,10));

        products.add(new Product(4,"Lipstick","Red Matter Color",25.00,100));

    }

    public static List<Product> cartItems = new ArrayList();

}

ShoppingController.java

package Controller;

import Model.ListOf;
import Model.Product;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "ShoppingController", urlPatterns = {"/shopping"})
public class ShoppingController extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //step 1: fetch data
        List<Product> result = ListOf.products
                .stream()
                .collect(Collectors.toList());

        request.setAttribute("productList", result);
        //step 2: do business logic

        //step 3: generate output
        RequestDispatcher dis=request.getRequestDispatcher("shopping.jsp");
        dis.forward(request, response);
    }
}

CartController.java

package Controller;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "CartController", urlPatterns = {"/cart"})
public class CartController extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        RequestDispatcher dis=request.getRequestDispatcher("cart.jsp");
        dis.forward(request, response);
    }

}

The output should be the list of product that the user has clicked "Add to cart". It should be more than 1 product if the user clicked more than 1 product but I only manage to get only 1 product in the cart and the previous product will disappear. Thanks in advance


text:
Q: Custom style with Qt Has anybody experience in building a custom style in Qt? What I have in my mind is a complete new style that affects all kind of widgets. I have seen some examples in the web for a custom combo box. But I have no idea how much time and code it takes to build a "complete" new custom style ... maybe someone can give me a hint.
We think of using Qt 4.3 (or even newer) ...

A: Check out the Stylesheets facility in Qt 4.  While it's still a hassle, it's way easier than doing a full-on custom style.  You can just adjust one visual facet at a time and try it out.
It pays attention to inheritance.  So if you style the font in QWidget, then every visual widget will also use that font.  And so on.

A: I have developed a "new" style that changed the appearance of much of an application.  It did take some time, and quite a bit of experimentation.  I also derived my style from the generic windows style, to allow it to handle some of the stuff I didn't want to mess with.  All told, I think it took me a week to get most of what I wanted, with practically no prior exposure to the styles.
In order to actually develop one, I would get into the source for their styles example, which has a "wood" style.  I put my own style in place of the example style, and started changing things while using the example program to check how it looked.  Depending on how you are developing it, you might want to have a configuration file so you can easily change some of the values without recompiling.

A: We've done it in the past (in Qt 3), and it's extremely time-consuming. We had a lot of problems with flickering, redraws not working the way we expected, sluggish behavior, bugs in the Qt implementation. It a lot less straight-forward than it seems, and there's little support or user experience too. Unless you need something really particular (as we did), I'd say it's not worth the trouble.
Other frameworks are supposed to make it easier (some Java-based?), but I don't have first hand experience.

A: You might want to look at existing styles. You can find quite a few of them on kde-look.org, in the Styles / 4.0 section.

A: If you don't need to radically change the widget style, you might want to try using widget style sheets:
         http://doc.qt.digia.com/4.4/stylesheet.html


text:
Q: My sql query is right or wrong ? It showing me error like Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean my query is
$statement = "SELECT * FROM profile_details
       WHERE    YEAR(CURDATE())-YEAR(dob) BETWEEN '$search_age'
                                              AND '$search_age1'
            AND gender LIKE '$search_gender'
        OR main_caste LIKE '$search_relegion'
        OR education_type LIKE '$search_qualification'
        OR occupation LIKE '$search_occupation'";

When i echo mysqli_error($con); it's showing message
You have an error in your SQL syntax; check the manual that corresponds
         to your MariaDB server version for the right syntax
         to use near
     'SELECT * FROM profile_details
      WHERE YEAR(CURDATE())-YEAR(dob) BETWEEN '20' AND '' at line 1

My connection file is given below
<?php

/*Default time zone ,to be able to send mail */
date_default_timezone_set('Asia/Kolkata');

//connect database
$con = mysqli_connect ("localhost","root","root","testdb") or die ("Unable to connect. Check your connection parameters.");         //host, username, password, database name

        //database connect error
        if (mysqli_connect_errno())
        {
        echo "Failed to connect to MySql: " . mysqli_connect_errno();
        }

?>

And the search result php file is .. I am using pagination for search results... On this page i am getting error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SELECT * FROM profile_details WHERE
    <?php
                date_default_timezone_set('Asia/Kolkata');
                require_once("includes/config.php");
                require_once("includes/user_pagination.php");
                global $con;
                //if(isset($_POST['home_quick_search'])){

                //get serch data from index.php
                    $search_gender = $_GET['s_gender'];
                    $search_relegion = $_GET['s_religion'];
                    $search_occupation = $_GET['s_occupation'];
                    $search_age = $_GET['s_age'];
                    $search_age1 = $_GET['s_age1'];
                    $search_qualification = $_GET['s_qualification'];

                $page = (int)(!isset($_GET["page"]) ? 1 : $_GET["page"]);
                if ($page <= 0) $page = 1;

                $per_page = 10; // Set how many records do you want to display per page.

                $startpoint = ($page * $per_page) - $per_page;

                $statement = "`profile_details` WHERE `DATEDIFF(YEAR,dob,CURDATE())` AS dob BETWEEN '$search_age' AND '$search_age1' AND `gender` LIKE '$search_gender' OR `main_caste` LIKE '$search_relegion' OR `education_type` LIKE '$search_qualification' OR `occupation` LIKE '$search_occupation' ORDER BY `user_id` ASC";

//$statement = "SELECT * FROM profile_details WHERE YEAR(CURDATE())-YEAR(dob) BETWEEN '$search_age' AND '$search_age1' AND gender LIKE '$search_gender' AND main_caste LIKE '$search_relegion' AND education_type LIKE '$search_qualification' AND occupation LIKE '$search_occupation'";

                $results = mysqli_query($con,"SELECT * FROM {$statement} LIMIT {$startpoint} , {$per_page}") or die (mysqli_error($con));

                    if (mysqli_num_rows($results) != 0) {

                    // displaying records.
                    $i = 0;
                        while ($row_user = mysqli_fetch_array($results)) {

                        $u_id = $row_user['user_id'];
                        $u_pid = $row_user['profile_id'];
                        $u_gender = $row_user['gender'];
                        $u_fname = $row_user['first_name'];
                        $u_relegion = $row_user['main_caste'];
                        $u_city = $row_user['city'];
                        $u_image = $row_user['photo'];
                        $u_dob = $row_user['dob'];

                        //age calculation
                        $dateOfBirth = $u_dob;
                        $today = date("Y-m-d");
                        $diff = date_diff(date_create($dateOfBirth), date_create($today));
                        //echo 'Age is '.$diff->format('%y');
                        $age = $diff->format('%y');
                        //age calculation ends

                        $u_status_all = $row_user['user_status'];
                        $u_status_of = $row_user['user_status']=='OFFLINE';
                        $u_status_on = $row_user['user_status']=='ONLINE';

                     echo'

';

                              if (!empty($u_image)){
                                  echo '';
                              }
                              else{
                                  echo '';
                              }

                            echo '

Profile ID: '.$u_pid.'

Age: '.$age.' Yrs, '.$u_gender.'

View Full Profile

';

    if (!isset($u_status_on) && $u_status_of){
                            echo "Nope";
                        }
                        elseif (isset ($u_status_of) && $u_status_on){
                            echo " ";
                        }
                        else {
                        if (isset ($u_status_of)){
                            echo " ";
                            }
                        }

                        echo "
                            $u_status_all

";

                    }

                    } else {
                                            echo "Sorry ! No Profiles are found.";
                                    }

            //  }

            ?>

                    <?php echo pagination($statement,$per_page,$page,$url='?'); ?>

Please help ..thanks in advance

A: A couple of notes:
The AND operator has a higher order of precedence than the OR operator. Adding parens can make your intent more clear to a future reader. Did you intend to check age only if the gender matched, and ignore the condition on age otherwise?
The calculation of age seems a bit strange, since it entirely ignores the month and day. The normative pattern is to compare the bare DATE column to expressions that return DATE values...
 WHERE ( t.dob >  DATE(NOW()) - INTERVAL 25 YEAR AND
         t.dob <= DATE(NOW()) - INTERVAL 19 YEAR
       )

As a demonstration of the values returned by those expressions ...
SELECT DATE(NOW()) - INTERVAL 25 YEAR AS b
     , DATE(NOW()) - INTERVAL 19 YEAR AS e

returns
b           e
----------  ----------
1992-02-10  1998-02-10

For debugging a problem with the SQL, echo or var_dump the value of the SQL text, before submitting it for execution.
Then examine the SQL.

The code pattern shown in the question, including values in the SQL text, is a pattern we frequently see in code that is vulnerable to SQL Injection. We can't tell whether this code is vulnerable, because we can't tell whether those values have been properly escaped.

A: SELECT ...
    FROM ( SELECT ... ) AS x  -- You need parens around derived query

a AND b OR c
is treated as
( a AND b ) OR c

Please add parens to your boolean expression to convince us that you did it right.


text:
Q: Assembly code to system functions (iPhone) possibly a really dumb question, but could someone explain why one could not write assembly code to trigger system functions or control hardware? For example, would it not be possible to write code to switch screen off/on or even the device's phone?
I am not talking about jailbreaking the device, nor making an app for the app store. Normal app with assembly to call system functions.
If indeed possible, anyone have a good reference or starting point of achieve such tasks?
Thanks

A: iPhones use a memory-protected operating system in which each user process is contained in its own virtual memory address space.  The address space is protected by the memory management unit (MMU) hardware and trying to access memory outside of regions given to the process by the OS will result in an exception.  The OS reserves hardware memory ranges to itself and does not make it available to user processes.  As such, it is not possible to directly interface to the hardware from a user process.

A: It is certainly possible to call system functions from assembly code. And what do you think a C or C++ application does? It does exactly that. C/C++ and assembly code all ultimately convert (at compile time) into machine code that the CPU executes.
I'm not sure where the guide would be for doing things like this, but you can certainly run a C program in a debugger and see how it calls various system functions or you can disassemble this program and read the disassembly without running the program in the debugger.
In any event, you will not get more control over the device from a program written in assembly than from a program written in C. The OS should restrict direct access to certain I/O devices and memory areas at the CPU level, where there's no distinction between assembly and C, it's all the same to the CPU, just a bunch of instructions in machine code.


text:
Q: Visual Studio does not format source code with implicitly typed array (`new[] {1,}`) Visual Studio 2015 usually does a reasonable job formatting code, but it seems to have trouble with implicitly typed arrays.
For instance, the input
var    x     =    new   [   ]     {
           1    ,
         }    ;

gets formatted as
var x = new[]     {
           1    ,
         };

It seems the [] trips VS, because temporarily removing it yields:
var x = new {
    1,
};

Which looks much better and is what I'm hoping for (after adding the [] again or course).
Did I misconfigure VS, or is this a bug perhaps?

A: As per the comments, I have submitted a ticket at github/roslyn.


text:
Q: Unable to make an Producer-Consumer instance with list in c++ guys. I am learning about the Producer-Consumer Problem. My professor gave us an example code using a classical int array to share resources between the two threads. It works as expected, however, I wanted to try it using std:list class from C++ and it doesn't work as expected. The consumer seems not to respect sem_wait(&full); so it tries to consume many times when there is nothing in the shared list.
Original code with array buffer
#include    <pthread.h>
#include    <semaphore.h>
#include    <stdlib.h>
#include    <stdio.h>
#include    <unistd.h>

#define    N 2
#define    TRUE 1

int    buffer[N], in = 0, out = 0;
sem_t  empty, full, mutexC, mutexP;

void *producer(void *arg) {

   while(TRUE) {
       sleep(rand()%5);

       sem_wait(&empty);
       sem_wait(&mutexP);

       buffer[in] = rand() % 100;
       printf("Producing buffer[%d] = %d\n", in, buffer[in]);
       in= (in+1) % N;

       sem_post(&mutexP);
       sem_post(&full);

   }
}

void *consumer(void *arg) {

   while(TRUE) {

       sleep(rand()%5);
       sem_wait(&full);
       sem_wait(&mutexC);

       printf("Consuming buffer[%d] = %d\n", out, buffer[out]);
       out = (out+1) % N;

       sem_post(&mutexC);
       sem_post(&empty);

   }
}

int main(int argc, char *argv[ ]) {
    pthread_t cons, prod;

    sem_init(&mutexC, 0, 1);
    sem_init(&mutexP, 0, 1);
    sem_init(&empty, 0, N);
    sem_init(&full, 0, 0);

    pthread_create(&prod, NULL, producer, NULL);
    pthread_create(&cons, NULL, consumer, NULL);

    pthread_exit(0);
}

My implementation with list:
#include    <pthread.h>
#include    <semaphore.h>
#include    <stdlib.h>
#include    <unistd.h>
#include    <iostream>
#include    <list>

#define    TRUE 1
#define    N 2

using namespace std;

list<int> sharedList;

sem_t  empty, full, mutexC, mutexP;

void *producer(void *arg) {

   while(TRUE) {

       sleep(rand()%5);

       sem_wait(&empty);
       sem_wait(&mutexP);
       int prod = rand() % 100;
       cout << "producing: " << prod << endl;
       sharedList.push_back(prod);

       sem_post(&mutexP);
       sem_post(&full);

   }
}

void *consumer(void *arg) {

   while(TRUE) {

       sleep(rand()%5);

       sem_wait(&full);
       sem_wait(&mutexC);

       if (!sharedList.empty()) {
           cout << "consuming: ";
           cout << sharedList.front() << endl;
           sharedList.pop_front();
       } else {
           cout << "not possible to consume" << endl;
       }
       sem_post(&mutexC);
       sem_post(&empty);
   }
}

int main(int argc, char *argv[ ]) {
    pthread_t cons, prod;

    sem_init(&mutexC, 0, 1);
    sem_init(&mutexP, 0, 1);
    sem_init(&empty, 0, N);
    sem_init(&full, 0, 0);

    pthread_create(&prod, NULL, producer, NULL);
    pthread_create(&cons, NULL, consumer, NULL);

    pthread_exit(0);
}

The - unexpected - logs from my implementation:
producing: 73
consuming: 73
not possible to consume
producing: 44
consuming: 44
producing: 9
producing: 65
consuming: 9
producing: 87
consuming: 65
consuming: producing: 29
87
not possible to consume
consuming: 29
producing: 9
producing: 60
consuming: 9
producing: 78

Can somebody explain to me what is happening?
Thanks in advance!

A: In the first place, note that in both programs:

*

*with only one producer ever contending for semaphore mutexP, that semaphore serves no useful purpose.

*Likewise, with only one consumer ever contending for semaphore mutexC, that serves no useful purpose either.

Now, consider what purpose is served in your first program by initializing semaphore empty with value 2 instead of value 1: I presume that you will agree that doing so allows the producer to run concurrently with the consumer, one position ahead.  This is ok because accesses to different array elements do not conflict.
But when your storage is a std::list instead of an array, it is not ok for two threads to manipulate it concurrently if one of them modifies it.  There are several complementary ways to look at it, among them:

*

*a std::list is a single object, access to which must be synchronized, whereas an array is merely an aggregate of its elements, not a distinct object of its own as far as synchronization requirements are concerned.

*a std::list has members -- maintaining the current list size, for example -- that are used by all manipulations, access to which must be synchronized.
However you choose to look at it, you must ensure that the std::list cannot be accessed concurrently by two threads if one of those threads modifies it.

A: Follow up
Although the second code does have its errors, it turns out that macOS does ignore sem_wait(). I tried to initialize all the semaphores with 0 expecting the program to enter a deadlock, but it actually didn't. So, if running on macOS, please refer to this answer

A: rand() % 6 can generate some interesting sequences; so the spurious wakeup not possible to consume is to be expected.
Beyond that, the only confusing bit is:
consuming: producing: 29
87
not possible to consume

Which isn't that confusing; the io statements interleave.  If they didn't, you would see this as:
consuming: 87
producing: 29
not possible to consume

where the last statement would be a result of checking the condition just before the producer created 29.


text:
Q: how to call model method in the model relationship method in laravel I have four tables namely: users, games, activities. The users and activities tables have Many to Many relationship. And, games and activities have One to Many relationship respectively. Of course I've that fourth pivot table for the Many to Many relationship above, namely, activity_user.
Inside the Game model, I have this relationship method to call all activities owned by that game, like so:
/**
 * Get game activities
 *
 * @return hasMany
 */
public function activitiesFilter()
{
    $user_id = auth('api')->id();
    return $this->hasMany(Activity::class)->where('status_id', 2)->multiplayer()->whereDoesntHave('users', function($q) use ($user_id){
        $q->where('user_id', $user_id);
    });//select only this game approved(status_id===2) activities whose multiplayer count have not been reached and which this user have not joined/created
}

To select activities whose multiplayer count have not been reached, I've a scope function inside the Activity model, like so:
/**
 * Scope a query to only include activity whose multiplayer count have not been reached.
 *note that the activities table have an int field for multiplayer.
 * @return \Illuminate\Database\Eloquent\Builder
 */
public function scopeMultiplayer($query)
{
    return $query->where('multiplayer','>', $this->users()->count());
}

However, this doesn't seem to work as $this->users()->count() seems to always return 0.
Your solution will be highly appreciated.


text:
Q: Emacs + Cider (Clojure) + Auto-Complete: How to get the docstring? I am trying to properly configure emacs to write my Clojure code. I based my Emacs configurations on this good blog post.
However, I did change a few settings like the theme he is using etc. I have been checking to get Auto-Complete (Eldoc? I am not sure) to display the docstring of the functions in Clojure, and from my own code.
I want to see the documentation like in that screenshot:

However, I cannot get the "yellow" documentation box to appear. I am not sure if this is due to a misconfiguration in my .emacs file, or if it is a command I have to use or...
Here is my .emacs file:
(add-to-list 'custom-theme-load-path "~/.emacs.d/lib/noctilux-theme")

(require 'package):
  (add-to-list 'package-archives
    '("marmalade" . "http://marmalade-repo.org/packages/")
    '("melpa" . "http://melpa.milkbox.net/packages/"))

;; Initialize all the ELPA packages (what is installed using the packages commands)
(package-initialize)

;; Set bigger fonts
(set-default-font "Courier New-13")

;; Setup to have a french keyboard layout working
(require 'iso-transl)

;; Show parenthesis mode
(show-paren-mode 1)

;; rainbow delimiters
(global-rainbow-delimiters-mode)

;; paredit
(add-hook 'clojure-mode-hook 'paredit-mode)
(add-hook 'nrepl-mode-hook 'paredit-mode)
(global-set-key [f7] 'paredit-mode)

;; theme
(load-theme 'noctilux t)

;; clojure-mode
(global-set-key [f9] 'cider-jack-in)
(add-hook 'clojure-mode-hook 'turn-on-eldoc-mode)

;; nrepl
(add-hook 'nrepl-interaction-mode-hook 'nrepl-turn-on-eldoc-mode)
(setq nrepl-popup-stacktraces nil)
(add-to-list 'same-window-buffer-names "*nrepl*")
(add-hook 'nrepl-mode-hook 'paredit-mode)

;; Auto complete
(require 'auto-complete-config)
;(add-to-list 'ac-dictionary-directories "~/.emacs.d/ac-dict")
(setq ac-delay 0.0)
;(setq ac-use-quick-help t)
(setq ac-quick-help-delay 0.0)
;(setq ac-use-fuzzy 1)
;(setq ac-auto-start 1)
;(setq ac-auto-show-menu 1)
(ac-config-default)

;; ac-nrepl
(require 'ac-nrepl)
(add-hook 'nrepl-mode-hook 'ac-nrepl-setup)
(add-hook 'nrepl-interaction-mode-hook 'ac-nrepl-setup)
(eval-after-load "auto-complete" '(add-to-list 'ac-modes 'nrepl-mode))

(defun set-auto-complete-as-completion-at-point-function ()
  (setq completion-at-point-functions '(auto-complete)))
(add-hook 'auto-complete-mode-hook 'set-auto-complete-as-completion-at-point-function)

(add-hook 'cider-repl-mode-hook 'set-auto-complete-as-completion-at-point-function)
(add-hook 'cider-mode-hook 'set-auto-complete-as-completion-at-point-function)

;; scroll one line at a time (less "jumpy" than defaults)

(setq mouse-wheel-scroll-amount '(1 ((shift) . 1))) ;; one line at a time

(setq mouse-wheel-progressive-speed nil) ;; don't accelerate scrolling

(setq mouse-wheel-follow-mouse 't) ;; scroll window under mouse

(setq scroll-step 1) ;; keyboard scroll one line at a time

Update based on @syohex's comment bellow
Here is what I see in my CLJ buffers:

In the NREPL, I do see a "v" instead of a "d" (by the way, what does these letters means?). As I said in my comment, in NREPL, I do see the yellow box appearing, then when the popup appears, then the doc yellow box disapear. In the CLJ code buffers, the yellow box never open.
Final Update
After some more testing, everything is working as expected. When the popup first shows, the yellow box disapear. However, when I start selecting different choices, then it reappears, at the right place.
Also, it started working in the CLJ buffers, and I see the letter "v" instead of "d" as seen in the sreenshot above. Maybe I forgot to start the NREPL, would have to re-test.
In any case, everything is working as expected.

A: nrepl-mode-hook, nrepl-interaction-mode-hook, nrepl-mode are obsoleted. You should use cider-mode-hook, cider-repl-mode-hook, cider-mode instead of them respectively.
And you should set ac-quick-help-delay to value more than 0(for example 0.5).
Patch is below.
--- nconf-orig.el   2014-05-21 16:51:40.056185465 +0900
+++ conf-new.el 2014-05-21 16:53:11.936182181 +0900
@@ -43,7 +43,7 @@
 ;(add-to-list 'ac-dictionary-directories "~/.emacs.d/ac-dict")
 (setq ac-delay 0.0)
 ;(setq ac-use-quick-help t)
-(setq ac-quick-help-delay 0.0)
+(setq ac-quick-help-delay 0.5)
 ;(setq ac-use-fuzzy 1)
 ;(setq ac-auto-start 1)
 ;(setq ac-auto-show-menu 1)
@@ -51,9 +51,10 @@

 ;; ac-nrepl
 (require 'ac-nrepl)
-(add-hook 'nrepl-mode-hook 'ac-nrepl-setup)
-(add-hook 'nrepl-interaction-mode-hook 'ac-nrepl-setup)
-(eval-after-load "auto-complete" '(add-to-list 'ac-modes 'nrepl-mode))
+(add-hook 'cider-mode-hook 'ac-nrepl-setup)
+(add-hook 'cider-repl-mode-hook 'ac-nrepl-setup)
+(add-to-list 'ac-modes 'cider-mode)
+(add-to-list 'ac-modes 'cider-repl-mode)

 (defun set-auto-complete-as-completion-at-point-function ()

A: Actually this configuration and the former ac-nrepl is deprecated, refer to the new package ac-cider
(require 'ac-cider)
(add-hook 'cider-mode-hook 'ac-flyspell-workaround)
(add-hook 'cider-mode-hook 'ac-cider-setup)
(add-hook 'cider-repl-mode-hook 'ac-cider-setup)
(eval-after-load "auto-complete"
    '(add-to-list 'ac-modes 'cider-mode))

A:
the yellow box appears first, then when the autocompletion popup
  appears, the yellow box with the docs disapear.

This behavior is caused by(setq ac-quick-help-delay 0.5) since 0.5s is too fast
Change 0.5 to a bigger number (minimal value to work is 0.9 on my computer, but this may dependent on your computer's performance) or
delete (setq ac-quick-help-delay 0.5) Since this would use the default: about 2.5s, it can resolve the problem.

A: I am viewing this in 2020 and ac-cider is deprecated but you can use company-mode instead.
Use M-x package-install company to install and follow the cider docs to configure it for cider-repl-mode and cider-mode


text:
Q: Suppose you're given two mutually exclusive events A and B, with P(A) = 1/4 and P(B) = 1/3. What is P(A(complement)intersect with B)
and vice versa.
since they are mutually exclusive they cant intersect so what does that mean for the complement

A: $A^{c} \cap B=B$ because $A$ and $B$ are mutually exclusive.


text:
Q: Misaligned title in UINavigationBar since iOS6 Ever since iOS 6 I have several problems with using custom styling in my application. I use a custom font and several UIAppearance proxies. A problem I can't get my head around is the misalignment of the title in my UINavigationBar. In iOS 5 everything worked fine and was correctly aligned.
Since iOS6 has been released and custom styling is not uncommon I assume this isn't a bug but my misunderstanding of some new change to iOS6.

I've searched the documentation for a text alignment method to call on the UIAppearance proxy, but I was unable to find such a method.
I use the following lines of code to style my UINavigationBar across my entire application:
[[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"NavigationBarBackground"]
                                   forBarMetrics:UIBarMetricsDefault];

[[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"NavigationBarBackground"]
                                   forBarMetrics:UIBarMetricsLandscapePhone];

[[UINavigationBar appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                      [UIColor whiteColor], UITextAttributeTextColor,
                                                      [UIFont fontWithName:@"Corbel-Bold" size:14.0], UITextAttributeFont,
                                                      nil]];

[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil] setTintColor:[UIColor whiteColor]];
[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                      [UIColor ceBlueColor], UITextAttributeTextColor,
                                                      [UIColor whiteColor], UITextAttributeTextShadowColor,
                                                      [NSValue valueWithUIOffset:UIOffsetMake(0, 1)], UITextAttributeTextShadowOffset,
                                                      [UIFont fontWithName:@"Corbel" size:0.0], UITextAttributeFont,
                                                      nil]
                                            forState:UIControlStateNormal];

[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -3) forBarMetrics:UIBarMetricsDefault];

A: If it helps, you can adjust (at least) the vertical position of the title:
[[UINavigationBar appearance] setTitleVerticalPositionAdjustment:4 forBarMetrics:UIBarMetricsDefault];

(This question helped me to find a solution to this problem: UINavigationBar custom title position )

A: Same issue here, but I noticed it doesn't happen when the navigation bar has either a back button or a right bar button (table edit). The alignment on the title is also fixed when navigating to a new view controller and then going back to the first one...
What I think that is happening is that iOS calculates the position of the frame of the title based on the default font, because the font I use is a bit smaller the title misaligns a bit to the left of the center.
My current fix is calling setNeedsLayout in viewWillAppear. Seems to be working.
- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    if (self.navigationItem.hidesBackButton || self.navigationItem.rightBarButtonItem == nil) {
        [self.navigationController.navigationBar setNeedsLayout];
    }
}


text:
Q: Use correct item in an array with time intervals I some text that looks like this:

Vind vid marken
   12-14UTC: Område E3a: N/2-5 knop, byar upp till 13 knop.
   Område E2b: N/2-5 knop, byar upp till 14 knop.
   Område E1a,E1b: NV-N/0-6 knop, byar upp till 15 knop.
   Område E2a: N/1-6 knop, byar upp till 12 knop.
14-16UTC: Område E1b: N/2-6 knop, byar upp till 16 knop.
   Område E3a: N/3-6 knop.
   Område E2b: N/3-5 knop.
   Område E2a: N/1-5 knop, byar upp till 12 knop.
   Område E1a: N/0-6 knop, byar upp till 14 knop.
16-18UTC: Område E1b: N-NO/1-7 knop, byar upp till 15 knop.
   Område E2a,E2b: N/0-4 knop, byar upp till 12 knop.
   Område E1a: N-NO/3-8 knop, byar upp till 15 knop.
   Område E3a: N-NO/1-6 knop, byar upp till 13 knop.
18-20UTC: Område E2b,E3a: N-NO/1-5 knop.
   Område E1b,E2a: N-NO/0-5 knop, byar upp till 11 knop.
   Område E1a: N-NO/1-7 knop.

My goal is to find the value of the correct location and time.
As you can see the text is deceived in times and in areas (for example E3a), and it repeats the same area in the next time interval.
With this regex: preg_match_all("/(\d{2}-\d{2})UTC/", $text, $arr);
I get this array:
array(2
      0 =>  array(4
          0 =>  12-14UTC
          1 =>  14-16UTC
          2 =>  16-18UTC
          3 =>  18-20UTC
      )

      1 =>  array(4
          0 =>  12-14
          1 =>  14-16
          2 =>  16-18
          3 =>  18-20
     )
)

Right now the time is 14:52 UTC.
How do I... lets say echo $arr[1][1], because I know the current time is between 14 and 16?
I need the regex to be either the way it is above, or at least maintain $arr[0] because I need that in the next regex pattern.
I'm stuck here because I can't figure out how to know what time interval it is I need in the next regex.

A: Try
preg_match_all("(\d{2})-(\d{2})UTC", $text, $arr);

That should return:
array(3
      0 =>  array(4
        0   =>  12-14UTC
        1   =>  14-16UTC
        2   =>  16-18UTC
        3   =>  18-20UTC
    )
  1 =>  array(4
        0   =>  12
        1   =>  14
        2   =>  16
        3   =>  18
    )
  2 =>  array(4
        0   =>  14
        1   =>  16
        2   =>  18
        3   =>  20
    )
)

From there you can use the values of array[1] and array[2] to compare against your current hour (using date("G")) either by iteration or a callback.
Since you're going to be pulling the time values from the regex, I would also recommend you sanitize and error check your inputs as best as possible as well using perhaps intval().


text:
Q: CALayer gets redrawn frequently despite shouldRasterize --> why? I have some fairly complex layers in a part of my app and I want them to rasterize as their content changes close to never. The frame of the view these layers are in can be changed by dragging a "spacerbar" around with your finger.
I made a simple test-app to visualise my problem and show you some code:
@interface ViewController () {
    UIView* m_MainView;
    UIView* m_TopView;
    UIView* m_BottomView;
    UIView* m_MidView;
    int m_Position;
}
@end

@implementation ViewController
- (void)loadView {
    m_MainView = [[UIView alloc] init];

    m_TopView = [[UIView alloc] init];
    m_TopView.backgroundColor = UIColor.blueColor;
    m_TopView.translatesAutoresizingMaskIntoConstraints = false;
    m_BottomView = [[UIView alloc] init];
    m_BottomView.backgroundColor = UIColor.blueColor;
    m_BottomView.translatesAutoresizingMaskIntoConstraints = false;
    m_MidView = [[UIView alloc] init];
    m_MidView.backgroundColor = UIColor.blackColor;
    m_MidView.translatesAutoresizingMaskIntoConstraints = false;
    [m_MainView addSubview:m_TopView];
    [m_MainView addSubview:m_BottomView];
    [m_MainView addSubview:m_MidView];

    CALayer* targetLayer = [[CALayer alloc] init];
    targetLayer.frame = CGRectMake (100, 200, 500, 50);
    targetLayer.backgroundColor = UIColor.yellowColor.CGColor;
    targetLayer.shouldRasterize = true;
    [m_BottomView.layer addSublayer:targetLayer];

    UIPanGestureRecognizer* recognizer = [[UIPanGestureRecognizer alloc]
        initWithTarget:self action:@selector(handlePan:)];
    [m_MainView addGestureRecognizer:recognizer];

    m_Position = 400;
    super.view = m_MainView;
}
- (void)handlePan:(UIPanGestureRecognizer*)sender {
    float touchY = [sender locationInView:m_MainView].y;
    m_Position = (int)touchY;
    [m_MainView setNeedsLayout];
}
- (void)viewWillLayoutSubviews {
    CGRect bounds = super.view.bounds;
    m_TopView.frame    = CGRectMake (0, 0, bounds.size.width, m_Position - 10);
    m_MidView.frame    = CGRectMake (0, m_Position - 10, bounds.size.width, 20);
    m_BottomView.frame = CGRectMake (0, m_Position + 10, bounds.size.width,
        bounds.size.height - m_Position - 10);
}
@end

.
Now ... By using instruments and activating "Color Hits Green and Misses Red" one can see when a layer is redrawn (is then highlighted in red).
In this example the bar (targetLayer) is green (cached) most of the time, but if I start dragging the spacer (which in fact changes the frame of the bottom-view) the layer turns red some times ... especially if I reverse the direction of the drag or if I drag slowly.
In my app this causes flickering as redrawing these layers is expensive.
Why does this happen??
I never change any property of the layer but it gets redrawn anyways?
I am sure I am missing something :-)
As a workaround I could make a snapshot of the layers and use the image ... that would work I think and if there is no solution I will have to use this approach but I would like to understand what is the problem here.
Anyone?


text:
Q: Creating a rule for a file type How can I create a rule in a makefile for a specific filetype so if I  write something like
result.txt: first.txt second.txt

in a makefile and it will concatenate prerequisites.
.txt:
     cat $? > $@

doesn't work

A: Since this seems to have helped, I am reposting it as an answer, with @eriktous' comment added in.
%.txt:
        cat $? >$@

If you don't want to process just the changed files, use $^ instead of $?.


text:
Q: Export data from multiple SQL tables into multiple worksheets in the same Excel file using SSIS I have successfully used SSIS to generate multiple Excel worksheets in the same Excel file where the columns all contained the same type of data. I was able to achieve this using suggestions from this link: https://social.msdn.microsoft.com/Forums/en-US/6f4a5b98-6373-4f7e-8d03-0876d0b4b611/loading-data-from-multiple-tables-to-multiple-sheets-of-excel-using-ssis?forum=sqlintegrationservices and which is elaborated on in this link: https://social.msdn.microsoft.com/Forums/en-US/2421d9aa-5347-4f24-a78b-da02eb644f5f/export-sql-server-table-into-multiple-sheets-in-excel?forum=sqlintegrationservices
For the new project I am working on, I am trying to export data from multiple SQL tables with different columns and data into multiple sheets in the same Excel workbook. Since the data is different for each table, the Dataflow Task in the example above doesn't appear to be dynamic to allow for the changes to columns and data conversions.
I know that this is possible using the SQL Server Import and Export Wizard but I am looking at over 200 tables. Instead, I have passed the desired table-names to an object variable in SSIS using the SELECT TABLE_NAME FROM information_schema.tables query. Perhaps there is a script that could deal with this. I am new to SSIS and although haven't used VB for several years, I am willing to use it or any other method to achieve the result.
Am I missing something? Is this procedure possible in SSIS?

A: It will be quite hard to do this in simple way. If you have different columns in tables you would like to have multiple different data flow tasks. You can create the packages "dynamicly" using the BIML using for example C# - read more here: https://www.mssqltips.com/sqlservertip/3124/generate-multiple-ssis-packages-using-biml-and-metadata/
Please think about using the import/export wizard from Management Studio (later you can save this into the SSIS package and reuse).