text:
Q: Game theory: Given a number N, decide the winner. Given a number $N$:

*

*Two people A and B subtracts a number k
$\left(~0 < k < N,\ k\mid N~\right)$ alternatively from $N$.

*The one who cannot make a move loses the game.Provided that A always starts first, decide the winner.

Initially, I tried solving this problem using dynamic programming considering the fact that a state can be a winning one if it leads to at least one losing state. Also, a state is a losing one if all the states it goes to are winning. Checking for all the states didn't prove to be time efficient. After looking at the solutions I found that this problem boils down to checking whether N is odd or even. What I think is, one can say that if a state X is losing then $\mathbf{X + 1}$ $\left(\,\mbox{as}\ \mathbf{1\mid\left(\,X + 1\,\right)}\,\right)$ will always be a winning state but what if $\mathbf{X}$ is a winning state ?.
How can one prove that even states will always be winning and vice versa ?.

A: Note a few things:
1) If you are passed an even number, you can not be made to lose in that turn.
This is because $N = 2m > 1$ and $1|N$ so you can pass $N -1$.
2) If you are passed an odd number, then either a) you are forced to lose if $N =1$ or b) you are forced to pass an even number. And your opponent cannot be made to lose in the next turn.
a) if $N =1$ you can't do anything.
b) if $N > 1$ but $N$ is odd so if $k|N$ then $k$ is odd and you must pass $N -k$ which is an odd minus an odd must be even.
3) if you are passed an even you can make it so that you are passed an even the next turn (if there is a next turn).
Just pass the $N-1$.  That will be odd and your opponent must pass you an even by 2). (or the opponent must lose if you passed a $1$).  [If you have a larger odd $k$ that divides $N$ you can pass $N -k$ which will also be odd.  That will speed the game up.]
4) The game is finite and must end.
You are passed a finite $N$ and you pass an $1 \le N - k < N$ that is smaller.  There are only a finite number (maximum $N$) turns that can be taken.
...... so ......
So if you are passed an even you need not lose that turn or, by induction, any other turn.  If you are passed an odd you might lose but you can not make your opponent lose.  All games must end.
Therefore (if both players play the best strategy) player $A$ will lose if the first $N$ is odd.  Player $A$ will win if the first $N$ is even.

A: Let $n=2^a\cdot d$ where $d$ is an odd number. We have two cases.
1) If $a>0$ then $n$ is even and if the player subtracts $0< d<n$ (or any divisor of $d$) then we obtain $n-d=(2^a-1)\cdot d$ which is odd.
2) If $a=0$ then $n$ is odd and any divisor $k$ is odd too. So for any move $0<k<n$ the new number $n-k$ is even.
Therefore we may conclude that the initial number $N$ is winning for the first player if and only if $N$ is even.

A: From an even state, you can always get to an odd state (by subtracting $1$), but from an odd state you can only get to an even state, because the only divisors of an odd number are odd, and odd minus odd is even.  (The game ends at the odd number $1$, since there is no integer $k$ between $0$ and $1$.)
Remark:  For a nontrivial variant, you might take a look at a game I came up with some years ago which, for lack of a better name, I call Factor Subtractor.  The sequence of starting numbers for which there is a winning opening move has no apparent regularity.

A: If $N=2$, then the second player, B wins the game.

Lets set some notations. Given $N$ as described above.
Let $a_1=N$.
First state:
Assume that A chooses in the first state $\alpha_1$.
Then let $b_1:=a_1-\alpha_1$.
Assume that B chooses in the first state $\beta_1$.
Then let $a_2:=b_1-\beta_1$.
Second state:
Assume that A chooses in the second state $\alpha_2$.
Then let $b_2:=a_2-\alpha_2$.
Assume that B chooses in the second state $\beta_2$.
Then let $a_3:=b_2-\beta_2$.
.......
.......
$i$-th state:
Assume that A chooses in the $i$-th state $\alpha_i$.
Then let $b_i:=a_i-\alpha_i$.
Assume that B chooses in the $i$-th state $\beta_i$.
Then let $a_{i+1}:=b_i-\beta_i$.

In all other cases, i.e., $2 \leq N$, the first player, A wins the game.
Let $k$ be the least natural number, which does'nt divides $N$, i.e.
$k:=min\{n \in \mathbb{N} : N-1 \geq n \nmid N  \}$.
  The strategy for the first player in the $i$-th state, is to choose the unique element $\alpha_i \in \{1, 2, 3, ..., k-2, k-1\}$ such that $b_i:=a_i-\alpha_i$ is divisible by $k$.

Let $k$ be the least natural number, which does'nt divides $N$, i.e.
$k:=min\{n \in \mathbb{N} : N-1 \geq n \nmid N  \}$.
[Notice that the set $\{n \in \mathbb{N} : n \nmid N \}$ is not empty.
Notice that $N-1 \nmid N$, since N is greater than $1$.]
Also notice that for every $t \in \{1, 2, 3, ..., k-2, k-1\}$ we have that:
$t\mid N$, by definition.

In $i$-th state the first player, A subtracts
the unique element $\alpha_i \in \{1, 2, 3, ..., k-2, k-1\}$;
such that $b_i:=a_i-\alpha_i$ is divisible by $k$.
[By the euclid's algorithm, A can be able to do such a move.]

Now it's the second player turn.
We claim that B could not win.
Suppose on contrary that B could win, so he/she must choose the whole remaining number; i.e. $b-i$
which means that the remaining number $b_i$ divides $N$.
On the other hand, $k \mid b_i$;
since A makes the remaining number divisible by $k$.
So we have: $k \mid b_i \mid N$,
so by the property of transitivity of division we have
that $k \mid N$, which contradicts the definition of $k$.

  Example
$N=60$.
In this case $k:=7$ is the least number which does not divides $60$.
The remainder of $a_1=60$ by $7$; is equal to $4$, so A subtracts $4$, and $56=b_1=a_1-\alpha_1=60-4$ is divisible by $7$.
Now it is the second player's turn for example he chooses $15$,
$41=a_2=b_1-\beta_1=56-15$ has the remainder equal to $6$ module $7$, so A subtracts $6$, and $35=b_2=a_2-\alpha_2=41-6$ is divisible by $7$.
Now again, it is the second player's turn for example he chooses $5$,
$30=a_3=b_2-\beta_2=35-5$ has the remainder equal to $2$ module $7$, so A subtracts $2$, and $28=b_3=a_3-\alpha_3=30-2$ is divisible by $7$.
Now again, it is the second player's turn for example he chooses $20$,
$8=a_4=b_3-\beta_3=28-20$ has the remainder equal to $1$ module $7$, so A subtracts 1, and $7=b_4=a_4-\alpha_4=8-1$ is divisible by $7$.
Now again, it is the second player's turn for example he chooses $2$,
$5=a_5=b_4-\beta_4=7-2$ has the remainder equal to $5$ module $7$, so A subtracts $5$; $0=b_5=a_5-\alpha_5=5-5$, and he wins the game.
  Notice that every integer like $a$ which is divisible by $7$ could not divide $60$, since $7$ does not divides $60$.


text:
Q: How to freeze a record once stage value got funded I have a following validation rule for "need to allow to create opportunities and be able to update opportunities as long as the deal stage is not funded.
and do not allow them to change the stage to funded. "
Everything working fine except "they should not be able to edit an opportunity if it's stage is Funded"
AND(
!ISNEW(),
ISPICKVAL( StageName , "Funded"),
$Profile.Name = "System Admin"
)

A: One solution (tip of the hat to @sfdcfox) is to change the Opportunity.recordType upon stage=funded to 'FundedOpportunity'.  Then create a new page layout where all the fields are read only and assign that page layout to Opportunities of recordtype ='FundedOpportunity'
Otherwise, you can brute force this by adding validation rules to every editable field checking for a change in value
Or...you can use an override of the Edit button with a VF page + page action controller that redirects to the View page if stage is funded, else to the edit page.

A: Formulas have to evaluate to true in order to fire. Therefore, the "profile name" check should be inverted:
AND(
    NOT(ISNEW()),
    ISPICKVAL(StageName, "Funded"),
    $Profile.Name<>"System Admin"
)

As a side note, I'm pretty sure it's "System Administrator", not "System Admin", which would have made it ineffective for everybody.

A: The first part of OR will stop them from going to Funded as a non admin, and the 2nd part wl stop them from editing when it is.
AND(
OR(
ISPICKVAL(StageName, "Closed Won"),
AND(
ISCHANGED(StageName),
ISPICKVAL(StageName, "Funded"))),
$Profile.Name <> "System Administrator")

redpajama_set_name: RedPajamaStackExchange


text:
Q: Swift: How to change imageView color to look like it was tapped? I have an imageView inside of a cell. However, when I tap it that cell, there aren't any visual indicators that it was tapped. I want it to look the same as an imageView inside a button, where it changes colors when you tap the button.
  func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
    let cell: UICollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath)

    // what do i do with the cell.imageView to change it's state to look like it was tapped?
  }

A:   func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
    let cell: IconCell = collectionView.cellForItemAtIndexPath(indexPath) as! IconCell
    cell.imageView.alpha = 0.5
    return true
  }

  func collectionView(collectionView: UICollectionView, didUnhighlightItemAtIndexPath indexPath: NSIndexPath) {
    let cell: IconCell = collectionView.cellForItemAtIndexPath(indexPath) as! IconCell
    cell.imageView.alpha = 1.0
  }


text:
Q: PyQt5 overriding QDockwidget event bug? I have the following problem where I want to customize the QDockwidget event function and calling super() already gives me an error withouth Code in it.
Error:
TypeError: invalid result from DockWindow.event(), an integer is required (got type NoneType)

Here is my actual Code:
from PyQt5.QtWidgets import QApplication, QDockWidget
from PyQt5.QtWidgets import QMainWindow
from PyQt5 import QtCore

import sys

class DockWindow(QDockWidget):
    def __init__(self, parent=None):
        super(DockWindow, self).__init__(parent, QtCore.Qt.Widget)

    def event(self, ev):
        # I actually want to do stuff here. But following already produces an error.
        super(DockWindow, self).event(ev)

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent, QtCore.Qt.Window)
        self.dock_window = DockWindow(parent=self)
        self.addDockWidget(QtCore.Qt.RightDockWidgetArea, self.dock_window)

def main(argv):
    app = QApplication(sys.argv)

    win = MainWindow()
    win.show()

    app.exec_()

if __name__ == '__main__':
    main(sys.argv)

EDIT:
return super(DockWindow, self).event(ev)

does the trick!


text:
Q: Spring MVC view/controller test of known good tiles setup fails with assertion error I have this MVC Controller:
@RequestMapping(produces = "text/html")
public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, @RequestParam(value = "sortFieldName", required = false) String sortFieldName, @RequestParam(value = "sortOrder", required = false) String sortOrder, Model uiModel) {
    if (page != null || size != null) {
        int sizeNo = size == null ? 10 : size.intValue();
        final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
        uiModel.addAttribute("smaker", Smak.findSmakEntries(firstResult, sizeNo, sortFieldName, sortOrder));
        float nrOfPages = (float) Smak.countSmaker() / sizeNo;
        uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
    } else {
        uiModel.addAttribute("smaker", Smak.findAllSmaker(sortFieldName, sortOrder));
    }
    return "smaker/list";
}

}
I use Tiles 2.2.2 and I have this view renders when the web app runs in Jetty, but I wanted to evaluate spring-test so I started with this simple test:
@RunWith(SpringJUnit4ClassRunner.class)
public class ViewsControllerTests extends AbstractContextControllerTests {

