text:
Q: Why TextInputLayout color is not changing if I put it in the AppBarLayout? I have tried to change the TextInputLayout color and it works perfectly, but once I put it in a AppBarLayout it not changes.
<com.google.android.material.appbar.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="220dp"
    >

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/textInputLayout"
        style="@style/Widget.MaterialComponents.TextInputLayout.FilledBox"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        app:boxBackgroundColor="@color/white">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/weightText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/weight"
            android:inputType="number" />

    </com.google.android.material.textfield.TextInputLayout>

A: Apparently it's just a mistake of the Android Studio preview, on the Emulator works perfectly

A: try this
i am using like this
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="220dp"
android:background="@android:color/transparent"    //use any color here
android:fitsSystemWindows="true">

<com.google.android.material.textfield.TextInputLayout
    android:id="@+id/textInputLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="8dp"
    android:textColorHint="@color/green"
    app:hintTextAppearance="@style/text">

add this line in TextInputLayout
app:hintTextAppearance="@style/mytext"
    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/weightText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/black"
        android:inputType="number" />

style xml code:
<style name="text" parent="@android:style/TextAppearance">
<item name="android:textColor">@color/black</item>
<item name="android:textColorHint">@color/red</item>

i hope it helps you.


text:
Q: Make Emacs open pdf/dvi after tex-view in a new buffer In TeX mode I can compile (region / buffer) and then ask Emacs to show what was compiled by running M-x tex-view or C-c C-v, however, when this command runs it looks into tex-dvi-view-command variable for the program to open the recently compiled file.
There are two problems with this approach now:

*

*The text color in the generated DVI is the same as in the Emacs buffer, but the background is not (I get white text on white background...), but it can be the problem of the particular program it is using to display it, not sure yet. Ocular shows black text on white background.

