text:
Q: Custom TeamCity plugin with a Build Feature that executes a long running process I am developing a custom TeamCity plugin that integrates with an enterprise deployment platform. It should deploy the binaries at the end of the build to some deployment platform by executing a command line command. Currently there is a class that extends the BuildFeature class on the server side to setup the details of artifacts to be deployed. On the agent side there is a class that extends AgentLifeCycleAdapter class, which overrides the beforeBuildFinish() method and executes a long running command line process. I am using SimpleCommandLineProcessRunner class to execute the external command line process:

final ExecResult result = SimpleCommandLineProcessRunner.runCommand(commandLine,
        null,
        new SimpleCommandLineProcessRunner.RunCommandEventsAdapter());

The process is being stopped after two minutes, which looks like some timeout:

[18:13:50]Running as atom_builder
  [18:13:50]Executing C:\TeamCity\buildAgent\work\db4107aa7e390a67\adeploy\adeploy.exe
   artifactVersion push
  C:\TeamCity\buildAgent\work\db4107aa7e390a67\agent\atom-agent-artifact-version.xml
  [18:13:50]Running at C:\TeamCity\buildAgent\work\db4107aa7e390a67\agent
  [18:15:22]2018-11-07 18:13:51 [Information]
  ["ArtifactPushService:PushArtifactAsync"] Calling method with parameters '"adeploy.exe" [18:15:22]Exit code: -1

What is the proper way to execute long running processes as part of the build when the build configuration has a custom Build Feature?

A: I found out the answer, so I will post it here, in case somebody else encounter the same problem.
Since we are talking about custom plugin, it's completely in the code of the agent -side of the plugin that executes the external process. As stated in the question, the external process is executed using SimpleCommandLineProcessRunner class and it passes an instance of RunCommandEventsAdapter class. The last one returns null in getOutputIdleSecondsTimeout() method. It means that SimpleCommandLineProcessRunner  will use default timeout of 90 seconds unless it's defined in teamcity.execution.timeout parameter.
So the solution is to define a LongRunningProcessRunCallback class that implements ProcessRunCallback interface. Put attention that getOutputIdleSecondsTimeout() returns a pretty long timeout.
public class LongRunningProcessRunCallback implements SimpleCommandLineProcessRunner.ProcessRunCallback {

    private static final int DEFAULT_TIMEOUT_SECONDS = 60 * 60 * 24;

    @Nullable
    @Override
    public Integer getMaxAcceptedOutputSize() {
        return null;
    }

    @Override
    public void onProcessStarted(@NotNull Process process) {

    }

    @Override
    public void onProcessFinished(@NotNull Process process) {

    }

    @Nullable
    @Override
    public Integer getOutputIdleSecondsTimeout() {
        return TeamCityProperties.getInteger("teamcity.execution.timeout", DEFAULT_TIMEOUT_SECONDS);
    }
}

And then pass it to SimpleCommandLieProcessRunner:
final ExecResult result = SimpleCommandLineProcessRunner.runCommand(commandLine,
                null,
                new LongRunningProcessRunCallback());


text:
Q: Canonical way to obtain CDI managed bean instance: BeanManager#getReference() vs Context#get() I figured that there are two general ways to obtain an auto-created CDI managed bean instance via BeanManager when having solely a Bean<T> to start with (which is created based on Class<T>):

*

*By BeanManager#getReference(), which is more often shown in
snippets:
Bean<TestBean> bean = (Bean<TestBean>) beanManager.resolve(beanManager.getBeans(TestBean.class));
TestBean testBean1 = (TestBean) beanManager.getReference(bean, bean.getBeanClass(), beanManager.createCreationalContext(bean));

*By Context#get(), which is less often shown in snippets:
Bean<TestBean> bean = (Bean<TestBean>) beanManager.resolve(beanManager.getBeans(TestBean.class));
TestBean testBean2 = beanManager.getContext(bean.getScope()).get(bean, beanManager.createCreationalContext(bean));

In effects, they do ultimately exactly the same thing: returning a proxied reference to the current CDI managed bean instance and auto-creates the bean instance if it doesn't already exist in the scope.
But they do it a bit differently: the BeanManager#getReference() always creates a whole new proxy instance, while the Context#get() reuses an existing proxy instance if already created before. This is evident when the above code is executed in an action method of an existing TestBean instance:
System.out.println(testBean1 == testBean2); // false
System.out.println(testBean1 == this); // false
System.out.println(testBean2 == this); // true

The javadoc of Context#get() is very explicit in this:

Return an existing instance of certain contextual type or create a new instance by calling Contextual.create(CreationalContext) and return the new instance.

while the javadoc of BeanManager#getReference() is not explicit enough on this:

Obtains a contextual reference for a certain bean and a certain bean type of the bean.

This got me confused. When do you use the one or the other? For the both ways you need a Bean<T> instance anyway, from which the bean class and bean scope is readily available which is required as additional argument. I can't imagine why they would need to be supplied externally in this specific case.
I can imagine that Context#get() is more memory efficient as it doesn't unnecessarily create another proxy instance referring the very same underlying bean instance, but just finds and reuses an existing proxy instance.
This puts me to the following question: when exactly is the BeanManager#getReference() more useful than Context#get()? It's more often shown in snippets and more often recommended as solution, but it only unnecessarily creates a new proxy even when one already exists.

A: beanManager#getReference gives you a new instance of a client proxy but the client proxy will forward method calls to the current contextual instance of a particular context.
Once you obtain the proxy and keep it and the method calls will be invoked on the current instance (e.g. current request).
It is also useful if the contextual instance is not serializable - the client proxy will be and will reconnect after you deserialize it.
BeanManager#getContext obtains the target instance without a client proxy. You may still see a Weld's proxy in the class name but that is an enhanced subclass that provides interception and decoration. If the bean is not intercepted nor decorated this will be a plain instance of the given bean.
Usually (1) is more suitable unless you have a special use-case where you need to access the target instance directly (e.g. to access its fields).
Or in other words
1) BeanManager#getReference will return a 'Contextual Reference', with a normal scoping proxy for the bean.
If a bean have with @SessionScoped as
@SessionScoped User user;

Then the contextual reference user  will 'point' to the respective User instance (the 'Contextual Instance') of the current session for each invocation.
Two different invocations to user.getName() from two different web browsers will give you different answers.
2) Context#get() will return a the internal 'Contextual Instance' without the normal scoping proxy.This is usually nothing a user should call himself. If you get the User user for "Bob" that way and store it in an @ApplicationScoped bean or in a static variable,
  then it will always remain to be the user "Bob" - even for web requests from other browsers! You will get a direct, non-proxied instance.

A: I have a Singleton that I was using the getReference() method to get the reference to.  Even though the singleton was already initialized, the proxy created through getReference() called the @PostConstruct each time getReference() was used.
@Startup
@ApplicationScoped
@Singleton

@PostConstruct
private void initialize() {}

By switching to the getContext().get() method, the unnecessary @PostConstruct proxy calls are no longer made.

A: This was very helpful when integrating CDI with javafx, the thing was that I needed a reference to the right scoped object cause and not the proxy of the dependent scope...
I used a producer method to get a javaFX Node that gets injected into the controler like so:
@Inject
@ApplicationScoped
@FXMLFile("javafx/wares.fxml")
@FXMLController(WaresController.class)
Parent wares;

but when using the BeanManager#getReference() the proxy I get back "eats" all the values that are set by the FXMLLoader, the  getContext.get() way solved it.
Thnx for this

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make sudo execute in current python virtual environment? I have a django website setup and configured in a python virtual environment (venv) on Ubuntu and all is working fine. Now in order to to run my server on port80 I need to use "sudo" which does not execute in the context of the virtual environment, raising errors (i.e no module named django ...)
Is there a way to get "sudo" to execute in the context of the python virtual environment?!

A: No, you don't need to do this. You shouldn't be trying to run the development server on port 80; if you're setting up a production environment, use a proper server.

A: As @DanielRoseman said you should not be using the Django development server in production.
But if you need to run the development server on port 80 you have to reference the use the virtual environment python executable directly.
sudo ../bin/python manage.py runserver localhost:80

A: This should be the solution.
Even tho I really don't recomment doing this. If you need sudo within Python you are probably on a wrong way.

A: this did the trick:
$ sudo -- sh -c './venv-bin-path/activate; gunicorn <params> -b 0.0.0.0:80'


text:
Q: Code popup crashes the Android app After the most recent update of the Android app, when I click on some code blocks, the app crashes.
I still don't know for sure why this happens. Stack Overflow code blocks work perfectly while others crash the app.

A: This will be fixed in the next build.  I screwed things up big time.
The Android app has a global context that exposes things like the current activity, its site, toolbar, etc.  When I added support for site-specific default code highlighting I took advantage of this:
    private String getPrettifyHintFromTags(String[] tags) {
        if (tags == null)
            return null;

        for (String tag : tags) {
            if (PrettifyHinter.containsTag(tag))
                    return PrettifyHinter.get(tag);
        }

        if (PrettifyHinter.containsSite(Current.getCurrentSite()))
            return PrettifyHinter.get(Current.getCurrentSite());

        return null;
    }

What I didn't realize was that A) getCurrentSite will throw an exception if there is no current activity:
Activity act = getCurrentActivity();
if (act == null)
    throw new RuntimeException("getCurrentSite() can only be called when an activity is in the resumed state");

B) there is no activity between when the current activity gets onPause and the new activity gets onResume, C) things that happen between those two points include the new activity's onCreate and onStart calls.
With all these factors put together, the following sequence of events occurred:

*

*You tapped the code block.

*The question activity started an activity with the code popup intent.

*The question activity was suspended, setting currentActivity to null.

*The code popup activity was created, asked to prettify, found no SO tags, asked for the current site, and got an exception, crashing the app.

To mitigate this, I've changed the signature of the method to String getPrettifyHintFromTags(String[], Site) and making sure the site is passed in from an appropriate point rather than reaching into the context.


text:
Q: invoke command on remote machine is not working using powershell I ran the below commands on my machine to download data from one server to another server using the invoke command
Enable-PSRemoting -force

Enter-PSSession Server1

invoke-command -computername Server1 -credential:'dom\jack' {c:\temp.ps1 -server serverX -id 4231e429-d238-4e32-a1bb-0ee812cd3124 -download $true}

ERROR is: Failed: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
but when i run the above command on my machine as
c:\temp.ps1 -server serverX -id 4231e429-d238-4e32-a1bb-0ee812cd3124 -download $true
it works as expected.
Is there something i am missing when i execute it remotely....please help me.
thanks

A: Try this good References:
http://www.ravichaganti.com/blog/?p=1108
http://technet.microsoft.com/en-us/magazine/ff700227.aspx

It might be something to do with the TrustedHosts or Authentication
  setting of a client. You can set it like this:WinRM set
  winrm/config/client @{TrustedHosts="*"}

Read more about this here:
http://blogs.dirteam.com/blogs/sanderberkouwer/archive/2008/02/23/remotely-managing-your-server-core-using-winrm-and-winrs.aspx
I use
powershell.exe -ExecutionPolicy Unrestricted -WindowStyle Hidden -NoLogo