    private MockMvc mockMvc;

    @Before
    public void setup() throws Exception {
        this.mockMvc = webAppContextSetup(this.wac).alwaysExpect(status().isOk()).build();
    }//wac is in the superclass which loads it from file

    @Test
    public void getSmakerView() throws Exception {
        this.mockMvc.perform(get("/smaker"))
                .andExpect(view().name(containsString("smaker/list")));
    }

}

Indeed I have Rendering view [org.springframework.web.servlet.view.tiles2.TilesView name 'smaker/list'; in the logs when I run this project in Jetty.
Yet when I run tests the test above it fails with
java.lang.AssertionError: Expected: a string containing "smaker/list but: was "uncaughtException"

which is my default ErrorView for my SimpleMappingExceptionResolver.
So something would seem to be wrong with either my test or my assumptions on what it does. Any ideas what my mistake could be here?

A: The problem is caused by the call of
uiModel.addAttribute("smaker", Smak.findAllSmaker(sortFieldName, sortOrder));

especially this part: Smak.findAllSmaker
Without any application context and resulting dependency injection or mocking this line will produce the problem you are facing.


text:
Q: Private chat with SignalR I would like to know if is possible to create a chat for private conversation like gmail chat or hotmail..
How can I ensure that only client A talks with client B?
How can I ensure that only logged clients can talk?

A: Try this application for Private chat with SignalR
Description of Application:
http://www.aspbucket.com/2016/03/implement-of-private-one-to-one-chat.html
Download link
https://github.com/shivam01990/SignalR-private-one-to-one-chat

A: Sure, you can create a unique "Group" each time a user initiates a chat with another user (or set of users). Then when you send messages to that group only those users would receive the message. You could also layer more security in front of sending messages to a group to ensure that the person sending the message is allowed to send a message to that group.

A: Look at ChatWithTracking in Basic chat sample, that's a great starting point for IM setup
p.s: updated the link; using a search query in case they change the repo structure again

A: Each client connecting to a hub passes a unique connection id. You can retrieve this value in the Context.ConnectionId property of the hub context. If your application needs to map a user to the connection id and persist that mapping, you can use one of the following:

*

*In-memory storage, such as a dictionary

*SignalR group for each user

*Permanent, external storage, such as a database table or Windows Azure table

http://www.asp.net/signalr/overview/hubs-api/mapping-users-to-connections


text:
Q: Missing a temporary folder. in wp-admin when i am trying to upload images from wp-admin it shows Missing a temporary folder.
I have tried php.ini for tmp folder but php.ini is not working. Is there any solution?


text:
Q: Passing information between test methods in a junit testcase Currently I am creating a TestCase for one work flow and a workflow have different steps.
The results of one step is important since , second step needs to know value of step1's execution.
class TestCaseWorkFlow1 extends TestCase {

  private static String resultOfStep1 = null;

  public void testStep1(){

    if(failed){
        resultOfStep1 = "failed";
    }
  }

  public void testStep2(){

    if(resultOfStep1 != null ) {
         //First test failed.
    }else {
    }

  }

}
Currently we are using static variable to pass information between testmethods .
What is the best solution for this scenario ?
Please help.
Thanks
J

A: This does not sound like a unit test to me. That is fine, but JUnit may not be the best tool. Can you upgrade to JUnit 4?
Assuming yes -

*

*Write a JUnit runner to ensure the order of your unit tests

*Pass state via static variables.

*Use Assume to validate that step one has worked.

A: Your tests should really be independent of each other, so think if there's a way to do that. For example, you know what the outcome of a successful step1 is, so just provide that as input in step2 using a mock object or other approach. Or see if there's a way to break the sequential coupling of the steps so that each can be run independently.

A: The conventional wisdom is that the best solution is to have all the steps recomputed from scratch for each test, usually in a private helper method, so that you don't depend on the order in which JUnit executes your tests (which is not actually defined to be in textual order). You should probably do this, unless some of the steps take a truly horrible amount of time to recompute.

A: It seems that you are trying to achieve something beyond unit testing... which is perfectly fine. Try using other tools that are built on top of jUnit and provide you with mechanisms for testing behavior rather than small units of code. One of tools that I've been successfully using for some time is jBehave. You'll end up describing test scenarios using plain text scripts executed by methods which match scenario steps.

A: I agree with Kilian and Graham. Tests should be independent and self-contained. I.e. each test should run alone the same way is it runs with other tests.
But if you have some good reason for such dependency between tests, maybe try TestNG. In TestNG you can specify tests dependent on each other.

A: As others have noted, you should make your tests independent of each other. One way to achieve this is to set up test fixtures correctly for each test.
However, the tests in your example look like they test different phases of the same scenario. So I would consider unifying all into a single test method, if that scenario is not too complicated.

A: in this basic example, the variable is changed in the test A, and can be used in the test B
public class BasicTest extends ActivityInstrumentationTestCase2 {
    public BasicTest() throws ClassNotFoundException {
        super(TARGET_PACKAGE_ID, launcherActivityClass);
    }

    public static class MyClass {
        public static String myvar = null;
        public void set(String s) {
            myvar = s;
        }
        public String get() {
            return myvar;
        }
    }

    private MyClass sharedVar;

    @Override
    protected void setUp() throws Exception {
        sharedVar = new MyClass();
    }

    public void test_A() {
        Log.d(S,"run A");
        sharedVar.set("blah");
    }

    public void test_B() {
        Log.d(S,"run B");
        Log.i(S,"sharedVar is: " + sharedVar.get());
    }

}

output result is:
run A
run B
sharedVar is: blah


text:
Q: How can I write private tag GDAL_NODATA to a TIFF using libtiff? In an earlier post I asked how to retrieve this tag from TIFF using python and libtiff. Eventually I found the answer and I reported on the solution last week. I also realised that in order to write a proper GeoTIFF, more tags are needed than only GDAL_NODATA, viz. ModelPixelScaleTag, ModelTiepointTag, ModelTransformationTag, GeoKeyDirectoryTag, GeoDoubleParamsTag, GeoAsciiParamsTag and GDAL_METADATA. Maybe even more are needed? The GeoTIFF format specification is found here - rather extensive ...
Now I want to also know how to write private tags. It goes wrong when I reach line 934 of module libtiff_ctypes:
r = libtiff.TIFFSetField(self, tag, data)
The GDAL_NODATA tag is part of the dictionary tifftags - see my earlier post. The error message that is reported is: WindowsError: exception: access violation reading 0xFFFFD8F1. What am I doing wrong?

A: With the help of a colleague, I have found the problem. This was my code:
tif.SetField("GDAL_NODATA", int(nodatavalue))

The definition of GDAL_NODATA I used was however like this:
TIFFFieldInfo(42113, -1, -1, TIFFDataType.TIFF_ASCII, FIELD_CUSTOM, True, False, "GDAL_NODATA")

The error is no more coming since we changed the first statement to this:
tif.SetField("GDAL_NODATA", str(nodatavalue))


text:
Q: RecyclerView in CoordinatorLayout shows items only after scrolling down I am using a RecyclerView in a CoordinaterLayout to display search result items. However the items show only after scrolling a bit, and I cannot figure out why. I assume it would have to do with the RecyclerView not adjusting to the reduced size in the CoordinatorLayout.
Any clues to this?

Layout is pretty much straighforward and the basic template provided by android studio except for the RecyclerView.
activity_results_recycler.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:fitsSystemWindows="true"
    tools:context="com.alamgir_swi.abjad.ResultsRecyclerActivity">

    <android.support.design.widget.AppBarLayout android:id="@+id/app_bar"
        android:fitsSystemWindows="true" android:layout_height="@dimen/app_bar_height"
        android:layout_width="match_parent" android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.design.widget.CollapsingToolbarLayout android:id="@+id/toolbar_layout"
            android:fitsSystemWindows="true" android:layout_width="match_parent"
            android:layout_height="match_parent" app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:contentScrim="?attr/colorPrimary">

            <android.support.v7.widget.Toolbar android:id="@+id/toolbar"
                android:layout_height="?attr/actionBarSize" android:layout_width="match_parent"
                app:layout_collapseMode="pin" app:popupTheme="@style/AppTheme.PopupOverlay" />

        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_results_recycler" />

    <android.support.design.widget.FloatingActionButton android:id="@+id/fab"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:layout_margin="@dimen/fab_margin" app:layout_anchor="@id/app_bar"
        app:layout_anchorGravity="bottom|end" android:src="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

content_results_recycler.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/activity_results_recycler"
    tools:context="com.alamgir_swi.abjad.ResultsRecyclerActivity"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/abjadList"
    >
</android.support.v7.widget.RecyclerView>

abjad_entry.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="10dp" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/abjad_entry"
        android:layout_gravity="right" />
</RelativeLayout>

Thank you for any hints.

A: Found the source of the problem.
I needed to call notifyDataSetChanged() on my instance of RecyclerView.LayoutManager after getting data from the CursorLoader.


text:
Q: How to put image in a pdf generated by reportlab which is stored in DO spaces - Django I want to put my logo in pdf that is stored in digital ocean spaces. The code that I wrote was
pdf.drawImage('https://dummy-bucket.sgp1.digitaloceanspaces.com/static/images/logo_name_header.svg', -0.10*cm,10*cm)

this throws the below error
fileName=<_io.BytesIO object at 0x000001D1CE603A90> identity=[ImageReader@0x1d1ce5e6f70] cannot identify image file <_io.BytesIO object at 0x000001D1CE603A90>

The file is accessible if entered in the address bar. I do not understand what this error is, please suggest me what to do?
The complete code
def get_pdf(request):

    data= {
       ... some data

        }

    try:

        buffer = io.BytesIO()

        pdf = canvas.Canvas(buffer, pagesize=A4)

        pdf = base_temp(pdf, data)  #base temp is a pre designed canvas
        pdf.setTitle("Invoice")

 pdf.drawImage('https://dummy-bucket.sgp1.digitaloceanspaces.com/static/images/logo_name_header.svg', -0.10*cm,10*cm)

        pdf.showPage()

        pdf.save()

        buffer.seek(0)

        # sending pdf as a response
        response =  FileResponse(buffer)

        # setting the content-type to pdf
        response['Content-Type'] = 'application/pdf'

        # telling the response that it is a pdf file
        response['Content-Disposition'] = f'inline; filename="{data["invoice_number"]}.pdf"'

        return response
    except Exception as e:

        print(e)

        return HttpResponse(str(e))


text:
Q: Multi Thread Delphi I'm having problems with multi thread in delphi. I Have a list of names (something about 2.000 names), and I need to get some data of each name in my site. My system works perfectly, except the thread control.
I want to create 10 threads, and, when some thread terminate, create another... until end of list.
var
 Form1: TForm;
 tCount: Integer;  //threads count

implementation

type
 TCheck = class(TThread)
 public
  constructor Create(Name: string);
  destructor Destroy; Override;
 protected
  procedure Execute; Override;
 end;

 MainT = class(TThread)
 protected
  procedure Execute; Override;
 end;

destructor TCheck.Destroy;
begin
 Dec(tCount);
end;

procedure MainT.Execute;
var
 i: Integer;
 Load: TStringList;
begin
 Load:=TStringList.Create;
 Load.LoadFromFile('C:\mynames.txt');

 for i:= 0 to Load.Count -1 do
 begin

  if tCount = 10 then  //if we have 10 threads running...
  begin
   repeat
    Sleep(1);
   until tCount < 10;
  end;

  TCheck.Create(Load.Strings[i]);
  TCheck.Start;
  Inc(tCount);

 end;

end;  // end of procedure

Well, I didn't put the TCheck.Constructor because the problem is the method how I'm check the number of created threads. I mean, my software just stop, without any error message, sometimes check 500 names, sometimes 150 names...
Sorry for Bad English.

A: Here is a threadsafe queue solution using generics.
Define how many consumer threads you want, the queue depth and just run the DoSomeJob procedure from a thread.
Define your job working with a string as a generic procedure (in CaptureJob).
When the queue is empty, the consumer threads will be destroyed. The DoSomeJob procedure waits until all jobs are ready.
You can easily turn this into a generic worker pool, reusing the threads without destroying them. The generic structure of the job items also make them suitable to handle different kinds of work.
Note this queue works on XE2 and above. If you are on a older delphi version, look for a similar threadsafe queue as suggested in comments.
uses
  Classes,SyncObjs,Generics.Collections;

Type
  TMyConsumerItem = class(TThread)
  private
    FQueue : TThreadedQueue<TProc>;
    FSignal : TCountDownEvent;
  protected
    procedure Execute; override;
  public
    constructor Create( aQueue : TThreadedQueue<TProc>; aSignal : TCountdownEvent);
  end;

constructor TMyConsumerItem.Create(aQueue: TThreadedQueue<TProc>);
begin
  Inherited Create(false);
  Self.FreeOnTerminate := true;
  FQueue := aQueue;
  FSignal := aSignal;
end;

procedure TMyConsumerItem.Execute;
var
  aProc : TProc;
begin
  try
    repeat
      FQueue.PopItem(aProc);
      if not Assigned(aProc) then
        break; // Drop this thread
      aProc();
    until Terminated;
  finally
    FSignal.Signal;
  end;
end;

procedure DoSomeJob(myListItems : TStringList);
const
  cThreadCount = 10;
  cMyQueueDepth = 100;
var
  i : Integer;
  aQueue : TThreadedQueue<TProc>;
  aCounter : TCountDownEvent;
  function CaptureJob( const aString : string) : TProc;
  begin
    Result :=
      procedure
      begin
        // Do some job with aString
      end;
  end;
begin
  aQueue := TThreadedQueue<TProc>.Create(cMyQueueDepth);
  aCounter := TCountDownEvent.Create(cThreadCount);
  try
    for i := 1 to cThreadCount do
      TMyConsumerItem.Create(aQueue,aCounter);
    for i := 0 to myListItems.Count-1 do begin
      aQueue.PushItem( CaptureJob( myListItems[i]));
    end;
  finally
    for i := 1 to cThreadCount do
      aQueue.PushItem(nil);
    aCounter.WaitFor;  // Wait for threads to finish
    aCounter.Free;
    aQueue.Free;
  end;
end;

NB: Ken explains why your initialization and start of threads are wrong. This proposal shows a better structure to handle this type of problems in a more generic way.

A: If you don't declare a variable to hold the return value of TCheck.Create, you can't access TCheck.Start (there's no instance of TCheck you can use to access the Start method).
The proper way would be to declare a var Check: TCheck; inside MainT.Execute, and then store the value returned:
Check := TCheck.Create(Load[i]);  { See note below }
Check.Start;
Inc(tCount);

NOTE The default property of TStringList is Strings, so you don't need to use it. You can just access Strings directly as I have above. The next two lines are exactly the same thing (but obviously one is shorter and easier to type):
Load.Strings[i];
Load[i];

If you don't want to keep a reference to TCheck, just change your code to be a with block (including the begin..end, and containing no other code in the block (this is the only way I ever recommend using a with):
with TCheck.Create(Load[i]) do
begin
  Start;
  Inc(tCount);
end;

With that being said, there are much better ways you can do this instead of creating/destroying all kinds of threads. As others have said, you could have a list of 10 threads and queue the work for them, so that each would process an item from Load and then return to get another item to process when done, and repeat until the list is complete. It's hard to say exactly how you would do that, because that would depend on your Delphi version. (There are libraries available that will do most of the work for you, like OMNIThreadLibrary, but it's not available for some older versions of Delphi. Recent versions of Delphi also support TQueue and TObjectQueue and some other types and functionality that might be very helpful.
(If you have a different question about how to do this in a queue with a limited number of threads, that should be a new question, not something you add to this one.)


text:
Q: Find the probability that $2$ black balls extracted are from urn $B$.
The urn $A$ contains $3$ black balls and $5$ red balls while urn $B$ contains
  $4$ black balls and $7$ red balls , If the $2$ balls are extracted simultaneosuly
   from any of the two urns are found to be black, find the probability that they are extracted from urn $B$.

$\dfrac{\dbinom{3}{2}}{\dbinom{8}{2}}+\dfrac{\dbinom{4}{2}}{\dbinom{11}{2}}=\dfrac{333}{1540}$
I am not sure if my logic is correct, also please tell that which concept of probability this
question uses whether is is binomial distribution or condintional probability etc.
I look for a short and simple way .
I have studied maths up to $12$th grade.

A: Be careful when you add probabilities. Usually, adding is fine if the probabilities are distinct (they do not affect each other), but here, they most certainly do. The method I will walk through in this solution requires knowledge of some basic conditional probability.
We begin by finding the total number of ways to end up with $2$ black balls. This is easy to count: we can select $2$ of the $3$ from $A,$ which can be done in $\dbinom{3}{2} = 3$ ways; $2$ of the $4$ from $B,$ which can be done in $\dbinom{4}{2} = 6$ ways; or $1$ ball from each urn, which can be done in $3 \cdot 4 = 12$ ways. Our "sample space" is $3 + 6 + 12 = 21$ ways (to get $2$ black balls).
Now we find the number of ways to get $6$ black balls from just $B.$ We already found this (above) to be $6$ ways.
Our probability, then, is $P = \frac{6}{21} = \boxed{\frac{2}{7}}.$

A: $\begin{eqnarray}
P(B|bb)=P(bb|B)\frac{P(B)}{P(bb)}...(*)
\end{eqnarray}$
Now, $P(bb)=P(bb|B)P(B)+P(bb|A)P(A)=\frac{1}{2}(P(bb|B)+P(bb|A))=\frac{1}{2}\left[\dfrac{\binom{4}{2}}{\binom{11}{2}}+\dfrac{\binom{3}{2}}{\binom{8}{2}}\right]$.
Sustituying in $(*)$
$\begin{eqnarray}
P(B|bb)&=&P(bb|B)\frac{P(B)}{P(bb)}\\
&=&\dfrac{\frac{\binom{4}{2}}{\binom{11}{2}}}{\dfrac{\binom{4}{2}}{\binom{11}{2}}+\dfrac{\binom{3}{2}}{\binom{8}{2}}}\\
&=&\frac{56}{111}\\
&\sim&0.504
\end{eqnarray}$

A: I will use some notation with which you might be unfamiliar. Feel free to ask for clarification.
Let $T = \{\text{Drew 2 black balls}\}$ and $U = \{\text{Chose urn $i$}\}$ for $i = A,B$. Then, we are interested in
$$P(U_B|T) = \frac{P(TU_B)}{P(T)}.\tag{$\star$}$$
This is true using Bayes' rule.
Notice that it would make calculations easier if I conditioned the numerator on $U$
$$P(TU_B) = P(T|U_B)P(U_B)$$
Since the question doesn't specify, I think we can assume that each urn is chosen with equal probability, so $P(U_B) = \frac{1}{2}$.
Now, if we chose urn $U$, what is the probability that we draw two black balls?
You seem to understand that this is
$$P(T|U_B) = \frac{\binom{4}{2}}{\binom{11}{2}} = \frac{6}{55}.$$
To get the denominator in $(\star)$, we use the law of total probability and then condition again on $U_i$,
\begin{align*}
P(T) &= P(TU_A)+P(TU_B) \\
&= P(T|U_A)P(U_A)+P(T|U_B)P(U_B) \\
&= \frac{\binom{3}{2}}{\binom{8}{2}}\cdot\frac{1}{2}+\frac{\binom{4}{2}}{\binom{11}{2}}\cdot\frac{1}{2} \\
&= \frac{3}{28}\cdot\frac{1}{2}+\frac{6}{55}\cdot\frac{1}{2}.
\end{align*}
Putting it all together we see that
$$P(U_B|T) = \frac{P(TU_B)}{P(T)} = \frac{\frac{6}{55}\cdot\frac{1}{2}}{\frac{3}{28}\cdot\frac{1}{2}+\frac{6}{55}\cdot\frac{1}{2}} = \frac{56}{111}=0.5045045
$$

A: Since the balls must be extracted from the same urn, we simply wish the conditional probability that they are event $B$: "from urn-$B$", given that they are event $b$: "both black".
We use Bayes' Rule and the Law of Total Probability.
$$\begin{align}\mathsf P(B\mid b) & = \dfrac{\mathsf P(b\mid B)\;\mathsf P(B)}{\mathsf P(b)} & \textsf{Bayes' Rule}
\\ & = \dfrac{\mathsf P(b\mid B)\,\mathsf P(B)}{\mathsf P(b\mid B)\;\mathsf P(B)+\mathsf P(b\mid A)\;\mathsf P(A)} & \text{Law of Total Probability}
\\ & = \frac{\mathsf P(b\mid B)}{\mathsf P(b\mid B)+\mathsf P(b\mid A)} & {\textsf{assuming no bias in urn selection}\\\mathsf P(A)=\mathsf P(B) } \\ & = \dfrac{\binom 3 2 / \binom 8 2}{\binom 3 2 / \binom 8 2 + \binom 4 2 / \binom {11} 2} & \textsf{as you were attempting to reason} \\ & = \frac {55}{111}  \end{align}$$


text:
Q: How to align labels with different length using geom_text in ggplot2? I have added a caption to my plot using geom_text and I want to justify the labels to the left and right respectively (since I am using facet_grid and I have two different groups).
This is my example:
library(ggplot2)
library(dplyr)

# DATA
val1 <- c(2.1490626,2.2035281,1.5927854,3.1399245,2.3967338,3.7915825,4.6691277,3.0727319,2.9230937,2.6239759,3.7664386,4.0160378,1.2500835,4.7648343,0.0000000,5.6740227,2.7510256,3.0709322,2.7998003,4.0809085,2.5178086,5.9713330,2.7779843,3.6724801,4.2648527,3.6841084,2.5597235,3.8477471,2.6587736,2.2742209,4.5862788,6.1989269,4.1167091,3.1769325,4.2404515,5.3627032,4.1576810,4.3387921,1.4024381,0.0000000,4.3999099,3.4381837,4.8269218,2.6308474,5.3481382,4.9549753,4.5389650,1.3002293,2.8648220,2.4015338,2.0962332,2.6774765,3.0581759,2.5786137,5.0539080,3.8545796,4.3429043,4.2233248,2.0434363,4.5980727)
val2 <- c(3.7691229,3.6478055,0.5435826,1.9665861,3.0802654,1.2248374,1.7311236,2.2492826,2.2365337,1.5726119,2.0147144,2.3550348,1.9527204,3.3689502,1.7847986,3.5901329,1.6833872,3.4240479,1.8372175,0.0000000,2.5701453,3.6551315,4.0327091,3.8781182)
val3 <- c(2.1490626,2.2035281,1.5927854,3.1399245,2.3967338,3.7915825,4.6691277,3.0727319,2.9230937,2.6239759,3.7664386,4.0160378,1.2500835,4.7648343,0.0000000,5.6740227,2.7510256,3.0709322,2.7998003,4.0809085,2.5178086,5.9713330,2.7779843,3.6724801,4.2648527,3.6841084,2.5597235,3.8477471,2.6587736,2.2742209,4.5862788,6.1989269,4.1167091,3.1769325,4.2404515,5.3627032,4.1576810,4.3387921,1.4024381,0.0000000,4.3999099,3.4381837,4.8269218,2.6308474,5.3481382,4.9549753,4.5389650,1.3002293,2.8648220,2.4015338,2.0962332,2.6774765,3.0581759,2.5786137,5.0539080,3.8545796,4.3429043,4.2233248,2.0434363,4.5980727)

df1 <- data.frame(value = val1)
df2 <- data.frame(value = val2)
df3 <- data.frame(value = val3)

data <- bind_rows(lst(df1, df2, df3), .id = 'id')
data$Sex <- rep(c("Male", "Female"), times=72)
data$d <- "ff"
data <- as.data.frame(unclass(data), stringsAsFactors = TRUE)

# PLOT

p <- data %>%
  ggplot(aes(value)) +
  geom_density(lwd = 1.2, colour="red", show.legend = FALSE) +
  geom_histogram(aes(y=..density.., fill = id), bins=10, col="black", alpha=0.2) +
  facet_grid(id ~ Sex ) +
  xlab("type_data") +
  ylab("Density") +
  ggtitle("title") +
  guides(fill=guide_legend(title="legend_title")) +
  theme(strip.text.y = element_blank())

p

# ADD CAPTION

caption_df = data.frame(value = c(min(data$value), max(data$value)), id = c(rep(tail(levels(data$id), n=1), times=length(levels(data$Sex)))),
                        Sex = c(levels(data$Sex)))
caption_df$txt = c("This is the first caption \nThis is the second caption", "This is the first caption \nThis is the second caption")

yrange <- layer_scales(p)$y$range$range
ypos <- min(yrange) - 0.4 * diff(yrange)

p + coord_cartesian(clip = "off",
                    ylim = layer_scales(p)$y$range$range,
                    xlim = layer_scales(p)$x$range$range) +
  geom_text(data = caption_df,
            aes(y = ypos, label = txt)) +
  theme(plot.margin = unit(c(1,1,2,1), "cm"))

This is how it looks:

This is what I want:

I have tried using hjust=0 but it doesn't look nice (they are both displaced)

I tried with hjust=1 but I have the same problem (displaced):

vjust doesn't give me what I need either.
Does anyone have an idea about how to solve it?
Thanks in advance

A: You can use hjust and nudge_x together in geom_text.
hjust = 0 will left-align the text, but also shifting the location of the text. nudge_x helps to counteract the effect of hjust by adding some "padding" around the text.
Try out different values of nudge_x to see which one best fit your goal.
library(ggplot2)

data %>%
  ggplot(aes(value)) +
  geom_density(lwd = 1.2, colour="red", show.legend = FALSE) +
  geom_histogram(aes(y=..density.., fill = id), bins=10, col="black", alpha=0.2) +
  facet_grid(id ~ Sex ) +
  xlab("type_data") +
  ylab("Density") +
  ggtitle("title") +
  guides(fill=guide_legend(title="legend_title")) +
  theme(strip.text.y = element_blank()) +
  coord_cartesian(clip = "off",
                  ylim = layer_scales(p)$y$range$range,
                  xlim = layer_scales(p)$x$range$range) +
  geom_text(data = caption_df,
            aes(y = ypos, label = txt), hjust = 0, nudge_x =  -1) +
  theme(plot.margin = unit(c(1,1,2,1), "cm"))


text:
Q: EVP AES Encryption on PSP I am trying to make a MMORPG for PSP and I will be encrypting al data sent over the network in some form. I have chosen AES for this.
I have this code:
int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key, unsigned char *iv, unsigned char *ciphertext){

int len;

int ciphertext_len;

/* Create and initialise the context */
EVP_CIPHER_CTX_init(&ctx);
appendLog("CTX Init", LOG_CRYPTO);
/* Initialise the encryption operation. IMPORTANT - ensure you use a key
* and IV size appropriate for your cipher
* In this example we are using 256 bit AES (i.e. a 256 bit key). The
* IV size for *most* modes is the same as the block size. For AES this
* is 128 bits */
if(1 != EVP_EncryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, key, iv))
    printLastError("2");
appendLog("Encrypt started", LOG_CRYPTO);
/* Provide the message to be encrypted, and obtain the encrypted output.
* EVP_EncryptUpdate can be called multiple times if necessary
*/
if(1 != EVP_EncryptUpdate(&ctx, ciphertext, &len, plaintext, plaintext_len))
    printLastError("3");
ciphertext_len = len;
appendLog("Mid encrypt", LOG_CRYPTO);
/* Finalise the encryption. Further ciphertext bytes may be written at
* this stage.
*/
if(1 != EVP_EncryptFinal_ex(&ctx, ciphertext + len, &len)) printLastError("4");
ciphertext_len += len;
appendLog("Encrypt final", LOG_CRYPTO);
/* Clean up */
EVP_CIPHER_CTX_cleanup(&ctx);
appendLog("CTX Cleanup", LOG_CRYPTO);
return ciphertext_len;
}

It freezes my PSP after writing "Mid encrypt" to the logs. I was wondering if there is anything noticeably wrong with this code. I am using openSSL v0.9.7j for PSP.
The original AES encrypt code:
int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key, unsigned char *iv, unsigned char *ciphertext){
EVP_CIPHER_CTX *ctx;

int len;

int ciphertext_len;

/* Create and initialise the context */
if(!(ctx = EVP_CIPHER_CTX_new())) exit(0);

/* Initialise the encryption operation. IMPORTANT - ensure you use a key
* and IV size appropriate for your cipher
* In this example we are using 256 bit AES (i.e. a 256 bit key). The
* IV size for *most* modes is the same as the block size. For AES this
* is 128 bits */
if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
exit(0);

/* Provide the message to be encrypted, and obtain the encrypted output.
* EVP_EncryptUpdate can be called multiple times if necessary
*/
if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
exit(0);
ciphertext_len = len;

/* Finalise the encryption. Further ciphertext bytes may be written at
* this stage.
*/
if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) exit(0);
ciphertext_len += len;