*It opens in dvi viewer. But I would like it to open in Emacs (Emacs can display PDF / DVI on its own, no need for external viewer).
So, my question is: is there a common way to achieve this (esp. #2) or I'll have to add that function myself?

A: I haven't used the specific feature that you've described, but I would imagine that if you ran emacs as a server (q.v., Using Emacs as a Server), you could set tex-dvi-view-command to use emacsclient, in which case the file would be opened in a new buffer in your current emacs session.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Troubleshooting Keyvault access from Azure VM I need to deploy a .Net Core 2.2 app to an Azure VM and I must read some credentials from Azure Keyvault.
I do not have full control on the environment.
I followed this tutorial
Use Azure Key Vault with a Windows virtual machine in .NET
as much as I could, but actually the VM had already been created by sysadmin.

*

*I created the KeyVault in the same resource group of the VM and added 2 secrets.

*I checked that the VM is registered in Active Directory and that it has a system assigned identity.

*I added to my Keyvault an access policy allowing read and list secrets to my VM.

*I tried the sample application in the tutorial.

*

*If I run it from Visual Studio on my pc (using the Azure Cli to authenticate with AZ LOGIN) I can get the secrets

*If I deploy the app in my Azure VM I get an "Identity not found" exception when I try to get the token

*I also tried to get the token using powershell on the VM:

$response = Invoke-WebRequest -Uri 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://vault.azure.net/'-Method GET -Headers @{Metadata="true"}

and I get this error
Invoke-WebRequest : {"error":"invalid_request","error_description":"Identity not found"}
At line:1 char:13
+ $response = Invoke-WebRequest -Uri 'http://169.254.169.254/metadata/i ...
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

If I use the https (the tutorial uses http, but just to be on the safe side I tried also the https variant)
$response = Invoke-WebRequest -Uri 'https://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://vault.azure.net/' -Method GET -Headers @{Metadata="true"}

there is a noticeable delay then I get this:
Invoke-WebRequest : Unable to connect to the remote server
At line:1 char:13
+ $response = Invoke-WebRequest -Uri 'https://169.254.169.254/metadata/ ...
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

Do you see any mistake in my settings or have some troubleshooting suggestion?

A: I can reproduce this error, the error probably indicates that Identity not found. I suggest checking again if you have assigned correctly the system assigned identity in the Azure portal.
Verify if the sysytemAssignedIdentity when you create it using Az CLI command is the same as the object ID in the Virtual machine panel. If you have many tenants, make sure you create the system assigned Identity in the right tenant.

Once I create the identity for the Azure VM, the error disappears. It seems that you do not need to use https, I get the same error Unable to connect to the remote server as you.


text:
Q: Odoo view translation issue I am having a strange issue with odoo translation engine:

The translation works fine for all the fields, but not for the view:
all the translated strings are field labels, but "string" attributes for view.xml tags remain untranslated.
view.xml:
                     <page name="public" string="Form 1">
                        <group>
                            <group>

....
                                    <field name="address_home_id"
                                           context="{'show_address': 1}"
                                           options='{"always_reload": True, "highlight_first_line": True}'
                                           string="Permanent Address"
                                    />

However, I do have those strings in both my.po file:
#. module: hr_mis
#: model:ir.ui.view,arch_db:hr_mis.view_employee_form
msgid "Form 1"
msgstr "ပုံစံ (၁)"

....
#. module: hr_mis
#: model:ir.ui.view,arch_db:hr_mis.view_employee_form
msgid "Permanent Address"
msgstr "အမြဲတမ်းနေရပ်လိပ်စာ"

and in the database:

Any idea what did I do wrong?

A: See the post:
[https://github.com/odoo/odoo/issues/24534][1]
In resume, this Tab/Page string is read from Database, so remove --dev=xml from your runtime config:

The option -- dev xml is:
xml: read template qweb from xml file directly instead of database.
  Once a template has been modified in database, it will be not be read
  from the xml file until the next update/init.
So it means, you are not working with the database for the views. As
  the translations are stored in the database, it actually make sense.
  This option is to be used when you are actually developping on your
  views, to see the result directly.


text:
Q: How to convert ReversedRandomAccessCollection to regular collection I've been trying to find a way to sort my resulting MPMediaQuery so that the results are sorted by date.
I've had a lot of difficulty, and then I found the "reversed()" method, but I cannot get the returned data into a format that I can use with the MPMediaPlayer.
My original query:
var qryPodcasts = MPMediaQuery()
var titleFilter = MPMediaPropertyPredicate()
titleFilter = MPMediaPropertyPredicate(value: "This American Life", forProperty: MPMediaItemPropertyPodcastTitle, comparisonType: .equalTo)
qryPodcasts.addFilterPredicate(titleFilter)

So I tried this:
let myItems = qryPodcasts.items?.reversed()
podCollection = MPMediaItemCollection(items: myItems!) //ERROR HERE
myMP.setQueue(with: podCollection!)

Which gave me this error:
"Cannot convert value of type 'ReversedRandomAccessCollection<[MPMediaItem]>' (aka 'ReversedRandomAccessCollection<Array<MPMediaItem>>') to expected argument type '[MPMediaItem]'"
How can I use the results of 'reversed()' in the MediaPlayer?

A: what about this?
let myItems = qryPodcasts.items?.reversed()
podCollection = MPMediaItemCollection(items: Array(myItems)!)
myMP.setQueue(with: podCollection!)


text:
Q: How to get grails to assign Id to a legacy Java object I have a java annotized domain object that I want to use in grails, this works fine, however all the generated templates use Id as the primary key. I tried to create a XxxConstraints.groovy file in the same package as my domain object, and added
mapping = {
    id type:'assigned', name:<name of java field>, type: string
}

but that does not seem to work.
The error I get when trying to render the gsp is "class XYZ does not contain field id"
By the way I am using grails 2.1.0.
Thanks for the help in advance.

A: If you're talking about scaffolding views, they just have id field hardcoded, like: <g:hiddenField name="id" value="\${${propertyName}?.id}" /> (sample from edit.gsp).
Just modify your GSPs by hand to use your key field.
If it's more than one class and you don't want to generate all the views, you can install the templates into your project sources with grails install-templates and modify those to use your PK field. Maybe Groovy wrappers for Java classes will have ident() method, though not sure.
After looking at the doc, I'm in doubt if mapping{} DSL will work at all. Looks like only constraints section will work, and I believe you only need @Id annotation.


text:
Q: Pandas groupby agg returns something that is not a dataframe. How do I evaluate to a dataframe? I have a dataframe.
df = ...
gb = df.groupby(['A','B','C'],axis=0)

new_df = gb.agg(['sum','max'])

def func(expected_list: List[str]):
    ...
    # fails if a list of strings is not passed

func(list(new_df.columns))

And things fail.
new_df.columns yields: [ ('A','max'), ('A','sum'), ('B','max'), ... ]

How does one convert an aggregate groupby call to a dataframe that returns a columns Series with a call to columns, as expected, rather than this tuple-quasi-tensor?

A: So it turns out that the returned index is a different type known as a MultiIndex, making the returned type of agg not a DataFrame(Index) but a DataFrame(MultiIndex) in pseudo-code, and you can return a Dataframe(Index) which has the expected behavior of a DataFrame output by read_csv for all downstream code with the following procedure:
result.columns = [re.sub(r'_$','',-'_'.join(col)) for col in result.columns]


text:
Q: Which one is correct, "best wishes to you" or "best wishes for you"? Which one is correct, "best wishes to you" or "best wishes for you"?

A: Best wishes to you is correct. I've never heard a native English speaker say "best wishes for you", and there are no examples of "best wishes for you" in the British National Corpus.
"Best wishes for 2011" or "best wishes for the new year" are fine. For more examples, see Google or the British National Corpus.

A:
Best wishes to you

- is the more usual construction of the two.
You can wish for something (using wish as a verb) or you can send a wish to someone (using wish as a noun). Combining these constructions is an error.

A: Simply:

*

*".. best wishes to you..."

*"best wishes for your..."

In the first instance, towards is the connotation that to is meant to take. (It so happens also to be an annotated meaning.)
In the second, for has no connoted sense of directionality but, instead, connotes application or bestowal--hence the change to possessive of "your..."
In one instance "wishes" extend towards the second person; in the second to something possessed or conferred by the second person.
Word meaning, not grammar, is the more fitting tag. Possibly syntax as well.

A: They have slightly different meanings.

Best wishes to you

means I am sending you my best wishes, while

Best wishes for you

means I have best wishes in my heart for you.
The first form is the standard in letters and cards, for example.


text:
Q: Permuting a list of chars takes all my memory (Python) I am building a dictionary of all the alpha and numbers. The problem with this code is "within matter of second consumes 100% of my memory". Do you think my implementation is bad?
Any Help is appreciated.
from timeit import Timer
from itertools import permutations
dictionary = []
small_alpha = map(chr, range(97,123))

lookup.append(small_alpha)

def test():
    for i in permutations(lookup, 10):
        dictionary.append(''.join(i))

if __name__ == '__main__':
    test()

(Edited)
I am a well educated. No intent of hacking. This is realistically not possible even if I have 100 machines. No one can compute such a big number. Just was trying out if it is possible to some extent

A: You need about 90077467 GB of memory to store the result data.
2 GB of memory costs $13 (http://www.newegg.com/Product/Product.aspx?Item=N82E16820146214), so you can fix this easily for the low, low price of $585,503,535.50.

A: You're doing things pretty much right, using itertools to provide a generator rather than actually producing a list -- right up until you try to create a list. That list simply is going to use up all your memory because it is in fact huge. You should probably write it to a file rather than trying to make a list in memory, but you will need a lot of disk space.

A: If you're going to use itertools, then use it all the way!
This is a perfect situation for a lazy generator--no need to actually store either the permutations or the data.
import itertools

small_alpha = itertools.imap(chr, range(97, 123))
numbers = itertools.imap(chr, range(48, 58))
lookup = itertools.chain(small_alpha, numbers)
d = (''.join(i) for i in itertools.permutations(lookup, 10))

if __name__ == '__main__':
    perms = list(itertools.islice(d,10))
    print(perms)

A: There are 36!/(36-10)! = 922,393,263,052,800 permutations (~1 quadrillion) of 10 alphanumeric characters.  Of course this will take all your memory.
Assuming each string takes 32 bytes to store (8 bytes for the pointer, 8 bytes for the length, 16 bytes for the content*, on a 64-bit machine), this requires 26.2 PiB of memory.
There is no way to store all permutations in a normal machine. Please state what you actually want to do.
(*: Actually it takes much more than that, since there are also type information, and in Python 3.x a character costs 2 bytes for UTF-16, and the list itself also takes memory.)

Even with just the alphabets the number of permutations is still 19,275,223,968,000 (~20 trillion), and still takes 561 TiB of memory for 32 bytes per string.

A: you should utilize the cloud to solve this problem. using gnu parallel would provide you with additional resources to help you build your dictionary. http://unethicalblogger.com/posts/2010/11/gnuparallel_changed_my_life

A: Firstly having variable called dictionary that is really a list is very confusing
Assuming you have enough memory, it would be much faster to use
dictionary = list(permutations(lookup, 10))

However since you don't have enough memory, this will just use up your memory even faster


text:
Q: Python tkinter treeview get / return parent name of selected item I am trying to return the parent of a tkinter treeview selection upon a selection event, so if the selection changes to "child" I would like it to print "parent", working example below, currently it prints the selection, not the parent of the selection:
try:
    import tkinter as tk
    import tkinter.ttk as ttk
except ImportError:
    import Tkinter as tk
    import ttk

class App:
    def __init__(self):
        self.root = tk.Tk()
        self.tree = ttk.Treeview(selectmode='browse')
        self.tree.pack(side="top", fill="both")
        self.tree.bind('<<TreeviewSelect>>', self.tree_select_event)
        self.parent_iid = self.tree.insert("", "end", text="Parent")
        self.child_iid = self.tree.insert(self.parent_iid, "end", text="Child")

        self.root.mainloop()

    def tree_select_event(self, event):
        print (self.tree.item(self.tree.selection()[0])['text'])

if __name__ == "__main__":
    app = App()

Currently prints upon selection of Child:
"Child"

Desired output upon selection of child:
"Parent"

A: Try this:
def tree_select_event(self, event):
    item_iid = self.tree.selection()[0]
    parent_iid = self.tree.parent(item_iid)

    if parent_iid:
        print(self.tree.item(parent_iid)['text'])
    else:
        print(self.tree.item(item_iid)['text'])

..and it's well documented here.


text:
Q: Creating a service (SERVICE_ACCEPT_SESSIONCHANGE) I am trying to create a service following the example documented in the link below:
http://msdn.microsoft.com/en-us/library/bb540475(v=VS.85).aspx
What I am interested in is to be able to catch user "lock" and "unlock" workstation events.
Using the code on from the example provided, I modified the following:
Line 15:
Original:
VOID WINAPI SvcCtrlHandler( DWORD );
Modified:
DWORD WINAPI SvcCtrlHandler( DWORD, DWORD, LPVOID, LPVOID );
Line 141:
Original:
gSvcStatusHandle = RegisterServiceCtrlHandler( SVCNAME, SvcCtrlHandler);
Modified:
gSvcStatusHandle = RegisterServiceCtrlHandlerEx( SVCNAME, SvcCtrlHandler, NULL);
Line 244:
Original:
gSvcStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
Modified:
gSvcStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP|SERVICE_ACCEPT_SESSIONCHANGE;
Line 266:
Original:
VOID WINAPI SvcCtrlHandler( DWORD dwCtrl )
{
   // Handle the requested control code.

   switch(dwCtrl)
   {
      case SERVICE_CONTROL_STOP:
         ReportSvcStatus(SERVICE_STOP_PENDING, NO_ERROR, 0);

         // Signal the service to stop.

         SetEvent(ghSvcStopEvent);
         ReportSvcStatus(gSvcStatus.dwCurrentState, NO_ERROR, 0);

         return;

      case SERVICE_CONTROL_INTERROGATE:
         break;

      default:
         break;
   }
}

Modified:
DWORD WINAPI SvcCtrlHandler( DWORD dwControl, DWORD dwEventType, LPVOID lpEventData, LPVOID lpContext )
{
   DWORD dwErrorCode = NO_ERROR;

   switch(dwControl)
   {
      case SERVICE_CONTROL_STOP:
         ReportSvcStatus(SERVICE_STOP_PENDING, NO_ERROR, 0);

         // Signal the service to stop.

         SetEvent(ghSvcStopEvent);
         ReportSvcStatus(gSvcStatus.dwCurrentState, NO_ERROR, 0);
   break;

      case SERVICE_CONTROL_INTERROGATE:
         break;

      case SERVICE_CONTROL_SESSIONCHANGE:
 ReportSvcStatus(gSvcStatus.dwCurrentState, NO_ERROR, 0);
 break;

      default:
 break;
   }

   return dwErrorCode;
}

With the changes above, my service compiled and install fine.
I try starting my service on the windows 7 machine, it would start fine (but I will not be able to stop, pause or do anything to the service as all option will be disabled).
I also tried my service on my Windows 2000 machine, it does not even start(it will be stuck on the "starting" status)
My main objective is getting the service to run properly on the Windows 7 environment, getting it backward compatible in Windows 2000  will be a bonus.
Can anyone please advise?
Thank you in advance,
Ron

A: I have a test service here that accepts session change events and runs just fine on Windows 7. It supports all notifications possible and correctly allows stop and pause and deals with the session change events.
Not that helpful, I know, but at least you know that you should be able to get it to work as documented... My service code is considerably more complex than the basic example you have there so I can't see at a glance what mistake you're making.
Since you're not getting seeing stop available as an option I'd check that you are setting the controls accepted correctly, or change just that back to just stop and make sure that you are seeing stop as an option once you start the service...

A: MSDN says : SERVICE_ACCEPT_SESSIONCHANGE: "Windows 2000:  This value is not supported."
Not sure if that is the actual reason why the service gets stuck in the starting phase.
Edit: Alternative ways to get session events on windows 2000:

*

*Winlogon Notification Packages

*SENS: ISensLogon


text:
Q: Null pointer exception while using getRow() in jxl I have written a java code using JXL api to read data from excel & return the table in form of 2D array. I'm getting a null pointer exception while using getRow()
My Code is as follows,
public String[][] getExcelData(String xlPath, String shtName)throws Exception
{
    int ci,cj;

    Workbook workbk = Workbook.getWorkbook(new File(xlPath));
    Sheet sht = workbk.getSheet(0);

    Cell Start = sht.findCell("Start");
    System.out.println("Start cell found");
    Cell End = sht.findCell("End");

    int startRow = Start.getRow();
    System.out.println("start row number"+startRow);
    int endRow = End.getRow();

    int startColumn = Start.getColumn();
    int endColumn = End.getColumn();

    /*rowCount = sht.getRows();
    colCount = sht.getColumns();*/
    int tableStartRow = startRow+1;
    int tableStartColumn = startColumn+1;

    int tableEndRow = endRow-1;
    int tableEndColumn = endColumn-1;

    //tabArray = new String[rowCount-1][colCount];
    tabArray = new String[tableEndRow-1][tableEndColumn-1];
    System.out.println("#row: " + rowCount);
    System.out.println("#col: " + colCount);

    ci=0;

    for (int i=1;i<=tableEndRow-1;i++, ci++)
    {

        cj=0;

        for (int j=1;j<=tableEndColumn-1;j++, cj++)
        {
            System.out.println("Ci ->"+ci+" & Cj ->"+cj);
            System.out.println("i ->"+i+" & j ->"+j);
            System.out.println("contents"+sht.getCell(j, i).getContents());
            tabArray[ci][cj]= sht.getCell(j, i).getContents();

            System.out.println("Value at"+ci+""+cj+"is ->"+tabArray[ci][cj]+"\n");

        }
   }
   return (tabArray);
}

Start cell found
SKIPPED: Test
java.lang.RuntimeException: java.lang.NullPointerException
at org.testng.internal.MethodInvocationHelper.invokeDataProvider        MethodInvocationHelper.java:161)
at org.testng.internal.Parameters.handleParameters(Parameters.java:429)
at org.testng.internal.Invoker.handleParameters(Invoker.java:1383)
at org.testng.internal.Invoker.createParameters(Invoker.java:1075)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1180)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
at org.testng.TestRunner.privateRun(TestRunner.java:767)
at org.testng.TestRunner.run(TestRunner.java:617)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
at org.testng.SuiteRunner.run(SuiteRunner.java:240)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
at org.testng.TestNG.run(TestNG.java:1057)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)
Caused by: java.lang.NullPointerException
at DataProvider.DataSource.getExcelData(DataSource.java:39)
at DataProvider.DataSource.getLoginData(DataSource.java:84)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
at org.testng.internal.MethodInvocationHelper.invokeDataProvider    (MethodInvocationHelper.java:135)
... 20 more

The excel to be read is -

Any help will be appreciated !!