I use this code:
try
{

    Invoke-Command -credential $testCred -computer $ServerName -scriptblock {
        param([String]$scriptDeploy, [String]$destino)  &"$scriptDeploy" 'parametro1' $destino
        $ScriptBlockOutput = $Error
    } -ArgumentList $RutaRemotaParaScriptDeInstalacion, "$dirRemotoDestino"

    "`r`n`r`nOK para script de despliegue"
    exit 0;

}
catch
{
    "`r`n`r`nError en script de despliegue"
    "`r`nError in " + $_.InvocationInfo.ScriptName + " at line: " + $_.InvocationInfo.ScriptLineNumber + ", offset: " + $_.InvocationInfo.OffsetInLine + ".";

    exit -1
}

A: You need to enable remoting on the remote machine. You also need to make sure the firewall/anti virus does not block the remoting ports. These are port 5985 for http, or port 5986 for https.
If both machines on the same domain it's fairly easy to get working. If the machines are on different domains however then it's more complex. There's a registry setting that needs to be changed on the remote server, and you need to pass credentials. Have a read here for more info. There is of course ssl which can also be enabled, but that's another story.

A: There is a bug in your script.
You should not be executing Enter-PSSession before the Invoke-Command, because the Invoke-Command itself sets up the PSSession.
Use only this:
Invoke-command -computername Server1 -credential:'dom\jack' {c:\temp.ps1 -server serverX -id 4231e429-d238-4e32-a1bb-0ee812cd3124 -download $true}

... Without the Enter-PSSession


text:
Q: Error when trying to display image in tkinter canvas I was trying to create and display an empty image to edit and update later on. This code worked when not using tkinter, just the image display. When i run the following code:
from random import randint
from time import *
from PIL import Image as Img
from PIL import ImageTk as ImgTk
from tkinter import *
main = Tk()
main.geometry('1001x1001')
width, height = map(int, input('width and height\n').split())
canvas = Canvas(main, width = width, height = height)
canvas.pack()
next_cells = []
img = Img.new('RGB', (width, height))
pix = img.load()
tkpix = ImgTk.PhotoImage(pix)
imgsprite = canvas.create_image(width,height,image=pix)
main.mainloop()

I get the following error:
File "/Applications/eeie", line 14, in <module>
  tkpix = ImgTk.PhotoImage(pix)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/PIL/ImageTk.py", line 108, in __init__
  mode = Image.getmodebase(mode)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/PIL/Image.py", line 275, in getmodebase
  return ImageMode.getmode(mode).basemode
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/PIL/ImageMode.py", line 64, in getmode
  return _modes[mode]

builtins.KeyError: <PixelAccess object at 0x108aa4790>

What is causing this error?

A: Here you go, description in code.
from tkinter import *
import Image, ImageTk

# create canvas
canvas = Canvas(width=300, height=200, bg='black')
canvas.pack()
# create image object
img = Image.new('RGB', (60, 30), color='red')
new_image = ImageTk.PhotoImage(img)
# load into canvas
canvas.create_image(50, 10, image=new_image, anchor=NW)
mainloop()

Output:

To update canvas create function, and update root after changes to the object are made.
from tkinter import *
import Image, ImageTk
import time

def update_position():
    while True:
        canvas.move(rectangle, 30, 10)
        time.sleep(1)
        root.update()

root = Tk()
# create canvas
canvas = Canvas(root, width=300, height=200, bg='black')
canvas.pack()
# create image object
img = Image.new('RGB', (60, 30), color='red')
new_image = ImageTk.PhotoImage(img)
# load into canvas
rectangle = canvas.create_image(50, 10, image=new_image, anchor=NW)
update_position()
root.mainloop()


text:
Q: Passing multiselect values from typeform to Salesforce via Zapier I have a bit of a challenge using a multiple choice field in typeform and passing the values to Salesforce via Zapier.
I have choices

Car - Home - Boat - Bicycle

which in Salesforce will be put into a textfield. Zapier will take those selections and send them to Salesforce where it will look like

CarHomeBoatBicycle

which is not that readable.
In Zapier I am trying to comma separate the values in the template, where I add , in the field under templates. But that will look weird when only some choices are selected. It could like

Car,,,Bicycle

I want it to look like

Car, Bicycle

I have tried to use the formatter action in Zapier, but that didn't help me towards a solution.

A: David here, from the Zapier Platform team. Great question!
The bad news is there's no good out-of-the-box way to do this. We've got an open feature request with the typeform team to make this process easier, but there's been no motion so far.
The good news, it's a pretty straightforward code step.
You'll want to set up a Javascript Code step that maps in each value from typeform. These are stored in the inputData variable.
Then, you can paste the following:
return {formatted: Object.values(inputData).join(', ')}

This takes all the int put values (some combination of transportation methods) and joins them separated by ", ". You'll need to update the input to the zap whenever your typeform options change, but otherwise this should work as expected.
Let me know if you've got any other questions!

A: you can achieve that behavior now.
You just need to add the multiple choice question field to the Zapier template (not the individual options) and you will get back a comma separated list of the selected responses.
I hope it helps.


text:
Q: Differences between subqueries and JOIN statements in SQL LibraryDB is a database system that keeps track of information concerning the books and their circulation in an imaginary library.
The schema for the LibraryDB database is given below:(note that the book_copy relation keeps track of the physical copies of the books in the library collection.)

*

*borrow(transactionID, personID*, borrowdate, duedate, returndate)

*author(authorID, firstname, middlename, lastname)

*book_copy(bookID, bookdescID*)

*book(bookdescID, title, subtitle, edition, voltitle, volnumber, language, place, year, isbn, dewey, subjectID*)

*borrow_copy(transactionID*, bookID*)

*person(personID, firstname, middlename, lastname, address, city, postcode, phonenumber, emailaddress, studentno, idcardno)

*publisher(publisherID, publisherfullname)

*written_by(bookdescID*, authorID*, role)

*published_by(bookdescID*, publisherID*, role)

*subject(subjectID, subjecttype)

I tried to write two types of SQL statements in SQLite to display the title of books that were never borrowed.
One using the LEFT OUTER JOIN clause:
SELECT title
FROM book INNER JOIN book_copy
     ON book.BOOKDESCID = book_copy.BOOKDESCID
        LEFT OUTER JOIN borrow_copy
        ON borrow_copy.BOOKID = book_copy.BOOKID
        WHERE borrow_copy.TRANSACTIONID IS NULL;

which returned 323 rows.
One without using the OUTER JOIN clause:
SELECT title
FROM book
WHERE bookdescID IN
      (SELECT bookdescID
       FROM book_copy
       WHERE bookID NOT IN
             (SELECT bookID
              FROM borrow_copy));

which only returned 298 rows.
Why these two SQL statements return two different results?
Which one is correct in displaying the title of books that were never borrowed?

A: *

*Both queries were used three tables book, book_copy, and borrow_copy. But the first query:

SELECT title
FROM book INNER JOIN book_copy
     ON book.BOOKDESCID = book_copy.BOOKDESCID
        LEFT OUTER JOIN borrow_copy
        ON borrow_copy.BOOKID = book_copy.BOOKID
        WHERE borrow_copy.TRANSACTIONID IS NULL;

selected all books with bookdescID in book_copy, and then selected all records from borrow_copy with bookID in book_copy table. I.e. if two records presented in table borrow_copy for one bookID, that increases the count of rows in the output result.
Second query:
SELECT title
FROM book
WHERE bookdescID IN
      (SELECT bookdescID
       FROM book_copy
       WHERE bookID NOT IN
             (SELECT bookID
              FROM borrow_copy));

has applied additional filters for the basic table (book).

*The second query is correct for searching the books that were never borrowed.


text:
Q: preg_match coordinates with degree sign I am trying to capture the coordinates of an input that could look like this

22°50'23.46"S,  43° 0'44.80"W

or this

41°12'27.84"N, 16°18'40.15"E

I think the problem is the degree symbols in my pattern. My current code:
$found = preg_match("~(\d+\p{Sm}\d+\s*\'\s*\d+\s*\.\s*\d+\s*\"\s*[N|S])\s*,\s*(\d+\s*\p{Sm}\s*\d+\s*\'\s*\d+\s*\.\s*\d+\s*\"\s*[E|W])~i", $_POST['submission']['url'], $matches);

$matches stays empty.

A: You're missing the /u modifier to make the engine interpret the pattern as Unicode.