/* Clean up */
EVP_CIPHER_CTX_free(ctx);
return ciphertext_len;
}

The PSPSDK openSSL does not have functions EVP_CIPHER_CTX_new() or EVP_CIPHER_CTX_free() and my EVP_CIPHER_CTX is declared globally and not in the function anymore.
My function call:
char *newS;
char AESKey[32];
char IV[16];
sprintf(AESKey, "12345678901234567890123456789012");
sprintf(IV, "1234567890123456");
encrypted_length = encrypt("HelloFromPSP", strlen("HelloFromPSP"), AESKey, IV, newS);

Can anyone help me figure out why the EVP_EncryptFinal_ex is frezing?
EDIT: Somehow managed to fix by going back to my old code(which was also freezing, odd)
char encrypted[4098]; //Could be smaller but is this size because it holds RSA data at some points in the code
char AESKey[32]; //Recieved from server, no sprintf filling this
char IV[16]; //Recieved from server, no sprintf filling this
encrypted_length = encrypt("HelloFromPSP", strlen("HelloFromPSP"), AESKey, IV, encrypted);


text:
Q: Trigger an action to start after X milliseconds I'm developing a Xamarin Forms mobile app, which has a page containing a SearchBar, a ListView, and Map control.  The list view contains a list of addresses, which are reflected as pins on the map.
As the user types in the SearchBar, the ListView is automatically updated (through ViewModel binding).  The ViewModel method that filters the datasource for the list looks something like this...
void FilterList()
{
    listDataSource = new ObservableCollection<location>(
        locationData.Where(l => l.Address.Contains(searchBar.Text))
    );

    // ***** Now, update the map pins using the data in listDataSource
}