A: Your problem is  spaces in your mastersheet in cell where  "Start" is written. Remove extra space after/before  Start.
It will work.


text:
Q: Derivative of sin(y) = x $$\frac{dy}{dx} = \frac{1}{\sqrt{1-x^2}}$$
The lecturer made the comment "the domain of x is between -1 and 1". if the domain of x is 1, the equation turns into
$$\frac{1}{\sqrt{1-1^2}}$$ and x becomes 0
$$\frac{1}{0}$$
Why is 1 a domain of x since it will cause the equation to divide by zero which is indeterminate

A: The step is made for the proof that
$$(\arcsin x)'=\frac{1}{\sqrt{1-x^2}}$$
which is indeed not defined for $x=\pm 1$, that is $x\in(-1,1)$, since the tangent at that point is vertical.


text:
Q: Export chart to pdf in high quality. Blurry zoom How can i export some charts make with chart.js library into PDF without lose quality. I want that i zoom in pdf the image doesn't show blurry.
PDF image

I'm trying build canvas in position -2000 with different size. But the problem persist...


text:
Q: django - split up urls.py into multiple I know, this is actually basics of django BUT
I tried to split my huge urls.py into 3 pieces. All 3 urls_xxx.py live under one folder: mysite.
then in main urls.py i did:
#urls.py
urlpatterns += patterns('',

    url(r'^', include('urls_search')),
    url(r'^', include('urls_ajax')),
    url(r'^', include('urls_sitemaps')),

)

but it is saying:
ImportError at /
No module named urls_search

this is urls_search.py:
urlpatterns = patterns('myapp.views',
    url(r'^advancedsearch/$', 'advsearch', name="advsearch"),
    url(r'^advancedsearch/tc/$', 'advtcsearch', name="advtcsearch"),
)

my URLCONF:
ROOT_URLCONF = 'mysite.urls'

what am I doing wrong? I am using Django 1.4

A: remove .py like this:
url(r'^', include('mysite.urls_search')),

A: You can do like this in main 'urls.py':
from mysites.url_1 import urlpatterns as url1
from mysites.url_2 import urlpatterns as url2
from mysites.url_3 import urlpatterns as url3

urlpatterns = url1
urlpatterns += url2
urlpatterns += url3

A: In main url.py
from mysites import url1
from mysites import url2
from mysites import url3

urlpatterns = url1.urlpatterns
urlpatterns += url2.urlpatterns
urlpatterns += url3.urlpatterns

and so on


text:
Q: Get or convert Week of year to ISO week While trying to get the number of weeks in a year I tried this:
maxWeek = calendar.GetWeekOfYear(New Date(t_year, 12, 31),
          CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday)

Which didn't work well for my purpouse, but I noticed something weird. For 2014-12-31 it returned 53 and for 2015-01-01 it returned 1. For 2015-01-05 it returned 2. That means that the weeks 53 and 1 are smaller then 7 days!
I need the result to be ISO Week compliant. I couldn't find online any examples of calendars following this same logic. Them all show the week 1 as from 2014-12-29 to 2015-01-04.

A: Your original post does not mention you are looking for ISO week, which may have made what you want unclear.
The NET GetWeekOfYear using FirstFourDayWeek and DayOfWeek.Monday is almost like an ISO Week. The difference is that an ISO Week is always seven days.  Keep in mind that an ISO Date is not just a different format, but a different calendar complete with its own terms (like leap week).  Your default NET calandar on the other hand is Gregorian.
It is not hard to tweak a NET WOY to an ISO Week:
Public Shared Function GetISOWeekOfYear(dt As DateTime) As Integer
    Dim cal As Calendar = CultureInfo.InvariantCulture.Calendar
    Dim d As DayOfWeek = cal.GetDayOfWeek(dt)

    If (d >= DayOfWeek.Monday) AndAlso (d <= DayOfWeek.Wednesday) Then
        dt = dt.AddDays(3)
    End If

    Return cal.GetWeekOfYear(dt, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday)

End Function

Simple tester for 12/31/xxxx:
For n As Integer = 1990 To 2016
    Console.WriteLine("{0}: week:{1}", n.ToString,
                      GetISOWeekOfYear(New DateTime(n, 12, 31)).ToString)
Next

Output of just the last few:

2005: week:52
  2006: week:52
  2007: week:1
  2008: week:1
  2009: week:53
  2010: week:52
  2011: week:52
  2012: week:1
  2013: week:1
  2014: week:1
  2015: week:53
  2016: week:52

A: Try this:
Dim maxWeek As Integer = Globalization.ISOWeek.GetWeekOfYear(New Date(t_year, 12, 31))

Applies to .NET versions: .NET 5, .NET 6, .NET Core 3.0, .NET Core 3.1 and .NET Standard 2.1
Get Details here:
https://learn.microsoft.com/en-us/dotnet/api/system.globalization.isoweek.getweekofyear?view=net-6.0


text:
Q: xaml shapes - relative to canvas size I have the need to draw shapes in XAML that are always relative to the container window/canvas size.  For example, I need a window to show a 3x3 grid on it, where the grid always splits the window into 3 equal parts.  Can I create lines that are bound to 1/3 the width of the grid?
thank you

A: You can set ColumnDefinitions in XAML, for the grid that you want ... all you need to do is set the Column's width to a percentage and you'll get the desired affect.
You can then set border's to create the lines you're looking for.
Does that solve your problem, or am I missing something


text:
Q: Dynamically Changing Boostrap title onclick Could you please help me with a way to dynamically change the modal tile?
I need users to see different tile for each button they click, I have created a prototype in html and please let me know whether there is a a better/secure way to achieve this:

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

My First Bootstrap Page

This is some text.

            <button type="button" class="close" data-dismiss="modal">X</button>

Title 1

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has

            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

     Title 1
     Title 2
     Title 3
     Title 4

Here is the fiddle: https://jsfiddle.net/africanheart/L17c7y91/

A: To get Dynamic Tiles, I think this is the perfect Solution.
I Added One Class and Removed one Class for your code
And I added Some of Tiles Classes in array in my Javascript.
Just Look At the Code Snippet or JSFiddle

var cars = ["glyphicon-film","glyphicon-th-large", "glyphicon-th", "glyphicon-th-list"];
var i=0;
$(".tile").addClass(cars[0])
$(".mybtn").click(function(){
$(".tile").removeClass(cars[i])
i++;
if(i<4){
$(".tile").addClass(cars[i])
}
else{
i=0;
$(".tile").addClass(cars[i])
}
});
<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

My First Bootstrap Page

This is some text.

        <button type="button" class="close" data-dismiss="modal">X</button>

Title 1

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

   Title 1
   Title 2
   Title 3
   Title 4

</htmclassl>