A: What is stopping you from using the ° character literally?
/
  (\d+\s*°\s*  \d+\s*'\s*  \d+\s*\.\s*\d+\s*"\s*  [NS])
  \s*,\s*
  (\d+\s*°\s*  \d+\s*'\s*  \d+\s*\.\s*\d+\s*"\s*  [EW])
/xi

A: Use mb_ereg_match instead to support UTF-8 chars. Docs: http://php.net/manual/en/book.mbstring.php
Initialize mb* like this:

mb_regex_encoding('UTF-8');
mb_internal_encoding('UTF-8');

A: Perhaps you should try ignoring the actual degrees and tick marks and focus just on the data you want to grab.
(\d+)\D+(\d+)\D+(\d+)\.(\d+)\W(\w+)\W+(\d+)\D+(\d+)\D+(\d+)\.(\d+)\W(\w)

This regex should capture the following data:
41
12
27
84
N
16
18
40
15
E

(Edit2: Corrected to properly pick up the N without punctuation.)


text:
Q: Doing owner draw in WPF items generated by data binding I am currently working on a WPF TreeView display. The content of this TreeView is from ordinary Data Binding:
<TreeView HorizontalAlignment="Stretch"
      x:Name="LogMonitor"
      VerticalAlignment="Stretch"
      ItemsSource="{Binding LogEntries, UpdateSourceTrigger = PropertyChanged }">
    <TreeView.Resources>
        <HierarchicalDataTemplate
                DataType="{x:Type Log:SystemLog}"
                ItemsSource="{Binding Path=Lines}">
                <TextBlock Text="{Binding Header}"/>
        </HierarchicalDataTemplate>
    </TreeView.Resources>
</TreeView>

The TreeView is filtered by keyword, but I would also like to have keyword highlighting for all the TreeViewItem that remain in the TreeView.
For instance, if there is a TreeViewItem with Header "This is an apple" and the user typed "apple" as filtering keyword, it should show a TreeViewItem looks like:

I tried some approaches, but there is not much luck.

*

*Using built-in styling :
The highlighting requires string matching and placing the color block underneath the matched substring. There seems no built-in style template that can be costumed into that way.

*Draw to canvas in ViewModel object and bind the canvas to the TreeViewItem :
It works only when the TreeViewItem is not selected, once selected, the built-in draw call cannot find a way to paint the canvas in the "highlight" style and just leaves a blank area.

*Create a subclass of TreeViewItem and override OnRender function, then substitute the ItemContainerGenerator of the TreeView to return my subclass of TreeViewItem :
Impossible, ItemContainerGenerator of TreeView is not settable and non-virtual.
And I can only think of one more option :

*Give up Data Binding, push the subclass of TreeViewItem with overrided OnRender function into Items list of TreeView by myself.
It gives me positive result in the experiment. But I feel uncomfortable about dropping Data Binding paradigm. So I would like to ask is there any other way to do owner draw with Data Binding presents.
Thank you.

A: Create a user control that breaks up the text into 3 areas: prehighlight, highlight, and post highlight.  You can do this all with standard binding and styling. Each TreeViewItem would be one of these controls.


text:
Q: How can I achieve accuracy of raycaster while mouse hover on different pieces of a LineSegment? I have created one example to draw a LineSegment in three.js. I have applied vertexColors to its material and pushed color for vertices. Now when I hover on all the different pieces of the LineSegment I change the color of that vertex (along with the next or previous vertex depending on the order it got pushed in the geometry.vertices array so that a line gets its color changed, you will understand once you see the code) that gets picked by the raycaster.
The jsfiddle link is here. https://jsfiddle.net/sounakgarai/tedmc2f0/3/
Now the issue is that the hovering is not accurate; a piece of the Linesegment gets its color changed even when the mouse cursor is in a far distance from it (you will be able to see it when you run it). I would like to see the accuracy in this case. The piece of LineSegment should change the color when the mouse cursor is accurately on it.
Is this achievable?

A: You don't take in count, that your container is not at the [0, 0] position on the screen.
As an option, you can use .getBoundingClientRect() method to get the bounding rect of your container and then subtract it from the mouse coordinates you get in your listener.
var rect;
. . .

// in the listener
rect = myDiv.getBoundingClientRect();

mouse.x = ((event.clientX - rect.left) / container.clientWidth) * 2 - 1;
mouse.y = -((event.clientY - rect.top) / container.clientHeight) * 2 + 1;

jsfiddle example
PS Just for your information, interface of jsfiddle.net has the Tidy button, which makes the code well-formed and thus much more readable.


text:
Q: Using Riemann Sum for ∑$c_n\sin(n\pi x /L)$ I have been attempting to convert the sum, $\sum_{n=1}^\infty$$c_n\sin(n\pi x /L)$, to a Riemann integral from a = 0 to b = $\pi$/L and with n ranging from 1 to ∞, but am a bit confused by the fact that the 'n' appears in the numerator, rather than in the denominator, of the angular part.
Can anyone help me to convert this to a continuous integral of the form normally associated with the Riemann integral for $\sum_{n=1}^\infty$$(\pi /n)\sin(i\pi  /n)$?
Having already made a number of attempts, I include my latest version in the hope that someone can comment.
Using the above information, $\Delta x_k$ = $\pi$/(Ln).  Since $x_k$ = k$\pi$/(Ln), then:
$\sum_{n=1}^\infty$$\ c_n$sin(n$\pi$x/L) = $\sum_{n=1}^\infty$$c_n$(Ln/$\pi$)sin(n$\pi$x/L)$\pi$/(Ln)
Substituting $\Delta x_k$ = $\pi$/(Ln) and $x_k$ = k$\pi$/(Ln), we have:
$\sum_{n=1}^\infty$$\ c_n$sin(n$\pi$x/L) = $\sum_{n=1}^\infty$$c_n$(Ln/$\pi$)sin($\pi^2$k/$L^2$)$\Delta x_k$.
From $x_k$ = $\pi$k/(Ln), we have $\pi$k/L=n$x_k$, so substituting this latter relationship into the angular part, the term on the right hand side may now simply be expressed as the integral:
$\sum_{n=1}^\infty$$\ c_n$sin(n$\pi$x/L) =  $\int_0^L$$c_n$(Ln/$\pi$)sin(n$\pi$$x_k$/L)$dx_k$
which now becomes:
$\sum_{n=1}^\infty$$\ c_n$sin(n$\pi$x/L) =  $\int_0^L$$c_n$(Ln/$\pi$)sin(n$\pi$$x$/L)$dx$
to which the result is:
$\sum_{n=1}^\infty$$\ c_n$sin(n$\pi$x/L) = 0
for even n, and:
$\sum_{n=1}^\infty$$\ c_n$sin(n$\pi$x/L) = 2$c_n$$L^2$/$\pi^2$
for odd n.
Any additional suggestions or comments on my results will be warmly welcomed.
Thank you in advance


text:
Q: php mysql server execution time - want to reset after every time a function is called. is it possible? I'm using a recursive function to do some calculation for every user and reward them for certain condition. Everything was working fine, but now that my user number has increased to something like 20000+ my script cannot be completed... my code is like
function give_award($mid) {

    $qry = mysql_query("SELECT * FROM users WHERE uid='$mid'");
    while($row=mysql_fetch_array_result)
     {
      $refer = $row["refer"];
     }
    //some conditions applied
    //query for user award
    //if succeed

    $mid = $mid+1;
    give_award($mid)

}

give_award($mid);

I'm Sure give_award(); isn't doing the time out in a single time calling. Is there a way that I can reset the time limit every time before the function is recursively (re)called?
Ways I've tried:
set_time_limit(0);
changing the timeout limit in .htaccess
changing apache timeout limit in php.ini
NB: No fatal error was show... But I've to restart apache every time I try to run this on local server... Using Zend Server Community edition on Win7 32bit.
Please help

A: I don't know where to find the recursion limit, but this is not a place to use it as far as I can tell anyway. A quick test here:
<?php
function KillingRecurse($r){
        echo $r.PHP_EOL;
        KillingRecurse(++$r);
}
KillingRecurse(0);

Result:
...
20916
Segmentation fault

I'm not surprised a segfault causes the server to need to be restarted, and the numbers kind of match up.
Tell us more about what you are trying to do here, because recursing through all users seems maddness here...


text:
Q: jQuery UI Draggable Limits I'm making a draggable item, I just want this to drag vertically, limiting to the parent div, so its always completely visible, any suggestion?
http://jsfiddle.net/q3nz4/

$('#dragable').live('mouseover',function(){
   $(this).draggable();
});

A: Take a look at this: http://jqueryui.com/demos/draggable/constrain-movement.html
$(function() {
    $("#draggable").draggable({
        axis: "y"
    });
});


text:
Q: I2C: How to adress the second page of a eeprom I have an eeprom and I can't properly adress everything out of the range 0x00-0x1f.
Using the Raspberry I send the following I2C command to the eeprom:
"sudo i2cset -y 1 0x50 0x00 0x10 0x29"
This command writes the byte 0x29 at the adress 0x10 to the eeprom.
I can than look if it worked by using the command "sudo i2cdump -y 1 0x50 i"
But if I use the same command as above but with a higher second adress value (for example sudo i2cset -y 1 0x50 0x00 0x80 0x29) and then try to look if it worked with i2cdump I don't see any changes. If I change the first byte adress value (for example sudo i2cset -y 1 0x50 0x01 0x10 0x29) then the value change is displayed at 90/0 in the i2cdump output.
Here is an example output of i2cdump so you can better understand what I mean (not my i2cdump output):
     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
10: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
20: 8a 8b de bb c9 d8 d0 1d ff ff aa c1 9e c1 9e e3
30: ba cc a8 d8 b2 ed c2 e4 bb 3c 32 e1 e1 e1 00 00
40: 01 c3 00 00 00 00 40 50 2d 01 01 40 01 95 00 a3
50: 10 01 80 ff ff ff 00 00 11 ff ff ff ff ff ff ff
60: 8a 8b de bb c9 d6 d1 1d ff ff aa c1 9e c1 9e e3
70: ba cc a8 d8 b2 ed c2 e4 bb 3c 32 e1 e1 e1 00 00
80: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
90: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
a0: 8b 8b de bb c8 d9 d1 1d ff ff ab c1 9e c1 9e e3
b0: ba cc a8 d8 b2 ed c2 e4 bb 3c 32 e1 e1 e1 00 00
c0: 01 c3 00 00 00 00 40 50 2d 01 01 40 01 95 00 a3
d0: 10 01 80 ff ff ff 00 00 11 ff ff ff ff ff ff ff
e0: 8a 8a de bb c9 d8 d1 1d ff ff aa c1 9e c1 9e e3
f0: ba cc a8 d8 b2 ed c2 e4 bb 3c 32 e1 e1 e1 00 00

Here's a link to the datasheet from my eeprom, it says a page is 32 byte big, I think that explains why I can`t adress anything bigger than 0x1f. But I don't understand how I can adress the next byte address after 0x1f ?!
Am I interpreting the i2cdump wrong or do I have to use other byte addresses ?
https://cdn-reichelt.de/documents/datenblatt/A300/ST24C32_ST24C64%23STM.pdf

A: You need to take a closer look at the memory datasheet. Figure 6 on page 7 shows the sequences needed to write to the memory array.
This is not compatible with what the i2cset command is doing. This command assumes that the I2C device is organized as up to 256 8-bit registers, where the register address is the second byte transmitted, and the data to be written is the third byte.
The memory device is not organized in this way. You need to find or write a different command that will send the correct sequences on the I2C bus.


text:
Q: Content script & jQuery. Download/get DOM from different web page I'm trying to modify img src attribute by getting the url from different page. Thing is i need to find it by inspecting DOM as it's not static data; i will be looking via classes and IDs.
My knowledge of chrome extensions is very limited at the time. Basicly i just started.
Look at the "PSEUDO CODE" part of background.js
manifest.json
{
    "manifest_version" : 2 ,
    "name": "#####" ,
    "version": "1.0" ,
    "description": "#####" ,
    "browser_action":
    {
        "name": "#####" ,
        "icons": ["icon.png"] ,
        "default_icon": "icon.png"
    },
    "content_scripts": [
    {
        "js": [ "jquery.min.js", "background.js" ] ,
        "matches": [ "http://*.#####.com/encounters/promospp.phtml"] ,
        "run_at": "document_end"
    }]
}

background.js
var l = document.getElementsByTagName("div");

for (var i = 0; i < l.length; i++)
{
    var obj = l[i].parentNode;
    if (l[i].getAttribute("class") && l[i].getAttribute("class") == "user_contact")
    {
        var div = l[i];
        var id = div.getAttribute("id").replace("u_", "0");
        var profileUrl = "../" + id + "/";

        var imgs = div.getElementsByClassName("userpic");
        log("found img.userpic : " + imgs.length);

        if (imgs && imgs.length > 0)
        {
            var img = imgs[0];

            var alink = document.createElement('a');
            img.parentNode.appendChild(alink);

            alink.setAttribute("href", profileUrl);
            alink.appendChild(img);

            // PSEUDO CODE - the unknown
            //
            // download profileUrl page html
            // search for given div element
            // pull src attribute value from it
            // apply it to img here

        }
    }
}

So in essence. How to download different page and work with it

A: Since you are including it already and tagged your question with it, I am going to answer with jQuery, I hope you don't mind. So first I rewrite what code you have in jQuery:
$('div.user_contact').each(function(){
  var id = $(this)[0].id.replace('_u','0');
  var profileUrl = "../" + id + "/";
  var imgs = $(this).find('.userPic');
  if(imgs.length > 0){
    var alink = $(document.createElement('a'));
    $(this).append(alink);
    $(alink).attr('href',profileUrl);
    $(alink).append(imgs[0]);

    //Here is where you get the page and search for the div you want
    $.get(profileUrl,function(data){
      //Since I don't know the layout of what you are looking for
      //I will just put in some placeholder
      $(imgs).first().attr('src',$('img.youWant',data).first().attr('src'));
    });

    // Since $.get is asynchronous, doing it like this might cause problems
    // if there is more than one div.user_contact.
    // In the case where there are a low number of them and you are fine running
    // blocking synchronous code, then you can do it with this instead:
    // $.ajax(profileUrl,{async:false,success:function(data){
  }
});

You'll also need to include permissions in your manifest for the site you are $.geting from. Something like this:
"permissions":["*://*.badoo.com/*"]

A: Using BeardFist solution + few fixes final code looks like this:
$('div.user_contact').each(function()
{
  var id = $(this)[0].id.replace('u_','0');
  log(id);
  var profileUrl = "../" + id + "/";
  log(profileUrl);
  var imgs = $(this).find('.userpic');

  if(imgs.length > 0)
  {
    var alink = $(document.createElement('a'));
    $(imgs[0]).parent().append(alink);
    $(alink).attr('href',profileUrl);
    $(alink).append(imgs[0]);

    $.get(profileUrl, function(data)
    {
      $(imgs[0]).attr('src',$('img.pf_phts_b_pht', data).attr('src'));
    });
  }
});

It works excelent. Entire html is inside data and it even stays loged and stuff :)


text:
Q: Google Maps CSS don't show map I have some problem with adding Google Maps to my project. When i get it into body tags it works. But when I have structure like this

it doesn't show anything. How I can solve this problem?

A: It is because height: 100%; is always relative to the parent's height. In your case, this is the nameless div, which has zero height, so #map_canvas will be the 100% of that, which is still zero. So the Google Maps won't show because the div has no visible height.
If you specifiy 100% on the parent div, it will work again. I guess you already have html, body { height: 100%; } if it works being simply in the body tag.
jsFiddle Demo

A: Do you have html, body also at 100%?
html, body, #map_canvas { margin: 0; padding: 0; height: 100% }


text:
Q: rendering hircharchic structure in symfony I have a datastructure which has a (possible) infinite depth. Similar to a file structure. Now I'm thinking about the best solution to output this by a twig template.
I was thinking about passing a multidimensional array to twig but this isn'T the best solution I think.
The structure look like:
- id1|testname
- - id4|anothere one
- - - id12|onemore
- id42|another text
- - id48|anothernode

... and so on ...
Is there a good solution to grab all levels inside a controller?
Actually, I take all "level 0" nodes (the one without subnode -Ids) by a query and run through it by a for loop. Then I check in another function ($this->checkChildNodes($id)) if there are Child nodes existing. But this is really ...uhm... non-professionell and I need your help to get a clear and nice solution.
Thank you all for your help in advance :)