I want to update the Map as the ListView is filtered, but not on EVERY keypress as that could happen multiple times a second.  Essentially, I want a "rolling pause" in each FilterList event before the Map is updated.  In pseudo-code...
    // ***** Now, update the map pins using the data in listDataSource
    if (a previously-requested map update is pending)
    {
        // Cancel the pending map update request
    }

    // Request a new map update in 1000ms using [listDataSource]

It's possible to do this using the Stopwatch class, which is available in Portable Class Libraries, but I suspect there's a cleaner/better way to accomplish this using Tasks.
Can anyone suggest a "cleverer" PCL-compatible way to do this?

A: you can try :
await Task.Delay(2000);

A: The problem with simple delays is that you can get a bunch of events queued up for when the delay expires. You can add logic to throw away the events that were raised while the delay was running. If you want to declare the logic at a higher level, you can use Reactive Extensions.

A: Just like you said this can be accomplished in a very clean way using Tasks and async programming.
You will want to read about it: http://msdn.microsoft.com/en-us/library/hh191443.aspx
Here's an example:
public async Task DelayActionAsync(int delay, Action action)
{
    await Task.Delay(delay);

    action();
}

A: Here is what I've done and it works in my Xamarin Form apps.
    public string Search
    {
        get { return _search; }
        set
        {
            if (_search == value)
                return;

            _search = value;
            triggerSearch = false;
            Task.Run(async () =>
            {
                string searchText = _search;
                await Task.Delay(2000);
                if (_search == searchText)
                {
                    await ActionToFilter();
                }
            });
        }
    }

I've this 'Search' Property binded to my Entry field. Whenever the user filters something, code waits for 1 second and then compares the new Text field with the field it was before 1 second before. Assuming the string is equal implies that user has stopped entering the text and code can now be triggered to filter.

A: Working in latest xamarin version.
Another Great method way on button click is ,
    public async void OnButtonClickHandler(Object sender, EventArgs e)
{
    try
    {
        //ShowProgresBar("Loading...");

        await Task.Run(() =>
        {
            Task.Delay(2000); //wait for two seconds

            //TODO Your Business logic goes here
            //HideProgressBar();

        });

        await DisplayAlert("Title", "Delayed for two seconds", "Okay");

    }
    catch (Exception ex)
    {

    }
}

async and await keys are important, suppose if you working on multithread environment.


text:
Q: Is there any good reason to use false in JSP tags? Is there any good reason to disallow scriptlet or EL expression to be inserted as attribute value?
Let's say we have tag:
<tag>
    <name>mytag</name>
    <tag-class>org.apache.beehive.netui.tags.tree.Tree</tag-class>
    <attribute>
        <name>attr</name>
        <required>false</required>
        <rtexprvalue>false</rtexprvalue>
        <type>boolean</type>
    </attribute>
</tag>

What could be a good reason for dissallowing the below?
<my:mytag attr="${setting}" />

A: There might potentially be attributes (eg. id to refer to the tag itself) that it's not suitable to set at run-time. You could probably come up with a scenario where you really wanted ${} to mean plain text, or where any EL content was evaluated manually in some kind of custom context.
But I think the real reason for the switch is backwards compatibility. Custom tags predate JSP's built-in support for the EL; changing the definition underneath a taglib so that ${} now has a special meaning is likely to break existing templates' use of that tag. Safer to default to rtexprvalue-false for back-compat and let new taglibs for JSP 2.0 specify they want the new behaviour.
[yes. what Thilo said. :-)]

A: I'd say it is mostly a backwards-compatibility measure, just like the ability to turn off EL completely for a given JSP.
Maybe the tag library existed before EL, and uses the special syntax ${} for its own purposes. Maybe the attribute value frequently takes values that include a literal ${}.
Without such a setting, existing code (in the tag library or the JSP) would need to be modified in order to still work after upgrading to the latest version of the Servlet spec.