`

A: Show your modal using a javascript method. And change title before showing modal. Here is the example
Here I used showModal() method to show the modal.
function showModal(title){
   $('.modal-title').html(title); // changing the title of modal
   $('#modal').modal('show');     // showing modal
}

And calling the method from href="javascript:showModal('Title 1');" in anchor tag

function showModal(title){
$('.modal-title').html(title);
$('#modal').modal('show');
}
<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

My First Bootstrap Page

This is some text.

            <button type="button" class="close" data-dismiss="modal">X</button>

Title 1

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has

            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

     Title 1
     Title 2
     Title 3
     Title 4

A: This is the right approach to your problem. It is in the official documentation and is dynamic.

$(document).ready(function() {

 $('#modal').on('show.bs.modal', function(e) {
  var btn = $(e.relatedTarget);
    var title = btn.data('title');
    $(this).find('.modal-title').text(title);
  });

});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

My First Bootstrap Page

This is some text.

        <button type="button" class="close" data-dismiss="modal">X</button>

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

   Title 1
   Title 2
   Title 3
   Title 4

It uses the "data-*" attribute pattern and can retrieve more information from attribute of the caller button

A: A small JQuery code to help you achieve the change in modal-title.

$(".btn-danger").click(function(e) {
  $(".modal-title").text($(this).text());
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

My First Bootstrap Page

This is some text.

          <button type="button" class="close" data-dismiss="modal">X</button>

Title 1

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
            It has

          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

   Title 1
   Title 2
   Title 3
   Title 4

A: solved your issue please have a look on this put this js below the code


text:
Q: Google recaptcha is not accessibility compliant The google recaptcha creates a textarea that has no accessibility attributes, like aria-label.   This is causing the recaptcha to fail our accessibility scan via Siteimprove.
I've tried adding the aria-label attribute to the textarea using javascript,  but i'm adding it to the element after it has been added to the DOM,  so i'm guessing that is why the accessibility is failing.
Here is text from Siteimproves google extension:

Failing requirement 4.1.2 textarea is empty.  This is because no label is associated  with the text area or an aria-label attribute isn't added to the textarea.

A: I ended up setting the following attributes in javascript and this fixed the issue.  This is a work-around in my book, as google should address this.
Anyway, here is what I set;
  var textarea = document.getElementById("g-recaptcha-response");
  textarea.setAttribute("aria-hidden", "true");
  textarea.setAttribute("aria-label", "do not use");
  textarea.setAttribute("aria-readonly", "true");

A: Since the Google reCAPTCHA textarea in question has the inline style display: none, it shouldn't need the aria-hidden=true or any other additional attribute, since it is already removed from the accessibility tree via the API and won't be focusable by users with screen readers.

<textarea
  id="g-recaptcha-response"
  name="g-recaptcha-response"
  class="g-recaptcha-response"
  style="width: 250px;
         height: 40px;
         border: 1px solid rgb(193, 193, 193);
         margin: 10px 25px;
         padding: 0px;
         resize: none;
         display: none;">
</textarea>

According to the documentation on the Fourth Rule of Aria, this is unnecessary (see the third green note section).
I've seen this problem occurring online from multiple automated accessibility tools (the WAVE tool and HTML CodeSniffer), but the problem is with the tools failing to test whether the textarea has the inline style display: none, and not the reCAPTCHA textarea element.
Hope that helps!

A: I had a quick fix for this one,
<script type="text/javascript">
    function onloadCallback() {
        $('#g-recaptcha-response').attr('aria-hidden', true);
    }
</script>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback>

A: The full solution that works is combing the two above answers
so:
<script>
        function onloadCallback() {
            $('#g-recaptcha-response').attr('aria-hidden', true);
            $('#g-recaptcha-response').attr('aria-label', 'do not use');
            $('#g-recaptcha-response').attr('aria-readonly', true);
        }
    </script>

<script src='https://www.google.com/recaptcha/api.js?onload=onloadCallback'></script>

A:

$(window).on('load', function () {
      onloadCallback();
 });
function onloadCallback() {
            $('#g-recaptcha-response').attr('title', "g-recaptcha-response");
        }

A: This passed the WAVE accessibility test for me:
Use a regular form label with a visually-hidden style for screen-readers only and a for attribute matching the ID of your Google recaptcha form field.
CSS
.sr-only {
  position:absolute;
  left:-10000px;
  top:auto;
  width:1px;
  height:1px;
  overflow:hidden;
}

HTML
<label class="sr-only" for="g-recaptcha-response">Google Recaptcha</label>

A: Using rails, and pulling in the recaptcha js through gems, I was unable to use the onloadCallBack "quick fix" option above because those assets are loaded earlier, and reloading them entirely seemed wasteful. I opted for a similar setAttribute, but needed to wait for a few seconds (even when using document.ready) to make sure the textarea was available on which to update the attribute. This seems to do what the question asker needs from a rails perspective, as was in my case, and screen readers will behave as desired/expected:
<script type="text/javascript">
    $(document).ready(function(){
        setTimeout(() => {
          var textarea = document.getElementById("g-recaptcha-response");
          textarea.setAttribute("aria-hidden", "true");
          textarea.setAttribute("aria-label", "do not use");
          textarea.setAttribute("aria-readonly", "true");
      }, 2000);
    });
</script>

If you're looking for a clean report for a client that reflects actual screen reader results, the wave browser extension for chrome and firefox both report clean (no error), while the wave web-based app still has an error on that field. htmlcodesniffer clears that textarea without error, but actually reports an error on the recaptcha iframe (which is above the textarea) having an empty title, which can't be changed because of the cross-site scripting request to update the iframe (that has different domain origin). Have a lovely day.


text:
Q: Continuity of the embeddings $j_i:M_i \to \bigoplus_k M_k$ I have two questions on the direct sum of two Banach spaces. Before the questions, I would like to point out the below universal property of the direct sum I noticed from Wikipedia. My first question is, how do we prove the embeddings $j_i$ must be continuous? My second question is, how do we prove the universal property from the constructive definition (on Wikipedia too)?
Remark: the universal property below is expressed in the general language of modules, but it translates directly to Banach spaces.
Universal property:
In the language of category theory, the direct sum is a coproduct and hence a colimit in the category of left $R$-modules, which means that it is characterized by the following universal property. For every $i$ in $I$, consider the natural embedding
$$
j_i: M_i \rightarrow \bigoplus_{i \in I} M_i
$$
which sends the elements of $M_i$ to those functions which are zero for all arguments but $i$. Now let $M$ be an arbitrary $R$-module and $f_i: M_i \rightarrow M$ be arbitrary $R$-linear maps for every $i$, then there exists precisely one $R$ linear map
$$
f: \bigoplus_{i \in I} M_i \rightarrow M
$$
such that $f \circ j_i=f_i$ for all $i$.

A: If I understand correctly, your questions are the following:

*

*If $ {\bigl(\bigoplus_{i\in\mathsf I} E_i\xrightarrow{\iota^k} E_k\bigr)}_{k\in \mathsf I} $ is a coproduct in the category $ \mathsf{Ban} $ of Banach spaces and bounded linear maps, how do we prove that all the injections $ \iota^k\colon E_i\to \bigoplus_{i\in I}E_i $ are continuous?

*If $ E_1,\dots, E_n $ are Banach spaces, how do we prove that $ \bigoplus_{j = 1}^n E_j = \bigl(\prod_{j = 1}^n E_j,\lVert{-}\lVert\bigl) $, where
$$
\lVert{(x_1,\dots,x_n)}\rVert = \max_{j = 1}^n {\lVert x_j\rVert}_{E_j}$$
is a coproduct in $ \mathsf{Ban} $?
The answer to 1. is that the $ \iota^k $ are continuous by definition, since you are taking the coproduct in $ \mathsf{Ban} $, and a bounded linear map is always continuous.
To answer 2., let $ E $ be a Banach space and let $ f_j\colon E_j\to E $ be bounded linear maps. Now let $ f\colon \bigoplus_{j = 1}^n E_j\to E $ be the map that results from the universal property of $ \bigoplus_{j = 1}^n E_j $ as a coproduct of vector spaces. Can you show that $ f $ is bounded?


text:
Q: Properties of other class instances being modified I have a class PageMaster, for which I instantiate several instances, including one called EmptyPage, which I never write to (only read from).
I have other class instances such as IndexPage, PrivacyPage et al. which have different properties set.
In my program (code below), when I modify any one of these class instances, every single other instance is also being modified in the exact same way.
Log3("Resetting special pages")

Log3("Setting pages equal to EmptyPage")
IndexPage = EmptyPage
PrivacyPage = EmptyPage
ContactPage = EmptyPage
AboutPage = EmptyPage
SiteIndexPage = EmptyPage
LogSpecialPages()

Log3("Setting flag IsIndexPage")
IndexPage.IsIndexPage = True
LogSpecialPages()

Log3("Setting flag isPrivacyPage")
PrivacyPage.IsPrivacyPage = True
LogSpecialPages()

Log3("Setting flag isContactPage")
ContactPage.IsContactPage = True
LogSpecialPages()

Log3("Setting flag isAboutPage")
AboutPage.IsAboutPage = True
LogSpecialPages()

Log3("Setting flag isSiteIndexPage")
SiteIndexPage.IsSiteIndexPage = True
LogSpecialPages()

Log3("Reset finished")

In this actual code from my program, when I perform the instruction IndexPage.IsIndexPage = True every single instance of Page - PrivacyPage, ContactPage, et al. are all modified - not just IndexPage.  The same thing happens with the others.  When I modify one instance, all other instances have string and/or boolean variable values changed.
(To do the logging, I serialize the class instances with JSONConvert and write it to an output.)
I can't understand why every single instance is being modified.  This is how they are instantiated, inside my form's class:
Dim IndexPage As New PageMaster
Dim PrivacyPage As New PageMaster
Dim ContactPage As New PageMaster
Dim AboutPage As New PageMaster
Dim SiteIndexPage As New PageMaster
Dim EmptyPage As New PageMaster

The only possible explanation I can come up with is that when I say, IndexPage = EmptyPage, and assign all the others equal to EmptyPage, that they somehow lose their individual identities.  That doesn't make sense to me, though, because I've never had anything like this happen.
The class is very simple, with a few string and boolean properties.
I then tried this simple modification.  Instead of IndexPage = EmptyPage I used  IndexPage = New PageMaster and it worked correctly.
This seems to confirm that, somehow, setting them all equal to EmptyPage is confusing their identifies.
Why do their identities become confused, causing any changes to one instance to be made to all?
It's like somehow when I say IndexPage = EmptyPage that it's just creating a symbolic reference from one to the other, rather than the behavior I expected, which was to set all the properties of one equal to the properties of the other.
UPDATE
After Jimi's comment confirming what I suspected to be the case, I decided to do a little test.  I just put a button on my test app and added this code in its click event:
' PART 1:  STRING
Dim name1 As String = "Bob"
Dim name2 As String = "Larry"
name2 = name1
name2 = "Fred"
MsgBox(name1)

'PART 2: CUSTOM CLASS
Dim Bob As New Person
Bob.Name = "Bob"
Dim Larry As New Person
Larry.Name = "Larry"
Larry = Bob
Larry.Name = "Hubert"
MsgBox(Bob.Name)

In the first example, we get the response of "Bob", which is what I would have expected.
In the second msgbox, we don't get "Bob".  Instead, we get "Hubert", because class instance Bob now points to Larry, and Larry's name was changed to "Hubert".
This prompts me to ask these questions:

*

*Why is the behavior is so completely different using String versus a class of our own creation?

*Can a different behavior be forced with custom classes?  Or is there another simple way to "Copy" one instance of a class over another?

*Does this presumably carry over into C#, which I also use?

A: Setting IndexPage = EmptyPage doesn't make a clone/copy of the EmptyPage object, it creates a reference to EmptyPage. (You could actually clone the EmptyPage object if you wish but I don't think that's what you're after here.)
Using IndexPage = New PageMaster instantiates a new PageMaster object called IndexPage, independent (except for any static properties, etc) from any other object instantiated from PageMaster, eg PrivacyPage.
This is really what Object Oriented Programming is about (among many other things).
If IndexPage, PrivacyPage, etc have exactly the same structure, instantiating them directly from PageMaster is fine. But if they have slightly - or even quite - different structures, you could create individual classes based on ("inheriting") PageMaster, or possiblly create an interface, eg IPageMaster. (You could even set the PageMaster class to be MustInherit so that it cannot be directly instantiated as an object.)
None of this is specific to VB.NET; the same basic principles apply to any OOP language including C#.NET.
As an aside, be careful if you define any static properties (Shared in VB) within your base class; static variables are common to all objects of the class, so their values will change even in derived class objects.
I've glossed over quite a bit here, but hopefully you get the basic idea.

A: With regards to your update:

Why is the behavior is so completely different using String versus a
class of our own creation?

It's not. It's exactly the same. The only difference between String and other types is that String supports literals. In this code:
Dim name1 As String = "Bob"
Dim name2 As String = "Larry"
name2 = name1
name2 = "Fred"
MsgBox(name1)

The fourth line is not changing something about the String object that name2 refers to. It is assigning a different String object to name2. Why would you expect that to affect the name1 variable or the String object that it refers to? As for this code:
Dim Bob As New Person
Bob.Name = "Bob"
Dim Larry As New Person
Larry.Name = "Larry"
Larry = Bob
Larry.Name = "Hubert"
MsgBox(Bob.Name)

you haven't really thought through what it actually does. After the first four lines, Bob and Larry refer to two different Person objects. The fifth line discards the object that Larry refers to and assigns the same Person object to Larry as Bob already refers to. Both variables now refer to the same Person object. If you make a change to the object via one variable, of course you're going to see that change via the other variable. How could you not?
Consider this real-life scenario. Let's say that I am best friends with a person named Bob and you are best friends with a person named Larry. You have an argument with Larry and are no longer friends and you become best friends with Bob. You and I are now both best friends with the same person. If your best friend then changed his name to Hubert, what would my best friend's name be? It would be Hubert, right? That's blindingly obvious, so why is it a problem that that is how it works in OOP? Programming objects are designed to mimic real-world objects, which is why things work the same in OOP as in the real world.
One thing that can also cause some confusion is the fact that String objects are immutable, i.e. once created, they cannot be changed. This means that, while you are able to change some aspect of a Person object in your second code snippet, there's no way to make a change to a String object in the first. If you have a variable of type String then you can assign a different String object to it - either a literal or the result of an expression - but you cannot modify the object it refers to.

Can a different behavior be forced with custom classes? Or is there
another simple way to "Copy" one instance of a class over another?

There is only one behaviour for reference types. ALL reference types work exactly the same way. If you want to create a copy of a reference-type object, i.e. an instance of a class, then you have to create it. Classes that require this usually implement the ICloneable interface, but you still need to provide the implementation yourself. That said, it is not uncommon for people to think that they need such functionality when they don't.

Does this presumably carry over into C#, which I also use?

Of course. OOP is OOP.


text:
Q: Event date and time not select in datepiker less then server time
*

*User careate feture event using bootstrep datepiker

*User select date and time greter then currant time
4.If user select date Event time is 04-09-14 11:55AM and server time is 04-09-14 11:60AM
after not valid date for create event.
I am Using this code.
    $event_time =htmlentities($_REQUEST['date_piker']) ;
    $server_time    = htmlentities( date('m-d-y h:iA')) ;
    echo 'Event time:-  '. $event_time.'
';
    echo 'Server Time:-'. $server_time;

    if($event_time < $server_time)
    {
        echo 'Date and time is invalid';
    }
    else
    {
       echo 'Date and time is valid';
    }

But It is not working. i need help.

A: why u didnt use timestamps? like this
<?php

$event_time = htmlentities($_REQUEST['date_piker']);
$eventTimeTimestamp = strtotime($event_time);
$serverTimeTimestamp = time();
$server_time = htmlentities(date('m-d-y h:iA', $serverTimeTimestamp));
echo 'Event time:-  ' . $event_time . '
';
echo 'Server Time:-' . $server_time;

if ($eventTimeTimestamp < $serverTimeTimestamp) {
    echo 'Date and time is invalid';
} else {
    echo 'Date and time is valid';
}

A: You should use DateTime::createFromFormat
$event = DateTime::createFromFormat('m-d-y h:iA', '04-09-14 11:55AM');
$server = DateTime::createFromFormat('m-d-y h:iA', '04-09-14 11:00AM');

if($event < $server){
    echo 'Date and time is invalid';
}else{
    echo 'Date and time is valid';
}


text:
Q: Why cell is deselect when I scroll down iOS (collectionview inside tableView)? I have a collectionview with mulitselect inside tableviewcell. When I scroll down - selected cell is deselect.
CollectionViewDelegate and DataSource contain in the cell. TableView just contain this cell. I think that, problem when TableView try to reuse cell.
class CategoryCollectionCell: UITableViewCell {

    @IBOutlet weak var collectionView: UICollectionView!
    static let identefier = "CategoryCollectionCell"

    private var items: [Value] = [] {
        didSet {
            collectionView.reloadData()
        }
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        commonInit()
    }

    private func commonInit() {
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.allowsMultipleSelection = true
    }

    func config(items: [Value]) {
        self.items = items
    }

}

extension CategoryCollectionCell: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        items.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CategoryCell.identefier, for: indexPath) as! CategoryCell
        cell.config(text: items[indexPath.row].name)
        cell.layoutIfNeeded()
        return cell
    }
}

A: In your func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell you have to set the cell as selected if it has been previously.
iOS resets every cell before reusing it. You have to check in your data if every cell before displaying should be selected or not.
You can either set a custom method in a custom UICollectionViewCell class or just set the cell to selected with the builtin
cell.isSelected = true


text:
Q: How to set C++ language standard in C++ Builder Today we worked on a piece of code that requires either C++14 or C++17.  My colleague used C++Builder for the code editing, and also wanted to try to compile the code piece with it.
We could not find the setting where one sets the C++ language standard. What we found by googling was that C++builder has a "classic compiler" that supports only parts of C++11 and a "clang-based compiler" that supports up to C++17. We found a check box for enabling/disabling the "classic compiler" in the project settings, but no project setting for selecting the language standard explicitly (to switch between C++14 and C++17). Is there something like that? Where?
The version that we have is C++Builder 10.2.
We also tried to explicitly set an additional compiler option -std=c++14 for the clang-based compiler but this option was rejected ("unknown value c++14").

A: Hans Passant has posted a comment to my question which links to New in RAD Studio 10.3: C++17, asynchronous C++ code completion, and more, thank you.
From this link I learn:

*

*C++ Builder 10.2 does not include any support for C++14 nor C++17.

*C++ Builder 10.3 supports C++17 only when compiling 32 bit windows binaries. Support for C++14 is only available in the sense that C++17 is "with some small exceptions, a superset" of C++14.  Which means, you cannot select the desired language standard used for compilation.

*C++ Builder 10.4 seems to support C++17 also for 64 bit windows. It is unclear if and how the language standard to use can be selected.

A: The ISO C++, 10.4 Sydney C++Builder and Clang version information is as follows:
http://docwiki.embarcadero.com/RADStudio/Sydney/en/Clang-enhanced_C%2B%2B_Compilers
Compiler    Platform        Clang Version   LLVM Version
BCC32C      32-bit Windows  5.0             5.0
BCC32X      32-bit Windows  5.0             5.0
BCC64       64-bit Windows  5.0             5.0
BCCIOSARM   32-bit iOS      3.3             3.3
BCCIOSARM64 64-bit iOS      3.3             3.5
BCCAARM     Android         3.3             3.3

https://clang.llvm.org/cxx_status.html
Clang 3.3 and later implement all of the ISO C++ 2011 standard.
Clang 3.4 and later implement all of the ISO C++ 2014 standard.
Clang 5 and later implement all the features of the ISO C++ 2017 standard.
David Millington, Product Manager for C++Builder, also keeps the Embarcadero C++Builder information updated on the C++ Reference site at
https://en.cppreference.com/w/cpp/compiler_support
You can look at the different ISO C++ language releases to see what many compilers support in their compiler releases.


text:
Q: Storing data for use during streaming I am attempting to stream an XML file using XSLT3. It has a number of tags that constitute "reusable" data that will need to be used during the processing of the repeating data (where streaming shines).
<Root>
    <ReusableData1>
        <ReferenceData id="1">

        </ReferenceData>
        <ReferenceData id="2">

        </ReferenceData>
    </ReusableData1>
    <RepeatingData>
        <RefId>1</RefId>
    </RepeatingData>
    <RepeatingData>
        <RefId>2</RefId>
    </RepeatingData>
 ...
</Root>

I cannot just copy-of the ReusableData into a variable due to the single downward selection restriction. I imagine accumulators come in to play here, but I can't make sense of them. The examples I see uses maps with primitive types, I need to store at least partial node-sets, as the reference data contains additional elements.

A: With Saxon, there is the extension attribute saxon:capture, see https://www.saxonica.com/html/documentation/extensions/attributes/capture.html, that should help:

If a large document has a short header section containing metadata,
you can capture a copy of the header in an accumulator, and the header
then becomes available throughout the rest of the document processing
using the accumulator-after() function

A: It should be as simple as
<xsl:accumulator name="reusable-data" as="element(ReusableData1)">
  <xsl:accumulator-rule match="ReusableData1" select="." saxon:capture="yes"/>
</xsl:accumulator>

and then later
<xsl:value-of select="accumulator-after('reusable-data')/ReferenceData[@id='1']/a"/>


text:
Q: Block a specific request by it's url in firefox how to prevent firefox from making a specific request
to an url, ex: site.com/ajax/something.php
i have found a lot of addons but they couldn't really do the job they
can block requests to another domain but not an absolute uri,
Is there any way to accomplish this ?

A: The solution with addons is to use AdsBlockPlus->Filter preferences->Add filter, then simply put the url after || eg: ||facebook.com/ajax/mercury/change_read_status.phpwhich will prevent any requests to the url, Programmatically @Noitidart link is a perfect solution i was looking for that too.

A: Here you go man: firefox extension: intercepting url it is requesting and blocking conditionally
That uses observer service. Ideally you want to use nsIContentPolicy which i think is more performant but i dont have a solution with that to share. The Adblock Plus author is on this forum he may be able to give us a solution i can spam. :P


text:
Q: iOS Reachability Not Recognizing When Host is Removed I am building an application and trying to check and see if a device is still available on the network (by connecting to the devices IPAddress). I am using reachability to confirm that it is available.
When I network access for the iOS device (turn on airplane mode for example) everything works properly, but if I remove the device from the network, reachability does not seem to notice the change.
It seems like reachability is caching the results, and not seeing the update.

A: Don't use reachability then!
Use this bit of code instead which works a treat;
NSString *connected = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]];
wait(25000);
if (connected == NULL) {

NSLog(@"Not Connected");
//Code to show if not connected

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"Oops! You aren't connected to the Internet."
delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];

} else {
NSLog(@"Connected Successfully!");
//Any other code for successful connection
}

A: The SCReachability API only checks if the local hardware is configured such that it could reach the specified address; it does not actually attempt to reach it. To determine if the target is alive and kicking, you must attempt to open a connection to it.

A: Check out this answer.  While the pixelbit's answer is viable, burtlo is right to bring up that just waiting 25 seconds isn't a great idea.  Using the NSURLConnection is much cleaner.

A: Apple updated the Reachabilty class file. You can test it with latest Xcode.
here is link:
Apple Reachabilty Sample Code
I tested with Xcode 8.3.1 on iPhone 6 version 10.3.1.
It will notify user for change in network status.


text:
Q: google apps script disappeared I was just rechecking all of my websites as I updated to PHP7 now I realised that my Google-script wasn't working properly. Now that I logged in to the script.google page I noticed they are all gone - no trace. When I open the previously working link it says I'm not allowed to open the script. Putting the Script-ID in the explorer to open the edit page it says there is no such script.
corresponding link: https://script.google.com/macros/s/AKfycbxnewLUtjWIlEITiX5RYRi-ZtJuI87nQ1G8t1rVnuGfUntsZXu9/exec?year=2017


text:
Q: Counting the number of older siblings in an Excel spreadsheet I have a longitudinal spreadsheet of adolescent growth.
ID | CollectionDate | DOB      | MOTHER ID | Sex
1  | 1Aug03         | 3Apr90   | 12        | 1
1  | 4Sept04        | 3Apr90   | 12        | 1
1  | 1Sept05        | 3Apr90   | 12        | 1
2  | 1Aug03         | 21Dec91  | 12        | 0
2  | 4Sept04        | 21Dec91  | 12        | 0
2  | 1Sept05        | 21Dec91  | 12        | 0
3  | 1Aug03         | 30Jan89  | 23        | 0
3  | 4Sept04        | 30Jan89  | 23        | 0

This is a sample of how my data is formatted and some of the variables that I have.  As you can see, since it is longitudinal, each individual has multiple measurements.  In the actual database there are over 10 measurements per individual and over 250 individuals.
What I am wanting to do is input a value signifying the number of older brothers and older sisters each individual has.  That is why I have included the Mother ID (because it represents genetic relatedness) and sex.  These new variable columns would just say how many older siblings of each sex each individual has.  Is there a formula that I could use to do this quickly?
=COUNTIFS($B:$B,"<>"&$B2,$H:$H,$H2,$AI:$AI,$AI2,$J:$J,"<"&$J2)

A: I have a possible solution. It involves adding two columns -- One for "# older siblings" and one for "unique?". So here are all the headings I have currently:

*

*A -- ID

*B -- CollectionDate

*C -- DOB

*D -- MOTHER ID

*E -- Sex

*F -- # older siblings

*G -- unique?

In G2, I added the following formula:
    =IF(A2=A1,0,1)

And dragged down. As long as the data is sorted by ID, this will only display "1" once for each unique person.
In F2, I added the following formula:
    =COUNTIFS(G:G,"=1",D:D,"="&D2,C:C,"<"&C2)

And dragged down. It seemed to work correctly for the sample data you provided.
The stipulations are:

*

*You would need the two columns.

*The data would need to be sorted by ID

I hope this helps.

A: Create a column named Distinct with this formula
=1/COUNTIF([ID],[@ID])

Then you can find all the older 0-sexed siblings like this
=SUMPRODUCT(([DOB]>[@DOB])*([MOTHERID]=[@MOTHERID])*([Sex]=0)*([Distinct]))

Note that I made the data a Table and used table notation. If you're not familiar [COLUMNNAME] refers to the whole column and [@COLUMNNAME] refers to the value in that column on the current row. It's similar to saying $A:$A and A2 if you're dealing with column A.
The first formula gives you a value to count that will always result in 1 for a particular ID. So ID=1 has three lines and Distinct will result in .33333 for each line. When you add up the three lines you get 1. This is similar to a SELECT DISTINCT in Sql parlance.
The SUMPRODUCT formula sums [Distinct] for every row where the DOB is greater than the current DOB, the Mother is the same as the current Mother, and the Sex is zero.

A: You need a formula like this (for example, for row 2):
=COUNTIFS($A:$A,"<>"&$A2,$E:$E,$E2,$D:$D,$D2,$C:$C,"<"&$C2)
Assuming E:E is column for sex, D:D is column for mother ID and C:C is column for DOB.
Write this formula in H2 cell for example and drag it down.


text:
Q: PHP Laravel How to group dates for each month and display them I have a table where I store music releases. Each row has a column named release_date and now I want my an overview for each month which makes it more clear and userfriendly. I was thinking about something like:
JANUARY
  4.1 - bla bla
  10.1 - bla bla
FEBRUARY
  8.2. - bla bla
  17.2. - bla bla

I am using Laravel, so is this possible somehow?
Right now I'm just displaying my data like this:
@if (count($releases) > 0)
   @foreach ($releases as $release)

            {{ \Carbon\Carbon::parse($release->release_date)->format('d. M')}}
            {{$release->artist}} - {{$release->album_title}}

   @endforeach
@endif

and my controller looks like this:
public function index() {
    $releases = Release::orderBy('release_date', 'asc')->get();
    return view('pages.index')->with('releases', $releases);
}

Can someone help me out?

A: Sooo... I though of using DB::raw within the groupBy BUT then remembered we need to specify the column name in order for the query to understand with what it should group the results.
My idea is to specify a select to help us do this. And it can help sorting out another problem as well:

*

*We need to target a column in order to group them;

*It is better to just target the values you need to display instead of the entire table;

For such:
Release::select('album_title', 'release_date', DB::raw("MONTH('release_date') as month"))
->groupBy('month')
->orderBy('release_date', 'ASC')
->get();

Then we already create a extra column to use for grouping base solely on months :)
The problem it might trigger though, is joining all years into the same query. So let's say you have musics from 2016 and 2017. By using above solution you will end up with January songs from 2016 and 2017.
We can group by month, but we can also group them by year (both together), so we can, in reality, generate 2 column based to help us out separating the years as well, from the months:
Release::select('album_title', 'release_date', DB::raw("CONCAT_WS('-',MONTH(release_date),YEAR(release_date)) as combinedDates")
    ->groupBy('combinedDates')
    ->orderBy('release_date', 'ASC')
    ->get();

If you are curios on further check the CONCAT_WS left the link that can help clarify it!
Handling GroupBy functionality
GroupBy and Select are kinda like, not the best friends, sorta.
It will force you to use all select columns in your GroupBy, which is something you do not wish.
Fortunately you can sort this within Laravel configurations. So:
Head to your config/database.php and locate mysql. Then add modes like below:
'modes' => [
                'STRICT_TRANS_TABLES',
                'NO_ZERO_IN_DATE',
                'NO_ZERO_DATE',
                'ERROR_FOR_DIVISION_BY_ZERO',
                'NO_AUTO_CREATE_USER',
                'NO_ENGINE_SUBSTITUTION'
            ],

By doing this we remove the restriction to forcefully use all columns in your select in groupBy and we avoid setting strict to FALSE

A: Controller:
public function index() {
    $releases = Release::orderBy('release_date', 'asc')->get();

    $releases = $realeses->groupBy(function($item){
        return \Carbon\Carbon::parse($release->release_date)->format('F');
    });

    return view('pages.index')->with('releases', $releases);
}

View:
@if (count($releases) > 0)
   @foreach ($releases as $month => $group)

{{ $month }}

        @foreach($group as $release)

                    {{ \Carbon\Carbon::parse($release->release_date)->format('d')}}
                    {{$release->artist}} - {{$release->album_title}}

        @endforeach
   @endforeach
@endif


text:
Q: How to make gitlab run jobs in sequential order? I have a gitlab-ci.yml file like the following:
stages:
  - test
  - job1
  - job2

test:
  stage: test
  rules:
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
  script:
    ...

myjob1:
  stage: job1
  script:
    ...

myjob2:
  stage: job2
  script:
    ...

According to the documentation HERE (or at least how I understood it), the first stage/job is only run when I create a merge request.
This is true, but the next stage (job1) is run in parallel when the first job (test) has been started. As far as I understand the stages which are defined in the order test -> job1 -> job2) always run in sequence.
So what am I doing wrong? Why do job test and job1 run in parallel, and not in sequence as expected?

A: After a lot of trial-end-errors and reading and rereading parts of the really unclear and confusing documentation I might have found a solution.
First, the stage you only want to run on a merge request (or which you do not want to run if you schedule a trigger or start the pipeline manually), you need to change that stage as follows:
test:
  rules:
    - if: $CI_PIPELINE_SOURCE == "web" || $CI_PIPELINE_SOURCE == "schedule"
      when: never
    - when: on_success
  stage: test
  script:
    - 'echo "Running Test"'
    - 'echo $CI_PIPELINE_SOURCE'

Here, you define a rule that checks if the variable CI_PIPELINE_SOURCE is either web or schedule. If the variable is web this means a manual pipeline trigger (i.e. you pressed manually on Run pipeline, which is not explained in the documentation), or if the pipeline is triggered by a schedule (not tested, but I assume that is what schedule means).
So if the pipeline is triggered by a scheduled event or manually, never tells gitlab to not execute that stage. The when: on_success is like an else statement, which tells gitlab to run that stage in any other case.
However, that is not the complete story. Because when you use git to make changes to the code and push it to gitlab via git push, you have two triggers in gitlab! A trigger merge_request_event and a trigger push. That means, the pipeline is started twice!
To avoid the pipeline started twice you need to use the workflow key, which helps to define if the pipeline (=workflow) is run or not. (The term workflow seems to mean pipeline). Here is the code to be put into the gitlab-ci.yml file:
workflow:
  rules:
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
      when: never
    - when: always

This construct suppresses the pipeline to be run when the trigger is merge_request_event. In that case, the additional pipeline is not run. In all other cases (when the trigger is e.g. push), the pipeline is run.
So here is the complete gitlab-ci.yaml code:
workflow:
  rules:
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
      when: never
    - when: always

stages:
  - test
  - stage1
  - stage2

test:
  rules:
    - if: $CI_PIPELINE_SOURCE == "web" || $CI_PIPELINE_SOURCE == "schedule"
      when: never
    - when: on_success
  stage: test
  script:
    - 'echo "Running Test"'

my_stage1:
  stage: stage1
  script:
    - 'echo "Running stage 1"'

my_stage2:
  stage: stage2
  script:
    - 'echo "Running stage 2"'

If you make a git push then one pipeline is run with the stages test, my_stage1 and my_stage2, and when you start the pipeline manually or if it is triggered by a schedule, one pipeline is started with the stages my_stage1 and my_stage2.
As to why this is so complicated and confusing, I have not the slightest idea.


text:
Q: Hibernate use of PostgreSQL sequence does not affect sequence table I've configured Hibernate to use PostgreSQL sequence (via annotations) to generate values for primary key id column as follows:
@Id
@SequenceGenerator(name="pk_sequence",sequenceName="entity_id_seq")
@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="pk_sequence")
@Column(name="id", unique=true, nullable=false)
public int getId() {
    return this.id;
}

What I see with this configuration is that hibernate is already assigning id values > 3000 on persisting, whereas the query on used sequence shows the following:
database=# select last_value from entity_id_seq;
last_value
------------
     69

(1 row)
Questions:
Is there anything wrong or not?
Should hibernate sync with the sequence table?
If not, where does it store the last generated id?
Thank you.

A: I had the same problem. It is related to the id allocating strategies of Hibernate. Whe n you choose GenerationType.SEQUENCE, Hibernate uses HiLo strategy which allocates IDs in blocks of 50 by default. So you can explicitly set allocationSize value like this:
@Id
@SequenceGenerator(name="pk_sequence",sequenceName="entity_id_seq", allocationSize=1)
@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="pk_sequence")
@Column(name="id", unique=true, nullable=false)
public int getId() {
    return this.id;
}

Though, I've also heard opinions that using HiLo strategy with allocationSize=1 is not a good practice. Some people recommend to use GenerationType.AUTO instead when you have to deal with database-managed sequences
Update: I did end up going with allocationSize=1, and things seem to work as I expect now.  My application is such that I don't really need blocks of IDs anyway, so YMMV.

A: DO NOT USE GenerationType.SEQUENCE for Postgres sequences!
It's completely counter-intuitive, but the Hibernate folks completely messed up on this.  You must use GenerationType.AUTO or Hibernate will demolish your sequences if you have to restart/rebuild your DB.  It's almost criminally negligent that they would allow this code to go into a production build, but the Hibernate team is rather famous for their bull-headed stances towards flatly-wrong positions (check out their position on LEFT JOINs, for instance).

A: First, you have to determine which version of Hibernate you are using.  In terms of hibernate-core versions, 3.2 onwards introduced more consistent support for id generators especially in regards to defined in annotations.  See http://in.relation.to/Bloggers/New323HibernateIdentifierGenerators for a discussion.
Next 3.6 introduced a setting ('hibernate.id.new_generator_mappings') which makes the generators discussed in that blog the default way JPA-annotations are handled.  The setting is false by default because Hibernate has to maintain backwards compatibility with older versions.  If you want the new behavior (which is completely recommended) then simply set that setting to true.
How GenerationType is handled depends on which version you are using and whether you have 'hibernate.id.new_generator_mappings' set to true.  I will assume you are using 3.6+ (since anything older is, well, old) and do have 'hibernate.id.new_generator_mappings' set to true (since that is the recommendation for new apps):

*

*GenerationType.AUTO -> treated as GenerationType.SEQUENCE

*GenerationType.SEQUENCE -> maps to the org.hibernate.id.enhanced.SequenceStyleGenerator class discussed in the blog

*GenerationType.TABLE -> maps to the org.hibernate.id.enhanced.TableGenerator class discussed in the blog

A: In Postgres I would do this:
@Id
@SequenceGenerator(name="pk_sequence",sequenceName="\"entity_id_seq\"")
@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="\"pk_sequence\"")
@Column(name="\"id\"", unique=true)
private int id;

Mostly with uppercase names Hibernate need to be passed escaped quotes in order to understand Postgres and find the tables, columns or sequences names.


text:
Q: ¿Como convertir array de hexadecimales a un único valor decimal con Python? Tengo el siguiente array con hexadecimales:
array = ['0xA7', '0xF3', '0x8', '0x0']
No son valores string los que están dentro del array, son el resultados de hacer:
hex(167)= 0xA7
hex(243)= 0xF3
...
Como se pueden concatenar los valores del array de la siguiente forma:
0008F3A7
De forma tal que se pueda calcular el valor decimal de esa concatenación con:
int('0008F3A7',16) = 586663

A: La salida de hex es una cadena con la representación en hexadecimal de un entero precedida de "0x". Por lo tanto como cadenas debes manipularlas:
 >>> "".join(byte.lstrip("0x").rjust(2, "0") for byte in reversed(array))
'0008f3a7'

Sería todo más simple si usaras f"{entero:02x}" para obtener la representación en vez de hex().
>>> enteros = (167, 243, 8, 0)
>>> array = [f"{entero:02x}" for entero in enteros]
>>> array
['a7', 'f3', '08', '00']
>>> int("".join(reversed(array)), 16)
586663

Le agrego un cero a la izquierda a las representaciones de 0 a 15 porque es lo que muestras en tu ejemplo, pero ten en cuenta que este cero no es inocuo si se agrega en medio de la cadena concatenada. Tampoco tendría sentido si incluyes valores por encima de 255.


text:
Q: While deploying on specific machines using azure devops can I only target Pilot run machines & post that other machines? I am currently having below scenario to crack :
I have deployment target(XYZ) on Azure devops. This XYZ group holds 20 targets, out of this 20 targets while deploying to production I want deployment should only happen at 2-3 machines first. Post successfull checks or post 2-3 days I can trigger on other set of machines.
I have no definite number of machiens that will always be my pilot machines.It may differ everytime.
As of now I have below approach , but I want to know what is the best practice that I can use to fulfil above requirement:
For now before deployment I will identify machines where pilot run will happen, I will add an extra tag to them under deployment group. Same tag will also be added under pipeline to the task.
As per this approach my deployment team will every time have to modify pipeline & deployment group, is there any better way to do this?

A: As indicated in the ticket you mentioned in the comment, currently as workarounds, we can filter by custom conditions or tags.
Filter by custom condition:

*

*Create a Pipeline Variable that contains server names as value.

*Add a Custom condition on Custom condition step:
and(succeeded(),contains(variables['IncludedServers'],variables['Agent.MachineName']))

*Modify the variables as needed when creating the release

Filter by tags:
We can use machine tags to limit deployment to specific sets of target servers.
The tags you assign allow you to limit deployment to specific servers when the deployment group is used in a Deployment group job.


text:
Q: Register generic type for each implementation of an interface Assuming I have the following types
public interface IBackgroundProcessor {}
public interface IBackgroundJob {}
public interface IStartupShutdownAction {}

public class BackgroundProcessor<TJob>
    : IBackgroundProcessor
    where TJob : IBackgroundJob
    {}

public class BackgroundProcessorStartupShutdownAction<TProcessor>
    : IStartupShutdownAction
    where TProcessor : IBackgroundProcessor
    {}

is there an easy way of registering a BackgroundProcessor<> for each IBackgroundJob in an assembly and a BackgroundProcessorStartupShutdownAction<> for each of the former?
Such that I can resolve MyConcreteBackgroundJob, BackgroundProcessor<MyConcreteBackgroundJob>, IEnumerable<IBackgroundProcessor> and IEnumerable<IStartupShutdownAction>
Currently, I do it like the following because I didn't find anything fitting in the docs, but I kinda think this pattern must be common enough that there is builtin support for it, and I just don't know about it:
public static void AddBackgroundJobs(this ContainerBuilder self,
                                     Assembly assembly)
{
  assembly.GetExportedTypes()
          .Where(t => t.IsAssignableTo<IBackgroundJob>() && !t.IsAbstract)
          .ForEach(registerJobProcessorAndAction);

  void registerJobProcessorAndAction(Type jobType)
  {
    var processorType = typeof(BackgroundProcessor<>)
                        .MakeGenericType(jobType);
    var actionType = typeof(BackgroundProcessorStartupShutdownAction<>)
                     .MakeGenericType(processorType);
    self.RegisterTypes(jobType, processorType, actionType)
        .AsImplementedInterfaces()
        .AsSelf()
        .SingleInstance();
  }
}


text:
Q: How to use zgrep to find out what line number or give some contextual info. surrounding a .gz file In Debian you can use zgrep to grep through a gunzipped archive file. The reason for making a gunzip file is easy enough, files such as changelogs are vast which can be highly compressed. The issue is with zgrep you only get a specific line and no above or below info. to give contextual info. on the change itself. An example to illustrate -
usr/share/doc/intel-microcode$ zgrep Fallout changelog.gz
  * Implements MDS mitigation (RIDL, Fallout, Zombieload), INTEL-SA-00223
  * Implements MDS mitigation (RIDL, Fallout, Zombieload), INTEL-SA-00223

Now as can be seen it seems my chip was affected by RIDL, Fallout and Zombieload bugs which seem to have been fixed by a software patch INTEL-SA-00223 which is mentioned but as can be seen it's pretty incomplete.
The way out is to use zless and then / RIDL or any of the other keywords and then you know but am wanting to know if there is any other way or that's the only workaround ? FWIW did come to know that the bugs were mitigated on 2019-05-14 where Intel made software patches affecting these and various other issues on that date. I did try using 'head' and 'tail' using pipes but neither of them proved to be effective.

A: Zutils (packaged in Debian) provides a more capable version of zgrep which supports all the usual contextual parameters:
$ zgrep -C3 Fallout /usr/share/doc/intel-microcode/changelog.Debian.gz

  * New upstream microcode datafile 20190618
    + SECURITY UPDATE
      Implements MDS mitigation (RIDL, Fallout, Zombieload), INTEL-SA-00223
      CVE-2018-12126, CVE-2018-12127, CVE-2018-12130, CVE-2019-11091
      for Sandybridge server and Core-X processors
    + Updated Microcodes:
--

  * New upstream microcode datafile 20190514
    + SECURITY UPDATE
      Implements MDS mitigation (RIDL, Fallout, Zombieload), INTEL-SA-00223
      CVE-2018-12126, CVE-2018-12127, CVE-2018-12130, CVE-2019-11091
    + New Microcodes:
      sig 0x00030678, pf_mask 0x02, 2019-04-22, rev 0x0838, size 52224

You can install it with sudo apt install zutils.

A: It is also only a workaround, but did you try
gzip -cd changelog.gz | grep -C <num_lines> "Fallout"

to display num_lines of context before and after the match (use -A <num_after> and -B <num_before> to fine-tune)?

A: You can use zcat and a normal grep:
zcat changelog.gz | grep -C3 "Fallout"

-C3 tells grep to provide 3 lines of context (3 above, 3 below).  Reduce this if you want less context.
You can tailor this further by using -B<number> and/or -A<number> instead (for 'before' and 'after' respectively.)


text:
Q: OpenCart: Class Loader not Found I am working a project, suddenly my system halted I gave it a reboot and now I am getting this error
Fatal error: Class 'Loader' not found in /var/www/html/projectfolder/index.php on line 29

I checked it in system->engine its there
Any idea?

A: Being stuck for 24 hours I did some research and found out if we have our admin panel on different vhost we can still open that and clear modifications from admin. Once they are cleared, this error is gone and site populates normally.


text:
Q: How can I get lead id in process builder I'm created process builder for task object. When "lead" object task is closed I want to submit that record to approve.
Actually What action I want choose next. How can get lead id? How can submit that record to approve?
Anyone please help me.
Thank you.


text:
Q: How emberjs function is invoked? I want to understand how the function in plugin is invoked.
Here's the code snippet from discourse-adplugin
export default Ember.Component.extend({
  ...
  _initGoogleDFP: function() {
    var self = this;
    loadGoogle(this.siteSettings).then(function() {
      ...
    });
  }.on('didInsertElement'),
  ...
});

There's no mention that the _initGoogleDFP function is evidently invoking by somebody but it's somehow invokes from guts of emberjs.
What is the principles of initialising emberjs components?
How _initGoogleDFP is invoking by emberjs?

A: The Ember.on function (or Function.prototype.on) returns a special function with some Ember implementation details:
export default Ember.Component.extend({
  ...
  _initGoogleDFP: <some-special-function-object>,
  ...
});

Ember iterates the keys in your class definition, looking for these special objects, and eventually calls Ember.addListener('didInsertElement', yourFunction).

You should generally avoid using .on. It's confusing. If you have two .on('didInsertElement'), in which order do they get called? Who knows.
The preferred way to write your code is to override didInsertElement:
export default Ember.Component.extend({
  ...
  didInsertElement() {
    this._super(...arguments);

    var self = this;
    loadGoogle(this.siteSettings).then(function() {
      ...
    });
  }
  ...
});

If you need to call _initGoogleDFP from other places, make it a function and you can call it from didInsertElement:
export default Ember.Component.extend({
  ...
  _initGoogleDFP: function() {
    var self = this;
    loadGoogle(this.siteSettings).then(function() {
      ...
    });
  },

  didInsertElement() {
    this._super(...arguments);
    this._initGoogleDFP();
  }
  ...
});


text:
Q: Determine the missing number in a grid of numbers I met this question yesterday while solving an I.Q test. It took me around 1 hour to come up with a solution that I'm not certain is the correct one.
Alright, without further ado, here's the puzzle:

What is the number that you should put instead of the dot?

****SPOILER ALERT****
MY INCOMPLETE SOLUTION
As you can see, every row is divided into 1 big number on the left, followed by four 1-digit numbers on the right.
So my idea is that if you take the sum of the first and second small numbers, then you take the sum of the third and fourth small numbers, and then you take the sum of the digits of both of the sums, then the result will be equal to the sum of the digits of the big number.
For example, take the third row:
The big number: 153
The four 1-digit numbers: 2, 1, 8, 7
The sum of 1st and 2nd = 2 + 1 = 3
The sum of 3rd and 4th = 8 + 7 = 15
The sum of the digits of both of the sums = 3 + 1 + 5 = 9
The sum of the digits of the big number = 1 + 5 + 3 = 9
However, this works for all rows, except the first one at the top. That's the closest I could get to the solution. Should a person find the complete solution, I'll be extremely grateful.

NOTE: it is entirely possible that the person who wrote this puzzle is playing "mind-games" with us, and that he included the first row just to deceive us, thus making the question even harder. But let's not make any assumptions here.
It is also worth noting that the choices that came with the puzzle were as follows:
A) 110
B) 128
C) 164
D) 92
Maybe the idea of the question is to choose the most different choice. the sum of the digits of all of these choices is 11, except for 110:
1 + 2 + 8 = 1 + 6 + 4 = 9 + 2 = 11
1 + 1 + 0 = 2

A: Operating under the assumption that we are being deceived by the puzzle maker, i.e. the first row is a ruse, the answer is fairly simple. Take the sum of the last two columns, multiply them by $10$, then add the sum of the first two columns to that number. In row $2$, for example:
$$5+7\rightarrow 120,9+3=12\rightarrow 120+12=132$$
This means, for our currently unsolved row, we'd get $B$, or $128$.
Can you elaborate why the puzzle maker might want to deceive us by giving us a faulty first row?
I'll update this if a more comprehensive solution comes to mind.

A: If you assume a linear model $y=\sum_{j=1}^4 \beta_j x_j$ with no intercept and ignore the first row, you get a perfect fit $\beta=(1, 1, 10, 10)$, as others have proposed, yielding 128.
If you assume a linear model $y=\beta_0+\sum_{j=1}^4 \beta_j x_j$ with intercept and include the first row, you get a perfect fit $\beta=(744, 56, -91, 252, 171)/26$, yielding $3340/26=128.462$.  Close enough?


text:
Q: How do I get an input file to read into a string array in C++? For some reason the full lines from my input file are not reading into the array, only the first word in each line. I am currently using the getline call, but I am not sure why it is not working. Here is the what I have for the call to populate the array. The txt file is a list of songs.
const int numTracks = 25;
string tracks[numTracks];
int count = 0, results;
string track, END;

cout << "Reading SetList.txt into array" << endl;

ifstream inputFile;
inputFile.open("SetList.txt");
while (count < numTracks && inputFile >> tracks[count])
{
    count++;
    getline(inputFile, track);
}
inputFile.close();

A: while (count < numTracks && inputFile >> tracks[count])

The >> operator reads a single word. And this code reads this single word into the vector in question.
getline(inputFile, track);

True, you're using getline(). To read the rest of the line, after the initial word, into some unrelated variable called track. track appears to be a very bored std::string that, apparently, gets overwritten on every iteration of the loop, and is otherwise completely ignored.

A: Your loop is using the operator>> to read the file into the array.  That operator reads one word at a time.  You need to remove that operator completely and use std::getline() to fill the array, eg:
const int numTracks = 25;
std::string tracks[numTracks];
int count = 0;

std::cout << "Reading SetList.txt into array" << std::endl;

std::ifstream inputFile;
inputFile.open("SetList.txt");
while (count < numTracks)
{
    if (!std::getline(inputFile, tracks[count])) break;
    count++;
}
inputFile.close();

Or:
const int numTracks = 25;
std::string tracks[numTracks];
int count = 0;

std::cout << "Reading SetList.txt into array" << std::endl;

std::ifstream inputFile;
inputFile.open("SetList.txt");
while ((count < numTracks) && (std::getline(inputFile, tracks[count]))
{
    count++;
}
inputFile.close();

Alternatively, consider using a std::vector instead of a fixed array, then you can use std::istream_iterator and std::back_inserter to get rid of the manual loop completely:
class line : public std::string {}

std::istream& operator>>(std::istream &is, line &l)
{
    return std::getline(is, l);
}

...

std::vector<std::string> tracks;

std::cout << "Reading SetList.txt into array" << std::endl;

std::ifstream inputFile;
inputFile.open("SetList.txt");

std::copy(
    std::istream_iterator<line>(inputFile),
    std::istream_iterator<line>(),
    std::back_inserter(tracks)
);

inputFile.close();


text:
Q: set bootbox dialog window focus through select2-open event I am opening a bootbox dialog box when the user click inside select-2 input box using the following code
$("#categoryfinder").on("select2-open", function () {
    bootbox.confirm("Are you sure?", function (result) {
        Example.show("Confirm result: " + result);
    });
});

Once it is opened, the popup window is not active and I have to click twice to close or to trigger any event on the popup
Please let me know if there is any solution for this.
EDIT: when I click inside 1, the popup is not active at 1,2,3, I have to click once to make it active.

A: I fixed this issue by doing the following changes
$("#allergenfinder").on("select2-opening", function (e) {
    e.preventDefault();
    excludeAllergenPrompt();

});


text:
Q: Is there a simpler notation to forward a particular keyword argument to a function? Sometimes I will write a function which calls another function with the same long keyword argument, as well as a bunch of unrelated arguments.
Is there a short notation for forwarding the keyword argument without repeating it twice, assuming that it must be called by keyword (because there are other keyword args for bar which are not used)?
Consider the following function.
def foo(a1, a2, a3, arg_with_very_long_name):
    # do other work
    bar(b1, b2, b3, b4, arg_with_very_long_name=arg_with_very_long_name)

Is there a shorter form for arg_with_very_long_name=arg_with_very_long_name in the call to bar above?

A: There's not a perfect way to do this better than what you have already.  One other option is to use **kwarg unpacking instead:
def foo(a, b, c, **kwargs):
    # do stuff
    bar(aa, bb, cc, **kwargs)

The downside (and upside) here is that you don't immediately know what keywords are getting forwarded on to bar.  It makes it so that foo accepts any default arguments that bar does -- But you can't introspect what those are just by looking at foo.

A: If the keyword argument follows directly the positional arguments, you need not use the kwarg=kwarg syntax:
def f(a, b, c, some_ver_long_kwarg_name=None):
    print(some_very_long_kwarg_name)

f(1, 2, 3, 4) # Prints 4


text:
Q: Change case of nodes in imported XML file via PHP preg_replace I'm trying to process an imported XML file and make the text in one of the nodes
<Name>SOMETHINGTOMAKELOWERCASE</Name>

lowercase
<Name>somethingtomakelowercase</Name>

So far I got:
$xml = file_get_contents($xmlfile);
$xml = preg_replace('/<Name>(.*)<\/Name>/e', '<Name>' . strtolower($1) . '</Name>',$xml);
fwrite(fopen($xmlfile, 'wb'), $xml);

I've tried about ten different versions of the regexp, but none of them will work. Could you please point me in the right direction as to the correct regexp?

A: Try this instead:
$xml = file_get_contents($xmlfile);
$xml = preg_replace('/<Name>(.*)<\/Name>/e', "'<Name>' . strtolower('\\1') . '</Name>'",$xml);
fwrite(fopen($xmlfile, 'wb'), $xml);

When using the /e modifier in preg_replace, you have to pass a string of code to be evaluated as the replacement parameter, not an already-evaluated expression.


text:
Q: Laravel query showing different Result in DB::Table and DB::Select with inner join I'm using 3 table
1.organizations
2.users
3.organization_user
So the organization_user is the pivot table for getting org. and user.
DB::select("SELECT users.name 'User Name',organizations.name 'Org Name'
   FROM users INNER JOIN organization_users ON
organization_users.user_id=users.id
    INNER JOIN organizations ON
organizations.id=organization_users.organization_id
   WHERE organization_users.organization_id=$org_id");

And getting the below result

[
{
"User Name": "Navid Anjum",
"Org Name": "org1"
},
{
"User Name": "kamal",
"Org Name": "org1"
} ]

But when using
DB::table('organization_users')
        ->join('users','users.id','=','organization_users.user_id')
        ->join('organizations','organizations.id','=',
        'organization_users.organization_id')
        ->select('users.name as Name','organizations.name as Org Name')
        ->where('organization_users.id','=',$org_id)
        ->get();

And getting the below result

[
{
"Name": "Navid Anjum",
"Org Name": "org1"
} ]

So What I'm doing wrong?

A: you not set the right id for organization_users in the second statement :
DB::table('organization_users')
    ->join('users','users.id','=','organization_users.user_id')
    ->join('organizations','organizations.id','=',
    'organization_users.organization_id')
    ->select('users.name as Name','organizations.name as Org Name')
    ->where('organization_users.organization_id','=',$org_id)
    ->get();