A: The way your query depends on the way you store the data structure in a database. Nested structures are much easier to query if you use solutions like a nested set or materialised path.
In templates, you can leverage twig blocks or macros to make rendering a bit easier.
I'd consider restricting depth level. Almost every time you can define a safe limit. I never had a requirement for an inifite nesting presented on a single view - it would be hard to present such a structure to the end user.
Also, have a look at how it's organised in KnpMenu and KnpMenuBundle. KnpLabs/DoctrineBehaviors looks interesting as well.


text:
Q: java reflection calling a function I am using the java reflection to call an API from the .class . I see my function is the list of functions listed by the .getMethods() API . The no param version works fine but the parameterised version fails .
The compilation time call for the API was
public static class CapabilitiesEditor  extends ComboBoxPropertyEditor  {
    public CapabilitiesEditor() {
        super();
        print(); // Call to print if fine .
        setAvailableValues(new String[] { "High", "Medium", "Low", "None", }); // I want call this one . Fails
        Icon[] icons = new Icon[4];
        Arrays.fill(icons, UIManager.getIcon("Tree.openIcon"));
        setAvailableIcons(icons);
    }

Here is my code that attempts to change the setAvailableValues dynamically.
 Class<?> cls;
    // Paremeterized call
    Class[] paramObject = new Class[1];
    paramObject[0] = Object[].class; // Function takes a single parameter of type Object[]
    Object[] params = new String[] { "H", "M", "L", "N" };

    // no paramater version
    Class noparams[] = {};