text:
Q: Toggle property of an element inside an array VueJS? I have a text field in which you can input the field and on Click it adds a value to an array which renders the chips. Now each chips has a value property and a toggle property. By Default every new chip has toggle set to false. Now i can add as well as delete chips. The chips are deleted by using the deleteChips method. What i am trying to do is when there is only one chip left, the chip's toggle value should change dynamically to false or true depending on whatever it was at the time. So basically toggle = !toggle.
I have tried using the array.length but wasn't able to get it working.
Here is a sample pen
Here is the sample code:-

new Vue({
  el: "#app",
  data() {
    return {
      inputValue: "",
      inputArray: [],
      selectedChip: ""
    };
  },
  methods: {
    createChips() {
      this.inputArray.unshift({
        value: this.inputValue,
        toggle: false
      });
      this.inputValue = "";
    },
    deleteChips(chip) {
      let index = this.inputArray.filter((el) => el.chip === chip);
      this.inputArray.splice(index, 1);
    },
    chipSelection(item) {
      this.selectedChip = item;
    },
    toggleChip(item) {
      item.toggle = true;
    }
  }
});

<link href="https://cdn.jsdelivr.net/npm/vuetify@1.5.14/dist/vuetify.min.css" rel="stylesheet" />

  <v-app id="inspire">
    <v-container>
      <v-layout justify-center>
        <v-flex xs6>
          <v-text-field v-model="inputValue"></v-text-field>
          <v-btn @click="createChips">Click Me</v-btn>

 0">

              <v-chip :key="chip.value" close @click="chipSelection(chip.value)" @input=deleteChips(chip)>
                <v-avatar>
                  <v-icon @click="toggleChip(chip.value)">
                    account_circle
                  </v-icon>
                </v-avatar>
                {{chip.value}}
              </v-chip>

        </v-flex>
      </v-layout>
    </v-container>
  </v-app>

Any help will be appreciated. Thank you.

A: tbh, I can't really follow your intent, but based on the comments, perhaps you want to watch the inputArray and execute code based on changes to its length.
watch: {
    inputArray(newValue, oldValue) {
        if ((newValue.length !== oldValue.length) && (newValue.length === 1)) {
            this.inputArray[0].toggle = !this.inputArray[0].toggle;
        }
    }
}


text:
Q: When you resize a Hashmap do you keep deleted items if you're doing linear probing I understand that you keep the items and just mark them as deleted when they are removed in a HashMap using linear probing. However, when you resize the HashMap do you also add the deleted Items?

A: If you're using that kind of linear probing in a resizable hash table, you should make a few changes to the usual resizing rules.
Remember that the objectives are:

*

*Maintain expected amortized O(1) cost per operation

*Never have less than a quarter (for example) of your table slots used

*Never have more than half (for example) of your table slots used

So, when the table fills up (1/2 slots full in this example), you resize, and:

*

*The size of the new table should be 4N, where N is the number of non-deleted items in the table.

*Only copy over the non-deleted items.  This will leave exactly 1/4 of your slots full.

A resize with N non-deleted items takes O(N) time, and after each resize it takes at least N operations to get to the next one, which provides the O(1) amortized expected time per operation that we need.
If your implementation requires a power-of-two or prime-numbered table size, then it's OK if you pick the closest one to 4N, or the next bigger one.

A: There's a trick that makes resizing a HashMap easy -- don't resize it.  Instead, have your resize() method do this:

*

*Create a second HashMap, initialized with a larger internal array than the current one (twice is large is good)

*Iterate over the contents of your current HashMap, inserting each key-value pair from your current HashMap into the newly created HashMap using your HashMap's regular put(key,value) method (or whatever you call it).  (Since the internal array of your newly created HashMap is significantly larger than your current one, this is guaranteed to fit without requiring any further resizes)

*Swap the contents of your current HashMap and the newer/larger HashMap (if you've allocated the contents of the HashMap as a separate heap object, this can be as easy as a single pointer-swap)

*That's it; now your original HashMap is resized larger, and you didn't have to write any additional resizing-logic to do it, because you re-used the logic you had already implemented.  The second HashMap (which now contains the older/smaller internal array) can now be discarded.


text:
Q: Uninitialized register variable warning I was working with a old codebase where I encountered few line of code which was causing lot of repeated warnings during compilation.
#define EXAMPLE(_ptr) \
{                               \
    register uintptr_t      *__sp __asm__("sp");        \
    (_ptr[0]) = (uintptr_t) __sp;                       \
    asm volatile("sw $a0,%0" : "=m" (_ptr[1])); \
    //SOME OTHER CODE HERE
}

the warning was:
warning: '__sp' may be used uninitialized in this function

Can anyone help me in understanding what is happening in this code block and how to remove this warning.


text:
Q: Find maxima for a negative parabolic equation I have the following negative quadratic equation

-0.03402645959398278x^{2}+156.003469x-178794.025

I want to know if there is a straight way (using numpy/scipy libraries or any other) to get the value of x when the slope of the derivative is zero (the maxima). I'm aware I could:

*

*change the sign of the equation and apply the scipy.optimize.minima method or

*using the derivative of the equation so I can get the value when the slope is zero

For instance:
from scipy.optimize import minimize

quad_eq = np.poly1d([-0.03402645959398278, 156.003469, -178794.025])

############SCIPY####################
neg_quad_eq = np.poly1d(np.negative(quad_eq))
fit = minimize(neg_quad_eq, x0=15)
slope_zero_neg = fit.x[0]
maxima = np.polyval(quad_eq, slope_zero_neg)
print(maxima)

##################numpy######################
import numpy as np

first_dev = np.polyder(quad_eq)
slope_zero = first_dev.r
maxima = np.polyval(quad_eq, slope_zero)
print(maxima)

Is there any straight way to get the same result?
print(maxima)

A: You don't need all that code... The first derivative of a x^2 + b x + c is 2a x + b, so solving 2a x + b = 0 for x yields x = -b / (2a) that is actually the maximum you are searching for
import numpy as np
import matplotlib.pyplot as plt

def func(x, a=-0.03402645959398278, b=156.003469, c=-178794.025):
    result = a * x**2 + b * x + c
    return result

def func_max(a=-0.03402645959398278, b=156.003469, c=-178794.025):
    maximum_x = -b / (2 * a)
    maximum_y = a * maximum_x**2 + b * maximum_x + c
    return maximum_x, maximum_y

x = np.linspace(-50000, 50000, 100)

y = func(x)
mx, my = func_max()

print('maximum:', mx, my)

maximum: 2292.384674478263 15.955750522436574

and verify
plt.plot(x, y)
plt.axvline(mx, color='r')
plt.axhline(my, color='r')


text:
Q: Rewrite Rules, Query Vars and Pagination Putt a lot of research in and did a lot of testing for this issue and I don't think I am going to solve this by myself at this point.
What we have:
A page with a permalink with one shortcode.
That shortcode is resolved via plugin, which provides different views / outputs relatively by the url-path:
/dashboard/admin <-- the WP page permalink
/dashboard/admin/trainers/list <-- path without own permalink
This all works fine with this rule:
dashboard/admin/(.*)

Now to the issue:
/dashboard/admin/trainers/list/page/2
This url doesn't trigger the pagination to go to page 2, the paged var is empty (null).
The rule:
dashboard/trainers/(.+)/page/([0-9]{1,})/?$

This rule matches perfectly with preg_match testers and the test plugin "Rewrite Rules Inspector":

The add_rewrite_rule part:
    $rule = $path.'/(.+)/page/([0-9]{1,})/?$';
    add_rewrite_rule( $rule, 'index.php?pagename=$matches[1]&dashview=$matches[2]&paged=$matches[3]','top');
    $this->flush($rule);
    $rule = $path.'/(.*)';
    add_rewrite_rule( $rule, 'index.php?pagename='.$path.'&dashview=$matches[1]','top');
    $this->flush($rule);

( $path is just "dashboard/admin" )
My rule for paged pages gets overridden by the second rule. How can I prevent that?
Debug I did:
Using a redirect_canonical filter callback, and returning the requested URL with "?paged=2" works, and will get me to page 2 of the list.


text:
Q: Push git changes to a shared network drive, data on remote repository not visible I do have a local repository on my local drive and a remote repository on my network drive.
Everything is working, i can push data to the remote repository (bare repository) and my colleague is able to pull my data from the remote repository on the shared network drive. There is just one mystery. I do not see the data on the remote repository on the network drive? Is the data in a different form in the objects folder?
i expected if i push sth to the remote repository on the network drive it will appear (data ist visible) on the remote repository.


text:
Q: generating email address images or something which can't be easily scraped I'm looking for a better Text-to-image solution for my Rails project to replace my current method which is generating a png using ImageMagick every time a new record is created or updated.
I want to prevent a mass scraping of data and abuse of email addresses provided.  I'm wondering if there is an API to generate the text or use of javascript, or SVG, etc. Anything short of Flash.
I'm looking for a better solution than my current method:
  def create_new_email_image

    if email_changed?

      path_to_images = '/images/emails'

      puts "Connecting to AWS..."
      config = YAML.load(File.open("#{RAILS_ROOT}/config/s3_credentials.yml"))[RAILS_ENV]
      AWS::S3::Base.establish_connection!(
        :access_key_id     => config['access_key_id'],
        :secret_access_key => config['secret_access_key']
      )

      puts "Finding S3 bucket..."
      begin
        bucket = AWS::S3::Bucket.find config['bucket_name']
      rescue AWS::S3::NoSuchBucket
        AWS::S3::Bucket.create config['bucket_name']
        bucket = AWS::S3::Bucket.find config['bucket_name']
      end

      images_path = "#{RAILS_ROOT}/tmp/"
      file_name = "#{id}.png"
      #file_name = "5056.png"
      file_path = images_path + "/"+ file_name

      File.delete file_path if File.exists? file_path

      img = Magick::Image.new(400, 22) { self.background_color = 'transparent' }
      img.format = 'PNG'

      text = Magick::Draw.new
      text.annotate(img, 0, 0, 1, 0, "#{email}") {
          self.gravity = Magick::WestGravity
          self.pointsize = 18
          self.fill = '#000000'
          self.kerning = -1
          self.font_weight = Magick::BoldWeight
          }

      img.write file_path

      if AWS::S3::S3Object.exists? file_name, bucket.name + path_to_images
        puts "file exists (deleting)"
        AWS::S3::S3Object.delete file_name, bucket.name + path_to_images, :force => true
      end

      AWS::S3::S3Object.store file_name,
         File.open(file_path),
         bucket.name + path_to_images,
         :content_type => 'image/png',
         :access => :public_read,
         :reload => true

      `rm #{file_path}`
    end
  end

A: Rails provides a mail_to helper.
mail_to "me@domain.com"
# => me@domain.com

mail_to "me@domain.com", "My email", :encode => "javascript"
# =>

mail_to "me@domain.com", "My email", :encode => "hex"
# => My email

mail_to "me@domain.com", nil, :replace_at => "_at_", :replace_dot => "_dot_", :class => "email"
# => me_at_domain_dot_com

mail_to "me@domain.com", "My email", :cc => "ccaddress@domain.com",
         :subject => "This is an example email"
# => My email

The :encode => "hex" or :encode => "javascript" options are what you are looking for.

A: I've had the same problem. Here is my solution:
def text_to_image(text,options={})
    return if text.blank?
    filename=get_text_file_path(text)
    unless File.exists?(filename)
      gc = Magick::Draw.new
      gc.fill = options[:color] unless options[:color].blank?
      gc.pointsize options[:size] unless options[:size].blank?
      gc.font=options[:font] unless options[:font].blank?
      gc.gravity = Magick::CenterGravity
      gc.text(0,0, text)
      metrics=gc.get_type_metrics(text)
      image = Magick::Image.new(metrics.width, metrics.height){
        self.background_color = 'transparent'
        }
      gc.draw(image)
      image.write(filename)
    end
  end

I use after_save callback to update graphic cache of email attribute.


text:
Q: Wordpress: Add the_permalink to a link inside of a function I am very new to PHP and really don't know where to start when it comes to writing it myself.
I have found this function for Wordpress which I am using:
function excerpt($limit) {
  $excerpt = explode(' ', get_the_excerpt(), $limit);
  if (count($excerpt)>=$limit) {
    array_pop($excerpt);
    $excerpt = implode(" ",$excerpt).'<a href="<?php the_permalink(); ?>">Read In Full';
  } else {
    $excerpt = implode(" ",$excerpt);
  }
  $excerpt = preg_replace('`\[[^\]]*\]`','',$excerpt);
  return $excerpt;
}

function content($limit) {
  $content = explode(' ', get_the_content(), $limit);
  if (count($content)>=$limit) {
    array_pop($content);
    $content = implode(" ",$content).'[...]';
  } else {
    $content = implode(" ",$content);
  }
  $content = preg_replace('/\[.+\]/','', $content);
  $content = apply_filters('the_content', $content);
  $content = str_replace(']]>', ']]>', $content);
  return $content;

}
In the above code, I have placed
"<?php the_permalink(); ?>"

into the href. It is just showing up as a string of words instead of creating a call to the posts link.
Anyone help me out??
Thanks!

A: I was having this exact problem, and found that sbrajesh was right — we need to use get_permalink().  But it only works if you append the php properly — when I used <?php ?> it didn't process the php at all (just spit out the html).
Here is the working version I ended up with: echo implode(' ', $words)."read more"; }

A: Try it like this:
$excerpt = implode(" ",$excerpt).'<a href="'<?php the_permalink(); ?>'">Read In Full';

You forgot to put ' before and after php. Hope this helps you.
Later edit:
I guess your whole code is write in php. Then I think you should try:
$excerpt = implode(" ",$excerpt).'Read In Full';

Hope this time will work.


text:
Q: Can't get left aligned triangle to be right aligned triangle i'm trying to make a right aligned triangle. I am able to make a left aligned triangle easily, but can't get the number of spaces to decrease with each additional row.
output should be:
       #
      ##
     ###
    ####
   #####

let levels = 8;
let hash = '';

for (let i = 1; i <= levels; i++) {
    hash += '#';
    console.log(hash)
}

A: Instead of reusing the same string, consider generating each row with repeat() and padStart():

function rightAlignedTriangle (levels) {
  for (let i = 1; i <= levels; i++) {
    const row = '#'.repeat(i).padStart(levels)
    console.log(row)
  }
}

rightAlignedTriangle(5)

To implement this using a nested loop instead of string methods, you can manually implement the above two methods as an inner loop on a variable string declared in the outer loop:

function rightAlignedTriangle (levels) {
  for (let i = 1; i <= levels; i++) {
    let row = ''

    for (let j = 0; j < levels; j++) {
      if (j < i) { row += '#' } // repeat(i)
      else { row = ' ' + row } // padStart(levels)
    }

    console.log(row)
  }
}

rightAlignedTriangle(5)


text:
Q: Google adsense awlays displays blank I create an ad unit with my google adsense account,and add the sync code piece into my page:
<script type="text/javascript">
        google_ad_client = "ca-pub-2512354990153831";
        google_ad_slot = "4650942105";
        google_ad_width = 728;
        google_ad_height = 90;
    </script>
<!-- index_top_ad_01 -->
<script type="text/javascript" src="//pagead2.googlesyndication.com/pagead/show_ads.js"></script>

But it always return empty "",you can view the site。
Can someone help me?


text:
Q: SMTP client in C blocks on SSL_read I have been working on a small project which is a SMTP client written in C with SSL.
I am trying to get it working with GMail. I have enabled the allow unsecure apps in GMail settings.
When I try to authenticate using the OpenSSL CLI with the command openssl s_client -connect smtp.gmail.com:465 it works just fine I get proper responses for HELO and EHLO commands (see the output below)
220 smtp.gmail.com ESMTP o3-v6sm18136158pgv.53 - gsmtp
HELO smtp.gmail.com
250 smtp.gmail.com at your service
AUTH LOGIN
334 VXNlcm5hbWU6

But once I run this with my C client it hangs on SSL_read after I send HELO smtp.gmail.com and it does not even give me any output for HELO smtp.gmail.com.
But if I send just HELO I get a proper response from the server saying that empty HELO isn't allowed
MAIN
int main(int argc, char **argv) {
    setup("smtp.gmail.com", 465);
    printf("[INFO] -- %s\n", recv_secure());
    send_secure("HELO smtp.gmail.com\r\n");
    printf("[INFO] -- %s\n", recv_secure());
    send_secure("AUTH LOGIN\r\n");
    printf("[INFO] -- %s\n", recv_secure());
    close_secure();
    return 0;
}

setup
int setup(char *hostname, int port) {
    SSL_CTX *ctx = init();

    struct hostent *host;
    struct sockaddr_in addr;
    int sock_fd;

    if((host = gethostbyname(hostname)) == NULL) {
        fprintf(stderr, "[ERROR] Unable to get host by name: %s", hostname);
        return -1;
    }

    sock_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
    bzero(&addr, sizeof(addr));

    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = *(long*)host->h_addr_list[0];

    if(connect(sock_fd, (struct sockaddr*) &addr, sizeof(addr)) != 0) {
        close(sock_fd);
        fprintf(stderr, "[ERROR] Unable to connect to remote server: %s\n", hostname);
        return -1;
    }

    ssl = SSL_new(ctx);
    SSL_set_fd(ssl, sock_fd);

    if(SSL_connect(ssl) == -1) {
        fprintf(stderr, "[ERROR] Unable to establish secure connection\n");
        close(sock_fd);
        return -1;
    }
    return sock_fd;
}

send_secure
void send_secure(const char* buffer){
    SSL_write(ssl, buffer, sizeof(buffer));
}

recv_secure
char* recv_secure() {

    int bytes = SSL_read(ssl, rbuffer, SIZE);
    rbuffer[bytes] = 0;
    fprintf(stderr, "[DEBUG] -- Received: %s\n", rbuffer);
    return rbuffer;
}

I ran ltrace with it and it seems to be blocked at SSL_read but SSL_pending return value is 0
I cannot seem to understand what am I missing here.

A:
void send_secure(const char* buffer){
  SSL_write(ssl, mbuffer, sizeof(mbuffer));
}

Assuming that mbuffer is a typo and buffer was meant instead, this will write either 8 or 4 bytes (the size of a pointer, depending on your platform), not the length of the buffer as you probably expected (which will be wrong, too since sizeof, when applied to a literal string, also includes the terminating null byte -- which will NOT be accepted by the smtp server).
Changing sizeof to strlen may let you proceed further, but your code has a lot of problems, for instance:

int bytes = SSL_read(ssl, rbuffer, SIZE);
rbuffer[bytes] = 0;

If SSL_read returns -1, this will (in the best case ;-)) crash your program.


text:
Q: Como Validar tiempo de vida de login Android Tengo ya terminada mi app en android studio, solo que ahora necesito hacer como un tipo de validación, donde mi sesión en un determinando tiempo expire y mande un alert y me regrese a la ventana de mi Login.
Aclaro este mensaje de session expirada me lo mandan desde un webservices.
Les dejo código de mi Login.
public class Login extends AppCompatActivity {

    //public Button login;
    ProgressDialog dialog;
    private EditText userNameET , passWordET;
    String editTextUsername;
    String editTextPassword;
    private static final int MY_PERMISSIONS_REQUEST_FINE_LOCATION = 1;
    private static final String TAG = "mx.com.oncontrol.oncontrol";
    ArrayList<Empresa> EmpresaArraylist = new ArrayList<Empresa>();
    final Context context = this;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setTitle("Iniciar Sesion");
        actionBar.setSubtitle("ONControl");

        TextView textViewversionName = (TextView) findViewById(R.id.VersionName);

        try {
            PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            textViewversionName.setText("V"+"."+packageInfo.versionName);

        }
        catch (PackageManager.NameNotFoundException e) {

        }