    try {

    cls = Class.forName("com.app.services.prop.system.SystemTopologyBean$CapabilitiesEditor");                                  Object obj = cls.newInstance();

    for(Method method : cls.getMethods()){
        System.out.println("method = " + method.getName());
    }
    // WORKS
    Method method = cls.getDeclaredMethod("print", noparams);
    method.invoke(obj, null);

    // **DOES NOT WORK**
    Method method = cls.getDeclaredMethod("setAvailableValues", paramObject);
    method.invoke(obj, params);

    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException e2) {
                                // TODO Auto-generated catch block
                                e2.printStackTrace();
                            }

I always get the following exception
java.lang.NoSuchMethodException: com.app.services.prop.system.SystemTopologyBean$CapabilitiesEditor.setAvailableValues([Ljava.lang.Object;)

EDIT :
I follow Mkyong wonderful tutorial on reflection How To Use Reflection To Call Java Method At Runtime

A: To retrieve your method, and then invoke it, you'll need to do it like this:
Class cls = Class.forName("com.app.services.prop.system.SystemTopologyBean$CapabilitiesEditor");
Object obj = cls.newInstance();
Method method = cls.getDeclaredMethod("setAvailableValues", new Class[] {String[].class});
method.invoke(obj, new Object[] {new String[] {"Foo", "Bar"}});

A: So there were two issues here that prevented me from access the function . Be careful I should have been using  getMethod instead of getDeclaredMethod
See Using .getDeclaredMethod to get a method from a class extending another answer to know which one should be applicable.
Also be very careful in calling the method.invoke function especially the second parameter .
See How to call MethodInvoke - reflection and Michael's answer above for the correct way to call .


text:
Q: Prometheus Alert Rules with docker label only working with prefix "container_label_"? I am running a prometheus-cadvisor.. monitoring dockerized system. In the docker containers that are to be monitored, I have
docker-compose.yml
    ...
      labels: somelabel: "somename"

in a Prometheus
alert.rules_containers

        ALERT missing_container
          IF
        count(rate(container_last_seen{name=~".+",somelabel=~"somename"}[5m])) by (somelabel,host) < 10
          FOR 5m
          ANNOTATIONS {...}

but this does not work
it only works if I change
somelabel to container_label_somelabel
Why ist that. I could not find any explanation anywhere. And all the example code I found was using labels the same way I did in the non-working version.

A: it seems this was a recent change in cAdvisor
https://github.com/google/cadvisor/pull/1426


text:
Q: GAE appcfg.py deploy always upload all files (instead changed only) I've started to have a problem today.
Everytime I run appcfg.py update . it updates 441 project files.
Even if I just modified 1 it will upload 442.
running appcfg.py update . twice will upload 441 files every time.
This is obviusly a problem because instead uploading a couple of files it is uploading a lot of them and taking a lot of time.
This is what I have tried:

*

*Updated app engine launcher to it latest version

*Rebooted

*removed all files from the folder, download them again from git

nothing seems to work.
I even left only app.yaml and index.php and it uploaded both files every time, even if I do not change anything.
Ideas?  thanks

A: This is expected behavior. Uploading the files are always fast for me.

A: it is fixed now.
At the moment of this answer, google seems to have fixed the issue.
Just tried to deploy and it only uploaded the modified files.


text:
Q: Is there a way to use periodicity in a regular expression? I'm trying to find a regular expression for a Tokenizer operator in Rapidminer.
Now, what I'm trying to do is to split text in parts of, let's say, two words.
For example, That was a good movie. should result to That was, was a, a good, good movie.
What's special about a regex in a tokenizer is that it plays the role of a delimiter, so you match the splitting point and not what you're trying to keep.
Thus the first thought is to use \s in order to split on white spaces, but that would result in getting each word separately.
So, my question is how could I force the expression to somehow skip one in two whitespaces?

A: First of all, we can use the \W for identifying the characters that separate the words. And for removing multiple consecutive instances of them, we will use:
\W+

Having that in mind, you want to split every 2 instances of characters that are included in the "\W+" expression. Thus, the result must be strings that have the following form:
<a "word"> <separators that are matched by the pattern "\W+"> <another "word">

This means that each token you get from the split you are asking for will have to be further split using the pattern "\W+", in order to obtain the 2 "words" that form it.
For doing the first split you can try this formula:
\w+\W+\w+\K\W+

Then, for each token you have to tokenize it again using:
\W+

For getting tokens of 3 "words", you can use the following pattern for the initial split:
\w+\W+\w+\W+\w+\K\W+

This approach makes use of the \K feature that removes from the match everything that has been captured from the regex up to that point, and starts a new match that will be returned. So essentially, we do: match a word, match separators, match another word, forget everything, match separators and return only those.
In RapidMiner, this can be implemented with 2 consecutive regex tokenizers, the first with the above formula and the second with only the separators to be used within each token (\W+).
Also note that, the pattern \w selects only Latin characters, so if your documents contain text in a different character set, these characters will be consumed by the \W which is supposed to match the separators. If you want to capture text with non-Latin character sets, like Greek for example, you need to change the formula like this:
\p{L}+\P{L}+\p{L}+\K\P{L}+

Furthermore, if you want the formula to capture text on one language and not on another language, you can modify it accordingly, by specifying {Language_Identifier} in place of {L}. For example, if you only want to capture text in Greek, you will use "{Greek}", or "{InGreek}" which is what RapidMiner supports.

A: What you can do is use a zero width group (like a positive look-ahead, as shown in example). Regex usually "consumes" characters it checks, but with a positive lookahead/lookbehind, you assert that characters exist without preventing further checks from checking those letters too.
This should work for your purposes:
(\w+)(?=(\W+\w+))

The following pattern matches for each pair of two words (note that it won't match the last word since it does not have a pair). The first word is in the first capture group, (\w+). Then a positive lookahead includes a match for a sequence of non word characters \W+ and then another string of word characters \w+. The lookahead (?=...) the second word is not "consumed".
Here is a link to a demo on Regex101
Note that for each match, each word is in its own capture group (group 1, group 2)

A: Here is an example solution, (?=(\b[A-Za-z]+\s[A-Za-z]+)) inspired from this SO question.
My question sounds wrong once you understand that is a problem of an overlapping regex pattern.


text:
Q: Using PHP to find the number inside {{2461245}} What is the best way to extract the number in the following string:
"This is a test string {2461245} and I need to extract the number"

Thank you.

A: This should help you :
$myText = 'This is a test string {2461245} and I need to extract the number';
preg_replace("/[^0-9]/","",$myText);

What you are saying there is : I want to replace everything which is not a number in the myText variable by "", which means everything which will stay in the end is your number.


text:
Q: Remove a file from a git branch but keep it in another? Recently I was working with someone else in 2 different branches on the same project. I accidentally merged the branch develop, which contained his code, into mine. I then saw his files in my merge request and subsequently learnt the hard way that doing
git rm HIS_FILES
on his unwanted files in my branch, would not only delete them from my branch, but from his too (and the entire git index).
What I want to know is, how would I correctly remove his files from my branch, so that they are not also deleted from his? Do I make a new branch once I realised his files are in my branch? Do I revert to the previous commit before I merged branch develop into my local one?
Thanks for any help

A: (This is technically a comment rather than an answer, but I wanted to be able to use formatting ... and, it would never fit.)

[git rm] would not only delete [files] from my branch, but from his too (and the entire git index).

This is not the case.  Moreover, this is not the right way to understand Git's index.
The index has three names: Git calls it the index sometimes, but then calls it the staging area other times.  In a few places, Git uses the word cache.  These mostly all refer to the same thing, whose concrete implementation is mostly just a file in the .git directory named index.1  But the index, regardless of which of these names you use for it, has little to do with existing commits.  The main function of the index is that it is where you build your proposed next commit.
When we talk about the index using the phrase staging area, we're concerned with the copies of files that are kept in the index.2  The way Git works, you have at your fingertips, at all times, three copies of each file!  You pick a commit—using git checkout or the new git switch in Git 2.23 or later—to be your current commit.  That commit holds a snapshot of all of your files, in a special read-only (and Git-only) compressed format.
These frozen format files inside a commit cannot be changed.  Nothing about any existing commit can be changed.  There are some big advantages to this: for instance, since the files can't be changed, they can be shared.  If commit A has some version of some file, and commit Z has the same version of the same file, the two commits can simply share the one underlying file.  (This is actually based on file content, not file name.)  But that has a big disadvantage too: it means you can't actually do anything new, i.e., do any new work, with these frozen files.
Git therefore needs a way, and a place, to defrost and decompress—i.e., rehydrate—the frozen-and-compressed (dehydrated) files.  The place Git puts them is in your work-tree.  Files in your work-tree are plain ordinary everyday files, as provided by your computer, so you can get work done.
So this explains two of the three copies of all of your files: there's the dehydrated copy of README.md in the current (or HEAD) commit, and there's the ordinary and useful copy of README.md in your work-tree where you can work with it.  But what's this third copy doing?
The answer is: it's sitting there in your index—or "staging area"—in the freeze-dried format, ready to go into a new commit.  If you run git commit right now, Git will build the new commit from the freeze-dried copies of files that are in the index.  Why not use the ones from the commit?  That should be obvious: it's because you can't change those copies!  But you can replace the freeze-dried copies that are in your index.  That's what git add does: it compresses (freeze-dries) the work-tree version of the file and writes that into the index.3
So, suppose you modify the work-tree version of README.md.  Before git add README.md, the index copy of README.md matches the HEAD copy of README.md, and the work-tree copy is different.  After git add README.md, the index copy of README.md matches the work-tree copy (except for being in the freeze-dried format).  There are three copies at all times, but two of them match.  Using git add replaces the index copy, so that it matches the work-tree copy.  (The HEAD copy can't be changed.)
This means that at all times, the index is ready to go: git commit simply packages the freeze-dried index files into a new commit.  The new commit becomes the HEAD commit, by being added to the current branch.  The new commit now has a full and complete (and frozen for all time) copy of every file, as seen in the index.  Now the HEAD commit and the index match, and if the index matches the work-tree, all three copies match.
When you use git rm, Git removes the named file from both the index and the work-tree.  The next git commit will not have that file, because it's not in the index.
If you then git checkout some other branch, Git now finds all the files in the frozen commit that is the tip of that other branch.  Git copies all these frozen-format files into the index, so that they're ready to go into the next commit you make; and having updated the index copies, Git rehydrates those into the work-tree, so that you can see and use the files.  Now the (newly-selected, different) HEAD commit, index, and work-tree again all match, and you're ready to work.
If, during switching from commit Z back to commit A, Git finds that commit Z has some file—to-be-deleted.txt perhaps—that isn't in commit A, Git removes to-be-deleted.txt from the index and from the work-tree.  So now it's gone—but it's still there in commit Z.  If you git checkout commit Z, Git sees that to-be-deleted.txt isn't in commit A, isn't in the index, and is in commit Z, so it copies the commit Z version of to-be-deleted.txt into the index and work-tree ... and now, again, HEAD, the index, and the work-tree all match.
One key to keep in mind at all times is that Git is about commits.  We will git checkout some branch name to switch branches, but that name identifies one particular commit.  Git will then fill the index and work-tree—both of which are temporary areas!—from that commit.  When we make a new commit, Git simply packages up whatever is in the index, adds our name and so on, writes out the new commit with its parent being the commit we checked out, and then updated the branch name to remember the hash ID of the new commit.  So branch names move.  The commits, once made, never change at all, and normally last forever.4

1We have to say mostly because there are a number of exceptions to this rule.  However, you can point Git to a different file, for special purposes, by setting the environment variable GIT_INDEX_FILE to the path name of a temporary index you'd like Git to use.  Git will create that file if it does not exist, and then use it as the index.  The git stash command, for instance, uses this to create commits from a temporary index, all without disturbing the (main or real) index.
2Technically, the index holds references to blob objects, which are how Git stores files in a frozen format.  Unless/until you get around to using things like git hash-object and git update-index, though, it works just as well to think of the index as containing a frozen-format copy of each file.
3This is where git hash-object -w and git update-index come in: git add compresses and writes a new freeze-dried blob object, or discovers that an existing blob has the right content and therefore winds up re-using that existing, already-frozen blob object.  That blob object has, or gets if it's new, a unique hash ID, and git add uses the same code as git update-index to write the correct hash ID into the index.
We could equally ask Why not build the new commit from the work-tree?  There's no really good answer to this:5 other version control systems, that don't shove an index in your face all the time, actually do that, or something that looks like that.  But Git shoves the index in your face, so you need to know about it.
4To get rid of a commit, you arrange things so that you can't find the commit.  Since branch names identify the last commit, it's easy to remove a commit that's at the end: just make the branch name go backwards, to identify that commit's parent.  But you can find every earlier commit by going backwards, one step at a time, so you can really only remove the tail end commits.  (This is clearer in some other VCSes, such as Mercurial, that don't let commits be on multiple branches.  Things get confusing in Git, where a commit is potentially on many branches at the same time.)
5One can point out the various features offered as a result, such as git add -p, but that's kind of a weak ex-post-facto justification.  The real question is whether these features are worth the initial complexity.  I don't think they are—I think Git could offer them in some other way that doesn't make the index as in-your-face as it is—but that's both opinion and speculation, which isn't really appropriate for StackOverflow.

A: git rm removes the file from your branch only.
The possible reason that the file has been deleted in other branches is that your branch has been merged to other branches. The merge should have removed that file.


text:
Q: Access Linked Tables, how to force relational values
Hopefully the image above makes it thru. So the way this works is that a user uses a form to enter the values on the Vuln_Remediation_Planning table. After all vulnerabilities associated with a patchID and existing OS have been entered, he moves to the next form where he is suppose to mitigate the risk associated with the vulnerabilities, and you can have multiple mitigating measures which is why the table is separate.
My question:
Right now when using the compensation form, the user has to select each patchID, OS, and vulnerability ID for each mitigating measure they select... this is cumbersome and error prone. Recall the first form only operates on the planning table, the second form operates on the compensation table.. but they are related so I feel the user would want to use a single drop down to select the top the primary keys, already assign in the previous table.
I was going to ask how to handle this, but I may have solved my own problem... 3 column combo box right, with the row source coming from the Remediation planning.... lol what do you think, any other ideas?

A: I figured it out. On the compensation table I just created a continuous form, and moved the OS and patchID fields to the header. When opening the form normally, it looks funny because the header values change when records are selected (as would be expected if they were all on the same row). Then from the remediation planning form, I have a button to open the compensating measures form that filters it so only the patchID/OS of the parent for is shown. Additionally, in the open event of the compensating measures form, I set the default values of PATCHID/OS using open args (in case no records are there yet or the user adds new records... otherwise it opens blank when there are no records.


text:
Q: Web.Config size limit for Azure Websites I have an ASP.NET web application which I am migrating to Microsoft Azure. For various reasons, our web config file has grown to be rather large. On our "on site" instance, we have solved this by modifying a registry key as recommended in this post. We have also split our web.config into smaller files, but we now have sub files which have also exceeded the limit, so splitting the files is not an option anymore.
I am assuming this is not possible in an Azure Website, and only if I am running a Virtual Machine in Azure. Is there any solution to this without creating a virtual machine?


text:
Q: Убираем таксономию(/?brand=...) Есть код. Данная тема не дубликат других тем! Приведен конкретный пример! Данный код представляет кнопку при нажатии на которую происходит фильтрация товара. При нажатии в адресной строке появляется небольшое дописывание по типу
/?brand=Название бренда. Как избавиться от /?brand= и оставить только      /Название бренда.
Может быть какой-то код редиректа. Или код скрытия таксономии из адресной строки. Или плагин какой.
Мой код кнопки:

                        <? foreach($brand_list as $brand){?>
                        <div class="<?if (in_array($brand->slug, $brand_array)) {?>active<?php }?>">
                        <label for="<?=$brand->name;?>">
                        <img src="<?=get_field('изображение', 'term_'.$brand->term_id)['url'];?>" />
                        <input  onchange="this.form.submit()" type="checkbox" id="<?=$brand->name;?>" name="brand" value="<?=$brand->name;?>">

                        <? }
                        ?>


text:
Q: Get user name and password fora particular website from browser history For My application, I want to check if for a particular website, user has user name and password saved in browser history. And if it saved, then read those credential details and used in my application to connect to that website using C# code.
I am not sure if it is possible.
Thanks

A: Don't think it's possible as none of the current browsers provide APIs to access secured data. For obvious reason to avoid any third party application accessing this information without authorization and use for malicious purposes.
You can access chrome related password information within browser only. You can access passwords in chrome by browsing to Link. This article shows how to access the information from within chrome.
In short your task is not possible.

A: To implement "keep me logged in functionality you need to write a UID (not their password or username) to the site cookie (with an expiry date say in 60 days) once they have confirmed their membership username/email address. Then on subsequent visits in the session_start procedure on your server (global.aspx file on IIS/asp.net) you use the UID value in the cookie to lookup in your Membership database for a valid and current membership record.... If the cookie crumb has expired, or no current membership record is found you redirect them to your login/join page to re-enter their credentials or to join your site.
Here is a VB.net session start from one of mine.
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
    Session("user_uid") = "8a4e9b96-1e80-40f2-af4f-1b4b736bd17a" ' Visitor
    'Code that runs when a New session Is started
    If Request.Browser.Cookies() Then
        If Not (Request.Cookies("UID").Value) Then
            Response.Cookies("UID").Value = Session("user_uid")
        Else
            Session("user_uid") = Request.Cookies("UID")
        End If
        Response.Cookies("UID").Expires = Now().AddDays(60)
        Response.Cookies("LASTVISIT").Value = Now().ToString()
        Dim count As Integer = Convert.ToInt32(Request.Cookies("VISITCOUNT").Value & "")
        Response.Cookies("VISITCOUNT").Value = (count + 1).ToString()

    End If
End Sub

See your Visual Studio Template projects or search in the Visual Studio Gallery for a template project that implements a SQL membership database with persistent credentials (MS Hello is an alternative also)


text:
Q: Inheritance: 'super' object has no attribute I'm trying to make a factory that will create an object that uses instance variables from a parent class. Doesn't a parent class get initialized to create a child class?
I thought adding super().__init__ in the child class' __init__() might fix it but it did not.
If instead of instance variables I used class variables in the parent class this error does not occur, but I don't want to share the data between child instances.
Is there a way to fix this?
class factory:

  @staticmethod
  def fact(type):

   if type is "A": return child_A()

   if type is "B": return child_B()

class parent:

  def __init__(self):
    self.attr1 = []
    self.attr2 = []

class child_A(parent):

  def __init__(self):
    self.data = [super().attr1, super().attr2]

class child_B(parent):

  def __init__(self):
    self.data = [super().attr1, super().attr2]

A: I was close. The parent attributes get accessed by the child class with self rather than super(). The parent class must be instantiated first.
class factory:

  @staticmethod
  def fact(type):

  if type is "A": return child_A()

  if type is "B": return child_B()

class parent:

  def __init__(self):
    self.attr1 = []
    self.attr2 = []

class child_A(parent):

  def __init__(self):
    super().__init__()
    self.data = [self.attr1, self.attr2]

class child_B(parent):

  def __init__(self):
    super().__init__()
    self.data = [self.attr1, self.attr2]


text: Q: Convert 2 digit years into 4 digit years and change the format in R I have a dataframe with a date column in the following format "21/03/22 20:00" which stands for 21 March 2022, 08 PM. I would like to convert that column with the format "2022-03-21". Is there an easy way to do this in R? I've searched in related questions but none of the answers helped me. Thanks


text:
Q: Symfony: Using a type='text' with form type 'checkbox' Is there a way to use the checkbox form type with a field that has been set to string?
This field can hold many values, it can be used to input data as a textfield or as a checkbox.
I have a event listener on the formtype to check if it should be a checkbox or text field.
/Entity.php
/**
 * @var string
 *
 * @ORM\Column(name="value", type="string", length=200, nullable=true)
 */
private $value;

formtype.php
$form->add('value', 'checkbox', array(

))

Error
Unable to transform value for property path "value": Expected a Boolean.

A: Entity.php
public function getValue()
{
    return (boolean)$this->value;
}

A: this worked for me:
rewrite the function in the Entity, adding explicitly boolean values in returns
public function getEstado() {
    if ($this->estado===1) {
        return TRUE;
    }
    return FALSE;
}


text:
Q: why mvm package to make springboot fat jar works for parent but not working for dependencyManagment I want to just use mvn package to make springboot fat jar but for below pom setting
mvn package works to create springboot fat jar
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.0.RELEASE</version>
    <relativePath/>
</parent>

for below pom setting, mvn package does not create springboot fat jar, i have to use mvn package spring-boot:repackage, why is that ? any hints will be more
than welcome!
<dependencyManagement>
    <dependencies>
        <!-- Spring Boot BOM -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>${springboot.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
      </dependencies>
</dependencyManagement>


text:
Q: Mock Progress Bar using jest i am writing unit test cases for a js file which contains Progress Bar library, how to mock this

myjs.js

console.log("File that contains some js code....")
function myFunc(para1,para2){
  var par = para1 + para2;
  swal("Info",para);
  return 3;
}
var bar = new ProgressBar.Line(dynamic, {//some code here} );

i am planning to unit test this function named "myFunc" so , i have written a test script that contains below code:

test.js

const $ = require('jquery');
global.$ = global.jQuery = $;
var ProgressBar = require('progressbar.js');
var myJs = require('myjs.js');
test('test if myFunc returns "3"',()=> {
 expect(myJs.myFunc).toBe(3);
 })

The myJs.js is loaded as a part of django template including the progressBar.js, while running this test case i get a error like ProgressBar is not defined.

additionally there exists a sweetalert in myFunc, how to mock this as well , a part from ProgressBar ?
Any kind help is appreciable


text:
Q: Testing increasing features with unit tests I'm wondering what the best practices are in Test Driven Development / testing using unit tests when it comes to increasing features.
E.g. I have a requirement when an object of Class Foo receives a bar() message, it should update a given field counter accordingly. I create a test case for this, which creates a Foo object and then tests the requirement.
Now what should I do if there is a new requirement, that when Foo receives a bar() message also another field, counter2 should be updated. Should I create a new test case for this, which checks only the second requirement, or do I just update the first test case?

A: Seems that your question contains the answer. From my practice, if it's a new requirement, which doesn't change previous one, then you should create a new test for it. If it's a change of requirements -- then you should modify old test, to fit these updated requirements, and do it prior to implementation.

A: I would generally add a new test case, so that the two features are kept independent in testing, and which test fails indicates which feature is wrong.


text:
Q: SQL Server: Replace values in field via lookup other table I am currently running into a challenge that probably has a easy solution, but somehow I am not able to come up with it.
I have Table A with two fields that are formatted as follows:
[ID]   [Codes]
 1      A;B
 2      D
 3      A;C

And table B formatted as follows:
[ID]   [Codes]
 A     Apple
 B     Orange
 C     Pear
 D     Strawberry

What I would like to do is a Lookup / Replace in order to generate the following output
a.[ID]   a.[Parsed_Codes]
  1     Apple;Orange
  2     Strawberry
  3     Apple;Pear

In short I want to replace the codes in table A, with the values associated with those codes in table B.
Of course I could just write a long replace statement (in my case there are several 100 codes), but that seems like an extremely inefficient method.
Thanks!

A: Simple way is by converting the Table A [Codes] column data(csv) into separate rows.
Then join with the Table B to get the respective codes. Finally convert the rows to CSV to get result. Try this.
CREATE TABLE #tablea
  ([ID]    INT,[Codes] VARCHAR(100))

INSERT INTO #tablea
VALUES      (1,'A;B'),(2,'D' ),(3,'A;C')

CREATE TABLE #tableB
  ([ID]    VARCHAR(100),[Codes] VARCHAR(100))

INSERT INTO #tableb
VALUES      ('A','Apple'),( 'B','Orange' ),
            ('C','Pear'),('D','Strawberry')

SELECT a.id,
       a.Codes old_code,
       b.Codes Parsed_Codes
INTO   #final
FROM   #tableb b
       JOIN (SELECT id,
                    codes,
                    Split.a.value('.', 'VARCHAR(100)') [new_Codes]
             FROM   (SELECT id,
                            [Codes],
                            Cast ('<M>' + Replace([Codes], ';', '</M><M>')
                                  + '</M>' AS XML) AS Data
                     FROM   #tablea) AS A
                    CROSS APPLY Data.nodes ('/M') AS Split(a)) a
         ON a.new_Codes = b.id

SELECT t1.ID,
       old_code,
       Stuff((SELECT '; ' + CONVERT(VARCHAR, Parsed_Codes)
              FROM   #final b
              WHERE  b.ID = t1.ID
              FOR XML PATH('')), 1, 2, '')
FROM   #final t1
GROUP  BY t1.id,
          old_code

OUTPUT
ID  old_code    Parsed_Codes
--  --------    ------------
1   A;B         Apple; Orange
2   D           Strawberry
3   A;C         Apple; Pear

(Note: temp table can be avoided to avoid code confusion i used temp table)

A: First create this function.. It's used to split a delimited string, into a variable table. Then we would be able to use this function to determine the codes from the other table and return them as one string using the STUFF function.
CREATE FUNCTION [dbo].[fnSplitString]
   (
    @string NVarchar(MAX)
   ,@delimiter Char(1) = ','
   )
RETURNS @t TABLE (string NVarchar(MAX))
AS
BEGIN
   DECLARE @pos Int
   DECLARE @piece Varchar(500)

   IF RIGHT(RTRIM(@string), 1) <> @delimiter
      SET @string = @string + @delimiter

   SET @pos = PATINDEX('%' + @delimiter + '%', @string)
   WHILE @pos <> 0
      BEGIN
         SET @piece = LEFT(@string, @pos - 1)
         INSERT   @t
                  SELECT   @piece

         SET @string = STUFF(@string, 1, @pos, '')
         SET @pos = PATINDEX('%' + @delimiter + '%', @string)
      END

   RETURN
END

Then run the following query...
DECLARE @result TABLE
   (
    [ID] Int
   ,[CommaDelimitedCodes] Varchar(500)
   )
DECLARE @codes TABLE
   (
    [ID] Varchar(500)
   ,[FullNames] Varchar(500)
   )
INSERT   INTO @result
         SELECT   1
                 ,'A;B'
INSERT   INTO @result
         SELECT   2
                 ,'D'
INSERT   INTO @result
         SELECT   3
                 ,'A;C'

INSERT   INTO @codes
         SELECT   'A'
                 ,'Apple'
INSERT   INTO @codes
         SELECT   'B'
                 ,'Orange'
INSERT   INTO @codes
         SELECT   'C'
                 ,'Pear'
INSERT   INTO @codes
         SELECT   'D'
                 ,'Strawberry'

SELECT   *
        ,STUFF((
                SELECT  ', ' + [FullNames]
                FROM    @codes t
                WHERE   id IN (SELECT  *
                               FROM    dbo.fnSplitString(r.[CommaDelimitedCodes], ';'))
               FOR
                XML PATH('')
               ), 1, 2, '') AS taglist
FROM     @result AS r

I created two variable tables to test - but obviously in your case you'd need to replace those with actual field names in your tables.


text:
Q: ActionBarSherlock size? What is ActionBarSherlock size in pixels please ? Specifically the height, I need to design a background and I need this dimension in pixels.
And I have already searched and all I found was sizes in dp.

A: Obviously,
ActionBar actionBar = getSupportActionBar();
int height = actionBar.getHeight();

A: you can convert dp into pixels and use in your project .
I hope it will solve your poblem.. ;)


text:
Q: Find the average of a collection of points (in 2D space) I'm a bit rusty on my math, so please forgive me if my terminology is wrong or I'm overlooking  extending a simple formula to solve the problem.
I have a collection of points in 2D space (x, y coordinates). I want to find the "average" point within that collection. (Centroid, center of mass, barycenter might be better terms.)
Is the average point just that whose x coordinate is the average of the x's and y coordinate is y the average of the y's?

A: There are different types of averages. Only the average of numbers is unambigious. The average you are looking for depends on what you want to use it for.  If you take the avg. x and y coordinates separately, that will give you the center of mass.

A: Yes, you can compute the average for each coordinate separately because $$\frac{1}{n} \sum (x_i,y_i) = \frac{1}{n} (\sum x_i, \sum y_i) = (\frac{1}{n}\sum x_i, \frac{1}{n}\sum y_i)$$


text:
Q: Understanding the `ngram_range` argument in a CountVectorizer in sklearn I'm a little confused about how to use ngrams in the scikit-learn library in Python, specifically, how the ngram_range argument works in a CountVectorizer.
Running this code:
from sklearn.feature_extraction.text import CountVectorizer
vocabulary = ['hi ', 'bye', 'run away']
cv = CountVectorizer(vocabulary=vocabulary, ngram_range=(1, 2))
print cv.vocabulary_

gives me:
{'hi ': 0, 'bye': 1, 'run away': 2}

Where I was under the (obviously mistaken) impression that I would get unigrams and bigrams, like this:
{'hi ': 0, 'bye': 1, 'run away': 2, 'run': 3, 'away': 4}

I am working with the documentation here:  http://scikit-learn.org/stable/modules/feature_extraction.html
Clearly there is something terribly wrong with my understanding of how to use ngrams.  Perhaps the argument is having no effect or I have some conceptual issue with what an actual bigram is!  I'm stumped.  If anyone has a word of advice to throw my way, I'd be grateful.
UPDATE:
I have realized the folly of my ways. I was under the impression that the ngram_range would affect the vocabulary, not the corpus.

A: Setting the vocabulary explicitly means no vocabulary is learned from data. If you don't set it, you get:
>>> v = CountVectorizer(ngram_range=(1, 2))
>>> pprint(v.fit(["an apple a day keeps the doctor away"]).vocabulary_)
{u'an': 0,
 u'an apple': 1,
 u'apple': 2,
 u'apple day': 3,
 u'away': 4,
 u'day': 5,
 u'day keeps': 6,
 u'doctor': 7,
 u'doctor away': 8,
 u'keeps': 9,
 u'keeps the': 10,
 u'the': 11,
 u'the doctor': 12}

An explicit vocabulary restricts the terms that will be extracted from text; the vocabulary is not changed:
>>> v = CountVectorizer(ngram_range=(1, 2), vocabulary={"keeps", "keeps the"})
>>> v.fit_transform(["an apple a day keeps the doctor away"]).toarray()
array([[1, 1]])  # unigram and bigram found

(Note that stopword filtering is applied before n-gram extraction, hence "apple day".)


text:
Q: Reader and Writer Methods Who can explain me the code snippets of "def name" and "def name=()"?
I don't understand why it is defined 2 times.
class Bird < Animal
  def initialize(name, length)
    @name
    @length
  end

  def name
    @name
  end

  def name=(new_name)
    @name = new_name
  end
end

A: One returns a value, one sets a value. Look at the method bodies.
def name
  @name               # return @name
end

def name=(new_name)
  @name = new_name    # set @name to your argument
end

Also, your initialize method does nothing. I assume you want to set those variables to the arguments you are taking.
def initialize(name, length)
    @name, @length = name, length
end

A: These are getter and setter methods
bird = Bird.new("pigeon", length)
 => #<Bird:0x007f93e9b41278>
bird.name
 => "pigeon"
bird.name = 'seagull'
 => "seagull"
bird.name
 => "seagull"

Both of the methods you defined in the class are what's being called here - the call to
bird.name = 'seagull'

is actually syntactic sugar for the method call
bird.name=('seagull')

Of course, the most "rubyish" way to write these methods would be one call to attr_accessor:
class Bird < Animal
  attr_accessor :name

  def initialize(name, length)
    @name = name
    @length = length
  end
end

This will give you both the getter and setter methods for the name attribute

A:
I don't understand why it is defined 2 times.

def name to read value from @name and def name= to write value to @name.
The below is a reader(attr_reader) method
def name; @name; end # shortcut is attr_reader :name

The below is a writer(attr_writer) method
def name=(new_name) ;  @name = new_name ; end # shortcut is attr_writer :name

A very good documentation What is an accessor?

A: These methods are known as "getters" and "setters", because (unsurprisingly), they 'get' or 'set' a variable.
You can also think of one as a 'command,' which will make some change to the data, and one as a 'query,' which will simply report a value (this is a helpful distinction to keep in mind when you are designing your own methods as well).
Ruby includes three class methods that define these getters and setters for you: attr_reader defines the getter, attr_writer defines the setter, and attr_accessor defines both.
You could just interact directly with the instance variable, but in most situations, code is easier to change and reason about when you use methods to access data rather than messing with the data itself.


text:
Q: Why Increasing Collector Voltage Reduces Collector-base Capacitance I'm looking at some transistor radio circuits and the book I'm following makes the following statement with regard to AC gain: "By raising the DC voltage at the collector, the internal collector-base capacitances of the transistor are reduced".
Here's a circuit to help understand what's going on:

Here the author has killed the DC gain by placing an inductor in parallel with R2 whilst leaving the AC gain intact: collector reactance (L1||R2) / emitter reactance (C3||R3).
I have a reasonable grasp of the effect of Miller Capacitance on an inverting amplifier, where the inverted output acts negatively on the input.  What I don't understand is why increasing the collector voltage acts to reduce collector-base capacitance.
Does the increase in current flowing through the collector-emitter junction have anything to do with it?

A: As @FakeMoustache hinted in a comment to your question, the explanation lies in the behavior of a reverse-biased PN junction, because that's what Q1's collector-base junction is in your circuit.
From a macroscopic point of view any reverse-biased PN junction acts like a parallel-plate capacitor whose capacitance (called transition capacitance \$C_T\$) depends inversely on the reverse voltage \$V_R\$. The relationship is not linear, but it is approximately:
$$
C_T = K \dfrac{1}{\sqrt{V_0 + V_R}}
$$
where \$V_0\$ is the voltage gap created by the junction and \$K\$ is a constant.
EDIT
Struggling to remember the exact form of the formula (there are half a dozen of ways of writing down that relationship, depending on which physical parameters of the junction you want to emphasize) I found a more intuitive formula in this Google book:
$$
C_T = \dfrac{C_0}{(1 + V_R)^n}
$$

Note:
That formula has an error in it (dimensional analysis debunks it). Probably \$V_R\$ is meant to be the relative voltage with respect to some reference. I guess the correct formula should be:
$$
C_T = \dfrac{C_0}{\left(1 + \dfrac{V_R}{V_0}\right)^n}
$$

where \$C_0\$ is the capacitance when no bias is applied and \$n\$ depends on how the junction is doped: \$n = \frac 1 2\$ for step-graded junctions, whereas \$n=\frac 1 3 \$ for linearly-graded junctions.
Another interesting article on the subject (tougher semiconductor physics stuff) explains how to derive that relationship (in yet another form!).


text:
Q: Measurability of optimal values and solutions In Theorem 14.37 of Variational Analysis by Rockafellar and Wets, it shows that for any normal integrand $f:T\times\mathbb{R}^n\to\overline{\mathbb{R}}$, the function $p:T\to\overline{\mathbb{R}}$ given by
$$p(t):=\inf~f(t,\cdot)$$
is measurable, and the mapping $P:T\rightrightarrows\overline{\mathbb{R}}$ given by
$$P(t):=\arg\min~f(t,\cdot)$$
is closed-valued and measurable.
According to the authors, many results in the book may be extended to spaces other than Euclidean. I am wondering is there a standard reference for the result if we replace $\mathbb{R}^n$ by a Polish (complete and separable metric) space?

A: I don't know any reference for the exact result you are looking for, but all the ingredients used in the proof by Rockafellar and Wets apply also to Polish spaces. You can find the relevant material in chapter 18 of Infinite Dimensional Analysis by Aliprantis and Border, 2006, as well as chapters III and VII (only the beginning of the latter chapter matters) in Convex Analysis and Measurable Multifunctions by Castaing and Valadier, 1977.


text:
Q: How to set permission to all AD users in Shareoint 2013 I am new to sharepoint 2013, I created sitecollection in Sharepoint 2013 Foundation and have set Read Permission to few specific users.
My requirement is how to set Permission to all Active Directory users of network domain so that they can browse site pages and list etc.

A: If you only have one Site Collection you want to share, then in the Visitor group (with read permission only) add the user Everyone which is equivalent to NT Authoruty\Authenticated Users.

But if you have several Site Collections in the same Web Application, you could add a User Policy on the Web Application, by adding All Users (windows) with full read permission.

A: When assigning/giving permission, type 'Everyone' in the people picker. This will give the permission to all users from AD


text:
Q: MySQL select query with case then and count I have two tables naming campaigns and coupons with the following structure
Campaigns

id
name

1
Campaign 1

2
Multiple Coupon Campaign

Coupons

id
campaign_id
code

1
1
FREDEL

2
2
123-xyz-coupon

3
2
xyw92b-cou

I am trying to get result data set like this

id
name
reference

1
Campaign 1
FREDEL

2
Multiple Coupon Campaign
MULTIPLE

Basically, if a campaign has multiple coupons, it should return MULTIPLE in the reference column, otherwise the coupon code itself.
I've tried something like this
select *, (select CASE WHEN (SELECT count(*) from coupons as temp where temp.id=coupons.id)>1 THEN 'MULTIPLE' ELSE code END AS reference FROM coupons where coupons.campaign_id=campaigns.id limit 1) as reference from campaigns

but the result is not as expected and it shows the first coupon code of both campaigns instead of MULTIPLE for the second one.
Tried the below query as well
select *, (select CASE WHEN count(*)>1 THEN 'MULTIPLE' ELSE coupons.code END FROM coupons where coupons.campaign_id=campaigns.id) as reference from campaigns

and it throws

In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column 'db.coupons.code'; this is incompatible with sql_mode=only_full_group_by

NOTE: I am looking for a sub-query on select and to avoid join clause
Thank you

A: SELECT Campaigns.id,
       Campaigns.name,
       CASE WHEN COUNT(*) = 1
            THEN MAX(Coupons.code)
            ELSE 'MULTIPLE'
            END reference
FROM Campaigns
JOIN Coupons ON Coupons.campaign_id = Campaigns.id
GROUP BY Campaigns.id, Campaigns.name

I was looking for a sub-query select version. – Kalesh Kaladharan

SELECT Campaigns.id,
       Campaigns.name,
       CASE ( SELECT COUNT(*)
              FROM Coupons
              WHERE Coupons.campaign_id = Campaigns.id )
            WHEN 0 THEN 'NONE'
            WHEN 1 THEN ( SELECT Coupons.code
                          FROM Coupons
                          WHERE Coupons.campaign_id = Campaigns.id )
            ELSE 'MULTIPLE'
            END reference
FROM Campaigns
-- HAVING reference <> 'NONE'

A: SELECT
name,
(
    SELECT
        CASE WHEN count(*) > 1 THEN
            'MULTIPLE'
        ELSE
            MIN(code)
        END AS reference
    FROM
        coupons
    WHERE
        coupons.campaign_id = campaigns.id
    GROUP BY
        campaign_id) AS reference
FROM
    campaigns


text:
Q: C# Razor Forms - Inserting Angular Attributes I'm learning C# and Asp.net for about 11 days with background in PHP and PHP related frameworks.
My problem is inserting Angular.js attributes like ng-controller into Razor generated input elements.
The problem is this...
@Html.TextBoxFor(model => model.Name, new { @class = "Form__TextType  Form__TextInput" })

So, this generates an html input[type=text] element with a class attribute. This syntax does not support adding ng-model="someModel" but I can do that with creating a Dictionary that has all the necessary attributes for that element on the server side and putting it as the last argument in TextBoxFor()
That way is not really good although it works. If i want to change an angular attribute, i would have to change the Dictionary object on the server side which could be very error prone.
Is there another way of adding angular attributes to Razor generated elements?

A: It seems that underscores in the HtmlAttributes parameters are converted to hyphens when rendering:
@Html.TextBoxFor(model => model.Name, new { ng_model="someModel" });

A: It looks like this answer to another question might help you solve your problem. If you're on MVC 3, I feel fairly confident the solution described there should work for you as well. If not, let me know -- my mind's still a little fuzzy this morning.


text:
Q: VBA Excel Macro -How to repeat the macro for each sheet? I have pieced together this macro VBA that works perfectly.  However,  I need to run the same code on multiple sheets in the same workbook.  I've tried many things i've seen online (SubWorksheetLoop2, etc) and am having no luck.  The goal is to use this code below and have it run through all the pages of my workbook.  The names of my tabs are 'CLASS II', 'CLASS III', etc.  Please advise!
Option Explicit
Sub InsertBetweenV3()
Dim Area As Range
Dim r As Long, lr As Long, sr As Long, er As Long, i
enter code here
'  turn off screen updating
Application.ScreenUpdating = False
enter code here
'  create an array to fill the 6 inserted rows
i = Array("", "OBS", "VIOL", "VIOL RATE", "STATEMENT", "")
enter code here
enter code here
'  activate/select the first worksheet
Worksheets(1).Activate
enter code here
'  lr is for last row.  Find the last row in column 1 = column A
lr = Cells(Rows.Count, 1).End(xlUp).Row
'  when we are inserting/deleting rows we usually start from the bottom up
For r = lr To 3 Step -1
'  Range("A" & r) is not equal to Range("A" & r - 1)
' If A1535 is not equal to A1534 Then
  If Cells(r, 1) <> Cells(r - 1, 1) Then
' insert 6 rows
 Rows(r).Resize(6).Insert
  End If
Next r

' now that we have inserted six empty rows for each change in STATION
' find the new last row in column 1 = column A
lr = Cells(Rows.Count, 1).End(xlUp).Row
' for each Area in range A1:A new last row
' Area will find each group of rows between the inserted 6 rows
For Each Area In Range("A2", Range("A" & Rows.Count).End(xlUp)).SpecialCells(xlCellTypeConstants).Areas
' with each Area
With Area
'  sr a variable for start row
'  the .Row of the Area is the first row of the Area sr = .Row
  sr = .Row
' er a variable for end row
 ' is equal to sr + count of rows in the Area – 1
 ' er = sr + .Rows.Count – 1

    er = sr + .Rows.Count - 1

' beginning in the blank inserted 6 rows
 ' transpose the i array vertically
    Cells(er + 1, 1).Resize(6).Value = Application.Transpose(i)
' in the first blank row change the interior color to Gray
'  from column 1 = column A to column 46 = column AT
    Cells(er + 1, 1).Resize(, 68).Interior.ColorIndex = 15
' bold the text inserted from the i array
    Cells(er + 2, 1).Resize(4).Font.Bold = True
  ' in the last blank row change the interior color to Gray
  '   from column 1 = column A to column 46 = column AT
    Cells(er + 6, 1).Resize(, 68).Interior.ColorIndex = 15
    ' put the formula in the appropriate cells to do the calculations
Range("G" & er + 2).Formula = "=COUNTIF(G" & sr & ":G" & er & ","">0"")"
Range("G" & er + 3).Formula = "=SUM(COUNTIF(G" & sr & ":G" & er & ", ""<6""),COUNTIF(G" & sr & ":G" & er & ","">9""),-COUNTIF(G" & sr & ":G" & er & ",""=0""))"
Range("G" & er + 4).Formula = "=(G" & er + 3 & "/G" & er + 2 & ")*100"
Range("K" & er + 2).Formula = "=COUNTIF(K" & sr & ":K" & er & ","">0"")"
Range("K" & er + 3).Formula = "=COUNTIF(K" & sr & ":K" & er & ","">32"")
Range("K" & er + 4).Formula = "=(K" & er + 3 & "/K" & er + 2 & ")*100"
Range("I" & er + 2).Formula = "=COUNTIF(I" & sr & ":I" & er & ","">0"")"
Range("I" & er + 3).Formula = "=SUM(COUNTIF(I" & sr & ":I" & er & ",""<4""),-COUNTIF(I" & sr & ":I" & er & ",""=0""))"
Range("I" & er + 4).Formula = "=(I" & er + 3 & "/I" & er + 2 & ")*100"
Range("S" & er + 2).Formula = "=COUNTIF(S" & sr & ": S" & er & ","">0"")"
Range("S" & er + 3).Formula = "=COUNTIF(S" & sr & ": S" & er & ","">235"")"
Range("S" & er + 4).Formula = "=(S" & er + 3 & "/ S" & er + 2 & ")*100"
Range("U" & er + 2).Formula = "=COUNTIF(U" & sr & ":U" & er & ","">0"")"
Range("U" & er + 3).Formula = "=COUNTIF(U" & sr & ":U" & er & ","">104"")"
Range("U" & er + 4).Formula = "=(U" & er + 3 & "/U" & er + 2 & ")*100"
  End With
Next Area
' find the last row in column 1 = column A
lr = Cells(Rows.Count, 1).End(xlUp).Row
' in the following ranges change the number format
Range("G2:G" & lr).NumberFormat = "0.000"
Range("K2:K" & lr).NumberFormat = "0.000"
Range("S2:S" & lr).NumberFormat = "0.000"
Range("U2:U" & lr).NumberFormat = "0.000"
' turn back on screen updating
Application.ScreenUpdating = True
End Sub

A: Worksheets can be identified by their Worksheet .CodeName property, Worksheet .Name property or Worksheet.Index property among others.
A large number of worksheets with a small number of exclusions is probably best sought after with an index based loop.
dim w as long
for w = 1 to worksheets.count
    with worksheets(w)
        if .name <> "Master" and .name <> "Summary" then
            'do some stuff with the worksheet(s)
        end if
    end with
next w

If you have a limited number of specific worksheets, then the .name(s) can be put into an array.
dim v as long, vWSs as variant
vWSs = array("CLASS II", "CLASS III", "CLASS IV")
for v = lbound(vWSs) to ubound(vWSs)
    with worksheets(vWSs(v))
        'do some stuff with the worksheet(s)
    end with
next v

Those are two methods that work well in different situations. The worksheet codename is best for referencing worksheets abstractly; perhaps as a destination to a copy/paste from within one of the above loops.

A: While not as elegant or dynamic as other methods, you could use a simple For loop:
For iCount = 1 to 99 'number of Worksheets
Worksheets(iCount).select
'Insert your code here
Next


text:
Q: NSDate hours in Cocoa I want to calculate the numbers of hours passed on a day from an NSDate object (in UT).
Basically, the example should look something like "17 hours and 31 minutes".
Thanks!

A: You need to use an NSCalendar to extract that date's NSDateComponents.

A: Have a look at Erica Sadun's NSDate utilities. You can either use them in your project or just get some inspiration on how to solve your problem.
But to answer your particular question, this is pretty easy, since NSDates are basically just counting seconds since a reference time. This works:
NSTimeInterval interval = [[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSinceDate:[NSDate dateWithTimeIntervalSinceReferenceDate:0]];
interval = interval / 3600.0f;
float hours;
float fraction;
fraction = modff(interval, &hours);
int minutes = (int)(fraction * 100.0f);
NSLog(@"%d hours and %d minutes", (int)hours, (int)minutes);

Maybe you can get rid of some of the casts.


text:
Q: What does the leakage current graph of the LM13700 OTA stand for? On the datasheet ( http://www.ti.com/lit/ds/symlink/lm13700.pdf ) there is a figure of leakage current- temperature. Is this the output leakage current?

A: This is the worst case CM input & output current at Vo=Vin=36V at abs. max Vcc due to input diodes vs Temp. and output emitter follower unbiased.


text:
Q: Deploy to Azure Storage from VSO with PowerShell Is it possible to use PowerShell to deploy from VSO and/or view the file system that VSO stores the code in?
Recently we have moved our source from a Local TFS to TFService / Visual Studio Online. On the Local TFS we had a PowerShell script that would  deploy the application to Azure Blob.
This is the body of what the script did
1.Create a staging/temporary folder
2.Copy the bin directory after the build,
3.Create a txt file that pulled the version # from the AssemblyInfo.CS file on the build agent (which the customer application would check to see if it needs to update)
4.Create a .sql file that also pulled the version # from the AssemblyInfo.CS file (which updates the customers DB)
5.Zips the copied bin and the created .sql together
6.Uploads the Zip and the txt to Azure Blob
We want to continue to use this script to deploy with while on VSO but the current issue is that I'm running blind on the file paths. I reviewed the build log and found C:\a\src and C:\a\bin, which is a start. I've also been able to run simple commands such as dir/mkdir after the build without errors coming back which I'm assuming means I can manipulate the file system VSO uses to some degree at least.
I Have also posted this question on the msdn site @ http://social.msdn.microsoft.com/Forums/vstudio/en-US/4a951897-52b3-4ee9-91e3-e1412c242207/deploy-to-azure-storage-from-vso-with-powershell?forum=tfsgeneral

A: Figured I'd update this with the solution to my issue.
VSO stores all the project files off the C:\a\ directory.
Source files are located in C:\a\src\
The bin directory is located at C:\a\bin\
In order to get to the correct files in your project, just follow the projects path as you see it in Visual Studio or on VSO.
Example:
Say I have a Project XYZ, which contains my BuildProcessTemplates and a directory named XYZ which holds my branches.
In order to get to the SRC of XYZ, my script would have to target 'C:\a\src\XYZ(projectName)\XYZ(directory)\Version0101(aBranch)\anotherDirectory\theFileIneed.txt'
You can manipulate the VSO directories as you see fit as you have all C.R.U.D. capabilities.
In my case, I create (or recreate) a STAGING folder
$prebuildSTAGING = "C:\a\PrebuildSTAGING"
function Set-Staging
{
    if(!(test-path $prebuildSTAGING))
    {
        mkdir $prebuildSTAGING -Force
    }
    else
    {
        rmdir $prebuildSTAGING -Recurse -Force
        mkdir $prebuildSTAGING -Force
    }
}

This will ensure that I have fresh STAGING folder every time.
I then pick the file that I need, edit it to fit my requirements, then push it back into SRC.
Doing this has allowed me to Automate incrementing the Assembly Version of the application as well as deploy it to Azure without any big headaches along the way.
UPDATE:::
Just wanted to update this again in case anyone is actually packaging their app on VSTS in this fashion ---
The directories have changed ( multiple times now ). The correct path to access the built files is C:\a\1\s\ {YourProjectName}\bin\ {YourBuildPlatform}\  {YourBuildConfiguration}\
Ex:
Solution Name in VS = ABC, Project Name in the solution = XYZ
You have a configuration for XYZ that is named TEST with a Platform of x86
The path to the bin would be
C:\a\1\s\XYZ\bin\x86\TEST