        int permission = ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION);

        if (permission != PackageManager.PERMISSION_GRANTED) {

            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)) {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("Permiso Requerido");
                builder.setMessage("Permiso de Acceso a Localizacion");
                builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int id) {
                        makeRequest();
                    }
                });

                AlertDialog dialog = builder.create();
                dialog.show();
            } else {
                makeRequest();
            }
        }

        userNameET = (EditText) findViewById(R.id.editText1);
        passWordET = (EditText) findViewById(R.id.editText2);
        //Display Text control
        //final TextView statusTV = (TextView) findViewById(R.id.tv_result);
        //Button to trigger web service invocation
        Button login = (Button) findViewById(R.id.button1);
        //Display progress bar until web service invocation completes
        //Button Click Listener
        login.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                if (userNameET.getText().length() != 0 && userNameET.getText().toString().trim() != "") {
                    if (passWordET.getText().length() != 0 && passWordET.getText().toString().trim() != "") {
                        editTextUsername = userNameET.getText().toString().trim();
                        editTextPassword = passWordET.getText().toString().trim();
                        //statusTV.setText("");
                        //Create instance for AsyncCallWS
                        SharedPreferences settings = getSharedPreferences("ONC_Settings", 0);
                        AsyncCallWS_Login task = new AsyncCallWS_Login(settings.getString("ONControlWSURL", "").toString(),
                                                                           settings.getString("ONControlToken", "").toString(),
                                                                           settings.getInt("ONControlEmpresa", 0),
                                                                           settings.getString("ONControlUsuario", "").toString());
                        //Call execute
                        task.execute();
                    }
                    //If Password text control is empty
                    else {
                        Toast.makeText(getApplicationContext(),"Ingresa Password",Toast.LENGTH_SHORT).show();
                    }
                    //If Username text control is empty
                } else {
                    Toast.makeText(getApplicationContext(),"Ingresa Usuario",Toast.LENGTH_SHORT).show();
                }

            }

        });

        SharedPreferences settings = getSharedPreferences("ONC_Settings", 0);
        AsyncEmpresa task = new AsyncEmpresa(settings.getString("ONControlWSURL", "").toString(),
                                             settings.getInt("ONControlEmpresa", 0),
                                             settings.getString("ONControlUsuario", "").toString());
        //Call execute
        task.execute();
    }

    protected void makeRequest() {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                MY_PERMISSIONS_REQUEST_FINE_LOCATION);
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @SuppressLint("LongLogTag")
    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_splash, menu);
        //tomar de datos de nuestra preferencia para mostrarlo en el edittex cuando reinicie app
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            // action with ID action_refresh was selected
            case R.id.action_settings:
                GrabarUrl();
                break;

        }
        return super.onOptionsItemSelected(item);
    }

    private class AsyncEmpresa extends AsyncTask<String, ArrayList, ArrayList>
    {
        private String ONControlWSURL;
        private int ONControlZonaCliente;
        private String ONControlToken;
        private int ONControlEmpresa;
        private String ONControlUsuario;

        public AsyncEmpresa(String ONControlWSURL,
                            int ONControlEmpresa,
                            String ONControlUsuario)
        {
            this.ONControlUsuario = ONControlUsuario;
            this.ONControlWSURL = ONControlWSURL;
            this.ONControlEmpresa = ONControlEmpresa;
        }
        @Override
        protected ArrayList doInBackground(String... params) {
            EmpresaArraylist = new ArrayList<Empresa>();
            webService O_WS = new webService(ONControlWSURL,
                                             ONControlZonaCliente,
                                             ONControlToken,
                                             ONControlEmpresa,
                                             ONControlUsuario);
            EmpresaArraylist=O_WS.Empresa();
            return null;
        }

        @Override
        protected void onPostExecute(ArrayList arrayList) {
            super.onPostExecute(arrayList);

            if(EmpresaArraylist.size()!=0){

               Spinner spiner = (Spinner)findViewById(R.id.spBussinessType);
                ArrayAdapter<Empresa> adapter = new ArrayAdapter<Empresa>(context, android.R.layout.simple_spinner_dropdown_item, EmpresaArraylist);
                spiner.setAdapter(adapter);
                spiner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        SharedPreferences settings = getSharedPreferences("ONC_Settings", 0);
                        SharedPreferences.Editor editor = settings.edit();
                        editor.putInt("ONControlEmpresa",EmpresaArraylist.get(position).getId());
                        editor.commit();

                    }
                    @Override
                    public void onNothingSelected(AdapterView<?> parent){}
                });

            }else{
                Toast.makeText(getApplicationContext(),"Ingresa Direccion de Servidor" ,Toast.LENGTH_SHORT).show();
            }
        }
    }

    private class AsyncCallWS_Login extends AsyncTask<String,String,webService.STR_Resultado> {

        private String ONControlWSURL;
        private int ONControlZonaCliente;
        private String ONControlToken;
        private int ONControlEmpresa;
        private String ONControlUsuario;

        public AsyncCallWS_Login(String ONControlWSURL,
                                 String ONControlToken,
                                 int ONControlEmpresa,
                                 String ONControlUsuario)
        {
            this.ONControlUsuario = ONControlUsuario;
            this.ONControlWSURL = ONControlWSURL;
            this.ONControlToken = ONControlToken;
            this.ONControlEmpresa = ONControlEmpresa;
        }

        @Override
        //Make Progress Bar visible
        protected void onPreExecute() {
           dialog=new ProgressDialog(Login.this);
            dialog.setIndeterminate(false);
            dialog.setMessage("Loding...");
            dialog.setCancelable(false);
            dialog.show();
        }

        @Override
        protected webService.STR_Resultado doInBackground(String... params) {
            webService.STR_Resultado O_ResultadoLogin = null;
            webService O_WS = new webService(ONControlWSURL,
                                             ONControlZonaCliente,
                                             ONControlToken,
                                             ONControlEmpresa,
                                             ONControlUsuario);

            O_ResultadoLogin = O_WS.Login(editTextUsername,
                                          editTextPassword);
            return O_ResultadoLogin;
        }

        @Override
        //Once WebService returns response
        protected void onPostExecute(webService.STR_Resultado Result) {
            super.onPostExecute(Result);
            SharedPreferences settings = getSharedPreferences("ONC_Settings", 0);
            SharedPreferences.Editor editor = settings.edit();
            editor.putString("ONControlToken",Result.Token);
            editor.commit();

            settings = getSharedPreferences("ONC_Settings", 0);
            SharedPreferences.Editor editorUsuario = settings.edit();
            editorUsuario.putString("ONControlUsuario",Result.UserName);
            editorUsuario.commit();

            if(Result.Valido == true) {

                dialog.dismiss();
                Toast.makeText(getApplicationContext(), "Gracias por Iniciar Sesion", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(Login.this, mx.com.oncontrol.oncontrol.Menu.class);
                startActivity(intent);
                finish();

            }else {

                dialog.dismiss();
                Toast.makeText(getApplicationContext(),"Datos Incorrectos," +
                        "Favor de Ingresar de Nuevo tus Datos",Toast.LENGTH_LONG).show();
            }
        }
    }

    public void GrabarUrl(){
        try {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Ingresa la URL / IP  del Servidor");

//Creamos el input text y asignamos el tipo de EditText que     necesitamos
            final EditText input = new EditText(this);
            input.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
            builder.setView(input);

            SharedPreferences settings = getSharedPreferences("ONC_Settings", 0);
            input.setText(settings.getString("ONControlWSURL",""));

// Agregamos los botones de Guardar/Cancelar
            builder.setPositiveButton("Guardar", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    //Creo Mi sharepreferens
                    SharedPreferences settings = getSharedPreferences("ONC_Settings", 0);
                    SharedPreferences.Editor editor = settings.edit();
                    editor.putString("ONControlWSURL",input.getText().toString());
                    editor.commit();
                    Toast.makeText(getApplicationContext(),"Datos Guardados",Toast.LENGTH_SHORT).show();

                    AsyncEmpresa task = new AsyncEmpresa(settings.getString("ONControlWSURL", "").toString(),
                            settings.getInt("ONControlEmpresa", 0),
                            settings.getString("ONControlUsuario", "").toString());
                    //Call execute
                    task.execute();

                }
            });
            builder.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

            builder.show();
        }catch(Exception ex){
            Log.e("ERROR",ex.getMessage());
        }
    }

}


text:
Q: How do I push changes to my remote repository without entering my password everytime? Everytime I push changes from my local directory to a remote repo, I am prompted to enter my username and password.
Is there a way to ignore typing the credentials for every git push in a particular session?

A: You can cache your credentials so you won't be prompted to enter them every time you push: git config --global credential.helper wincred

Note: Above command is for Windows.

Other operating systems and source here.


text:
Q: can we access the managed code with out pointer object? i have created some application in managed c++.when i try to instantiates it shows error as
cannot convert from obj to *obj. when i instantiates as pointer obj it shows no error.
so. is there any way to access such class without creating pointer object

A: The question says you're using Managed C++, and the tags say you're using C++/CLI (available in VS 2005 or later). You'll probably have a less confusing time with C++/CLI.
If that's what you're using, then there are two ways to "translate" from C#. Suppose you have some C#:
// Construct
MyClass c = new MyClass();

// Call some method
c.MyMethod();

Console.Writeline(c); // will call ToString on MyClass

// Finished with it
c.Dispose();

You can write this in C++/CLI like this:
MyClass ^c = gcnew MyClass;

// Call some method
c->MyMethod();

Console.Writeline(c); // will call ToString on MyClass

// Finished with it
c->Dispose();

The variable c is called a "handle", not a pointer, declared with ^ instead of *. Also we have to use gcnew instead of new. This is the same thing as a reference variable in C#, and is analogous (but not identical) to a pointer in C++, so we use -> to access members.
Or you can write it like this:
// Create with local scope
MyClass c;

// Call some method
c.MyMethod();

Console.Writeline(%c); // will call ToString on MyClass (note the %)

First thing to note: we declare it in the style of a local C++ variable. There is no need to explicitly gcnew the object. Secondly, we treat the object as if it was a local variable (or a C++ reference to such a variable). So we use . instead of ->. Thirdly, we can "convert" this local object into a handle, by prefixing it with %, which acts like the .NET equivalent of & that we use with ordinary pointers. It means "take the address of" or "give me a handle to" an object. Finally, we don't have to call Dispose on the object. The compiler does that for us at the end of the scope in which we declared it, as the Dispose method is the mechanism by which destructors are implemented in C++/CLI.

A: You could create it on the stack.
MyObject foo;
foo.bar();   // accessing bar method on object foo

Maybe the syntax you are looking for is this:
MyObject *foo = new MyObject;
foo->bar;


text:
Q: JVM crashed with a fatal error. Problematic frame is C [libc.so.6+0x10b294] __clock_gettime+0x24 I am writing a web app, which has a feature that writes data to an Excel file (using Apache POI tools) and gets downloaded by customers. The app runs pretty well on my Linux VM, but crashes on k8s each time a download request gets called.
Below is part of the JVM crash log:
#
# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0x00007f808e739294, pid=1, tid=0x00007f7fe52a4700
#
# JRE version: Java(TM) SE Runtime Environment (8.0_241-b07) (build 1.8.0_241-b07)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.241-b07 mixed mode linux-amd64 compressed oops)
# Problematic frame:
# C  [libc.so.6+0x10b294]  __clock_gettime+0x24
#
# Core dump written. Default location: /apply/integrator/core or core.1
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#
---------------  T H R E A D  ---------------

Current thread (0x00007f8088aa4800):  JavaThread "http-nio-8080-exec-6" daemon [_thread_in_native, id=74, stack(0x00007f7fe51a4000,0x00007f7fe52a5000)]

siginfo: si_signo: 11 (SIGSEGV), si_code: 128 (SI_KERNEL), si_addr: 0x0000000000000000
.......
.......
Stack: [0x00007f7fe51a4000,0x00007f7fe52a5000],  sp=0x00007f7fe529dc20,  free space=999k
Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
C  [libc.so.6+0x10b294]  __clock_gettime+0x24
C  [libc.so.6+0x86a63]
[error occurred during error reporting (printing native stack), id 0xb]

Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)
j  sun.font.FontConfigManager.getFontConfig(Ljava/lang/String;Lsun/font/FontConfigManager$FontConfigInfo;[Lsun/font/FontConfigManager$FcCompFont;Z)V+0
j  sun.font.FontConfigManager.initFontConfigFonts(Z)V+178
j  sun.font.FontConfigManager.loadFontConfig()[Lsun/font/FontConfigManager$FcCompFont;+2
j  sun.font.FcFontConfiguration.init()Z+39
j  sun.font.FcFontConfiguration.<init>(Lsun/font/SunFontManager;)V+16
j  sun.awt.X11FontManager.createFontConfiguration()Lsun/awt/FontConfiguration;+53
j  sun.font.SunFontManager$2.run()Ljava/lang/Object;+205
v  ~StubRoutines::call_stub
J 1599  java.security.AccessController.doPrivileged(Ljava/security/PrivilegedAction;)Ljava/lang/Object; (0 bytes) @ 0x00007f80794d50cf [0x00007f80794d5080+0x4f]
j  sun.font.SunFontManager.<init>()V+222
j  sun.awt.FcFontManager.<init>()V+1
j  sun.awt.X11FontManager.<init>()V+1
v  ~StubRoutines::call_stub
J 1975  sun.reflect.NativeConstructorAccessorImpl.newInstance0(Ljava/lang/reflect/Constructor;[Ljava/lang/Object;)Ljava/lang/Object; (0 bytes) @ 0x00007f8079603fa3 [0x00007f8079603f40+0x63]
J 1974 C1 sun.reflect.NativeConstructorAccessorImpl.newInstance([Ljava/lang/Object;)Ljava/lang/Object; (89 bytes) @ 0x00007f807960af7c [0x00007f8079609f40+0x103c]
J 2102 C1 sun.reflect.DelegatingConstructorAccessorImpl.newInstance([Ljava/lang/Object;)Ljava/lang/Object; (9 bytes) @ 0x00007f8079671ac4 [0x00007f80796719c0+0x104]
j  java.lang.reflect.Constructor.newInstance([Ljava/lang/Object;)Ljava/lang/Object;+79
J 4231 C1 java.lang.Class.newInstance()Ljava/lang/Object; (155 bytes) @ 0x00007f80791bf8ec [0x00007f80791befe0+0x90c]
j  sun.font.FontManagerFactory$1.run()Ljava/lang/Object;+21
v  ~StubRoutines::call_stub
J 1599  java.security.AccessController.doPrivileged(Ljava/security/PrivilegedAction;)Ljava/lang/Object; (0 bytes) @ 0x00007f80794d50cf [0x00007f80794d5080+0x4f]
j  sun.font.FontManagerFactory.getInstance()Lsun/font/FontManager;+17
j  java.awt.Font.getFont2D()Lsun/font/Font2D;+0
j  java.awt.Font.canDisplayUpTo([CII)I+1
j  java.awt.font.TextLayout.singleFont([CIILjava/util/Map;)Ljava/awt/Font;+64
j  java.awt.font.TextLayout.<init>(Ljava/text/AttributedCharacterIterator;Ljava/awt/font/FontRenderContext;)V+170
j  org.apache.
.ss.util.SheetUtil.getDefaultCharWidth(Lorg/apache/poi/ss/usermodel/Workbook;)I+39
j  org.apache.poi.xssf.streaming.AutoSizeColumnTracker.<init>(Lorg/apache/poi/ss/usermodel/Sheet;)V+49
j  org.apache.poi.xssf.streaming.SXSSFSheet.<init>(Lorg/apache/poi/xssf/streaming/SXSSFWorkbook;Lorg/apache/poi/xssf/usermodel/XSSFSheet;)V+71
j  org.apache.poi.xssf.streaming.SXSSFWorkbook.createAndRegisterSXSSFSheet(Lorg/apache/poi/xssf/usermodel/XSSFSheet;)Lorg/apache/poi/xssf/streaming/SXSSFSheet;+6
j  org.apache.poi.xssf.streaming.SXSSFWorkbook.createSheet(Ljava/lang/String;)Lorg/apache/poi/xssf/streaming/SXSSFSheet;+9
j  org.apache.poi.xssf.streaming.SXSSFWorkbook.createSheet(Ljava/lang/String;)Lorg/apache/poi/ss/usermodel/Sheet;+2
.......
.......
---------------  S Y S T E M  ---------------

OS:NAME="Alpine Linux"
ID=alpine
VERSION_ID=3.13.5
PRETTY_NAME="Alpine Linux v3.13"
HOME_URL="https://alpinelinux.org/"
BUG_REPORT_URL="https://bugs.alpinelinux.org/"

uname:Linux 5.10.113-1.el7.x86_64 #1 SMP Thu Apr 28 00:44:36 UTC 2022 x86_64
libc:glibc 2.30 NPTL 2.30
rlimit: STACK 8192k, CORE infinity, NPROC infinity, NOFILE 1048576, AS infinity
load average:2.42 2.39 2.38

/proc/meminfo:
MemTotal:       65960156 kB
MemFree:        50173428 kB
MemAvailable:   56264880 kB
Buffers:          199864 kB
Cached:          6194120 kB
SwapCached:            0 kB
Active:          1624812 kB
Inactive:       12835352 kB
Active(anon):     136984 kB
Inactive(anon):  8153056 kB
Active(file):    1487828 kB
Inactive(file):  4682296 kB
Unevictable:           0 kB
Mlocked:               0 kB
SwapTotal:             0 kB
SwapFree:              0 kB
Dirty:               484 kB
Writeback:             0 kB
AnonPages:       7918388 kB
Mapped:           454332 kB
Shmem:            315468 kB
KReclaimable:     658012 kB
Slab:             928020 kB
SReclaimable:     658012 kB
SUnreclaim:       270008 kB
KernelStack:       39840 kB
PageTables:        36932 kB
NFS_Unstable:          0 kB
Bounce:                0 kB
WritebackTmp:          0 kB
CommitLimit:    32980076 kB
Committed_AS:   12516988 kB
VmallocTotal:   34359738367 kB
VmallocUsed:      162160 kB
VmallocChunk:          0 kB
Percpu:            71936 kB
HardwareCorrupted:     0 kB
AnonHugePages:   6258688 kB
ShmemHugePages:        0 kB
ShmemPmdMapped:        0 kB
FileHugePages:         0 kB
FilePmdMapped:         0 kB
HugePages_Total:       0
HugePages_Free:        0
HugePages_Rsvd:        0
HugePages_Surp:        0
Hugepagesize:       2048 kB
Hugetlb:               0 kB
DirectMap4k:      431996 kB
DirectMap2M:    66676736 kB

The key point appears to be:
# The crash happened outside the Java Virtual Machine in native code.
# Problematic frame:
# C  [libc.so.6+0x10b294]  __clock_gettime+0x24

...which is beyond my abilities to fix. How would I resolve this issue?


text:
Q: Regex preg_match_all between two tags and condition i'm trying to get the content between two tags with a condition.
So here is a example, i want to get all tr's but only the ones with /c in it.
example string:

 /a

 /b

 /c

 /d

using what i got so far i get all tr's
preg_match_all("/<tr.*<\/tr>/", $input_lines, $output_array);

what do i need to do to get this working?
thank you

A: preg_match_all("/([^<]*/c[^<]*)<\/td>/", $input_lines, $output_array);

in other words: Whenever the regex will encounter < without having found a /c - it will fail.
if other html tags could be inside the td, you need to replace [^<]* with .*?.
([^<]*/c[^<]*)<\/td>

Debuggex Demo
Note: using .*? can lead to unwanted, greedy results see this example:
(.*?/c.*?)<\/td>

Debuggex Demo


text:
Q: gnuplot palette for splot 3D surface of errors: symmetrical colors I am plotting a 3D surface (I have z values on a matrix 8x10 in a text file); The z values represent the error, so it goes e.g. from -20% to +10%. I would like to plot this with colors, in a symmetric way, meaning e.g. -10% needs to be the same red intensity as +10%. The value around 0% (very small errors) needs to be green (or also blue or whatever). So in this way the more intense the red is, the greater the error is (regardless if positive or negative).
I am plotting using:
# line styles
set style line 1 lc rgb '#B2182B' # red
set style line 2 lc rgb '#D6604D' # red-orange
set style line 3 lc rgb '#F4A582' #
set style line 4 lc rgb '#FDDBC7' # pale orange
set style line 5 lc rgb '#D1E5F0' # pale blue
set style line 6 lc rgb '#92C5DE' #
set style line 7 lc rgb '#4393C3' # medium blue
set style line 8 lc rgb '#2166AC' # dark blue
# palette
set palette defined ( 0 '#B2182B',\
                      1 '#D6604D',\
              2 '#F4A582',\
              3 '#FDDBC7',\
              4 '#D1E5F0',\
              5 '#92C5DE',\
              6 '#4393C3',\
              7 '#2166AC' )
set dgrid3d 30,30 gauss 1
splot 'file.csv' matrix using 1:2:3 with lines palette title 'Error (%)'

I took the line styles and palette from ColorBrewer RdBu.
I tried also centering around zero using stats and set cbrange but without success.

A: "without success" is not sufficient description to debug.  It should work to give the desired symmetric range as set cbrange [-foo : foo]".  The numeric values given in the set palette` command are not important so long as they are symmetric. Here is an example
set palette defined (-1 "dark-red", 0 "grey90", 1 "dark-red")
set cbrange [-15 : 15]
set xyplane at 0
splot besj0(y)*x*x with pm3d


text:
Q: Name of vector $(0,\dots,0,1,0,\dots,0)$ Is there a name generally accepted for vectors of the form $(0,\dots,0,1,0,\dots,0)\in \Bbb R^n$?
I understand this is one of the members of the orthonormal base of $\Bbb R^n$, but I believe that in the context I'm using. it this characterisation would be somewhat pedantic.
Also, is there a standard symbol to denote it? I was thinking of using $\mathbf{1}_{i^{*}}$, where $i^{*}$ stands for the position of the $1$.


text:
Q: AMP form response not working in google cache I created an AMP page for my website, all works fine on my desktop browser, tested and works fine on my mobile, if certain fields are empty or not valid, the submit-error correctly displays the error message, also, on successful submission it correctly displays the submit-success message.
When I submitted the page to Google to cache the amp page, I tested the form once again, this time it isn't displaying the error or success messages. But if the form submission is valid, it will send me an email but not display the success message.
Form html code:
<form action-xhr="posts/submit.php" method="POST" class="contactForm" target="_top">
    <fieldset>

            Select a product:(required)

            <select name="product">
                    <option selected="" disabled="">Select a Product</option>
                    <option value="product1">product 1</option>
                    <option value="product2">product 2</option>
            </select>

            Full Name:(required)
            <input type="text" name="fullname" value="" class="contactField" />

            Telephone: (required)
            <input type="text" name="telephone" value="" class="contactField" />

            Email: (required)

            <input type="text" name="email" value="" class="contactField" />

        <input type="hidden" name="ps" value="amp_Homepage">

            <input type="submit" class="buttonWrap button bg-teal-dark contactSubmitButton" value="Start my claim" />

    </fieldset>

        <template type="amp-mustache">
            Congratulations {{fullname}}! You have successfully submitted your claim. You can expect a telephone call from My Claim Solved just to confirm a few details.
        </template>

        <template type="amp-mustache">
            Oops! {{message}}
        </template>

</form>

PHP page:
<?php
$source_origin = trim($_REQUEST['__amp_source_origin']);//Security
if($source_origin != "https://example.com"){
echo "Not allowed origin";
return;
}
header('AMP-Access-Control-Allow-Source-Origin: https://example.com');
header('Content-Type: application/json; charset=UTF-8;');

$start = microtime(true);
$con=mysqli_connect("myip","myuser","mypass","mydb");

$Product = mysqli_real_escape_string($con, $_REQUEST['product']);
$FullName = mysqli_real_escape_string($con, $_REQUEST['fullname']);$FullName = ltrim($FullName);$FullNameMail = mysqli_real_escape_string($con, $_REQUEST['fullname']);
$Telephone = mysqli_real_escape_string($con, $_REQUEST['telephone']);
$Email = mysqli_real_escape_string($con, $_REQUEST['email']);
$Provider = mysqli_real_escape_string($con, $_REQUEST['provider']);
$PageSource = mysqli_real_escape_string($con, $_REQUEST['ps']);

if($Product != 'product1' && $Product != 'product2'){
    header('Status: 400', TRUE, 400);
    echo json_encode(array('message'=>'You must select a product.'));
}elseif(empty($FullName) || strlen($FullName)<3) {
    header('Status: 400', TRUE, 400);
    echo json_encode(array('message'=>'You must enter your full name.'));
}elseif (empty($Telephone) || strlen($Telephone)<9) {
    header('Status: 400', TRUE, 400);
    echo json_encode(array('message'=>'You must enter a valid telephone number.'));
}elseif (!filter_var($Email, FILTER_VALIDATE_EMAIL)) {
    header('Status: 400', TRUE, 400);
    echo json_encode(array('message'=>'You must enter a valid email address.'));
}else{

    // Send Email
    $To = "myemail@example.com";
    $Message = "bla bla";
    $Headers = "From: myemail@example.com";
    mail($To, 'subject bla', $Message, $Headers);

    echo json_encode(array("product"=>$Product,"fullname"=>$FullName,"telephone"=>$Telephone,"email"=>$IPAddress));
}

?>

A: just to let you know how it was fixed (thanks to ade for pointing me in the right direction), I amended the headers on the php page to the below:
header("access-control-allow-credentials:true");
header("access-control-allow-headers:Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token");
header("access-control-allow-methods:POST, GET, OPTIONS");
header("access-control-allow-origin:".$_SERVER['HTTP_ORIGIN']);
header("access-control-expose-headers:AMP-Access-Control-Allow-Source-Origin");
header("amp-access-control-allow-source-origin:https://".$_SERVER['HTTP_HOST']);
header("Content-Type: application/json");