text:
Q: How to inherit all systemwide (native) audio effects into a mediaplayer app? How to inherit and enable (make effectual) current audioeffects (bassboost, equalizer, whatever) from an app playing audiostreams, assuming some other app is at disposal on the device for the manipulation of the native intonation algorithms.
The API documentation is not obvious on how to achieve this.
The following is not working, or is insufficient:
Equalizer equalizer = new Equalizer(0, mediaPlayer.getAudioSessionId());
                        equalizer.setEnabled(true);

                        mediaPlayer.prepare();
                        mediaPlayer.start();

A: I can answer myself. The obvious solution should have been something like:
Equalizer.inheritSystemEq()

I got it to work only the following cumbersome way. Do note that the solution is deprecated, but that the deprecated solution has not been replaced by an alternative API.
Equalizer equalizerSystem = new Equalizer(0, 0) //0 as second parameter is deprecated.
//get current eq settings for global mix out
short band0 = equalizerSystem.getBandLevel((short) 0);
short band1 = equalizerSystem.getBandLevel((short) 1);
short band2 = equalizerSystem.getBandLevel((short) 2);
short band3 = equalizerSystem.getBandLevel((short) 3);
short band4 = equalizerSystem.getBandLevel((short) 4);

equalizerSystem.release();

//copy these "system" values (Set by another equalizer app) into
//another equalizer instance particular for this audio session.

Equalizer equalizer = new Equalizer(0, mediaPlayer.getAudioSessionId());
equalizer.setEnabled(true);
equalizer.setBandLevel((short) 0, band0);
equalizer.setBandLevel((short) 1, band1);
equalizer.setBandLevel((short) 2, band2);
equalizer.setBandLevel((short) 3, band3);
equalizer.setBandLevel((short) 4, band4);

Finally, i.e. subsequently, call mediaPlayer.prepare() or mediaPlayer.prepareAsync, else the equalizerSystem = new Equalizer(0,0) will not work.
Also set in AndroidManifest:
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>

To adopt recurring changes to eq settings, there is additionally a need to detect this via OnParameterChangeListener.


text:
Q: MYSQL How to do a count using a substring and left joining content. I am trying to figure out how to do this query. I have looked all over and with little sucess.
I have 2 tables one is called numbers the other is called area_code
Here is what they look like. I know that there will need to be substring(phoneNumbers,1,3)
Table: numbers
phoneNumber
4062081234
4062345453
2141234454
2101234555

Table: area_code
area_code       state      stateLong
214               TX         Texas
210               TX         Texas
406               MT         Montana

Desired output:
stateLong              count of phoneNumbers per state
Montana                2
Texas                  2

Thank you so much for the help.

A: You can join using left():
select ac.stateLong, count(*)
from area_code ac
    join numbers n on ac.area_code = left(n.phoneNumber,3)
group by ac.stateLong

In your title, you mention the need for an outer join, if you want to return all the states even if they don't have phonenumbers:
select ac.stateLong, count(*)
from area_code ac
   left join numbers n on ac.area_code = left(n.phoneNumber,3)
group by ac.stateLong

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possible to rotate UIAlertController (and Alert) in landscape orientation? I am editing an app where I added a new UIViewController to configure a multiplayer game in one layout.
I have added two buttons for each player (top button, bot button). Each button generates an alert at  the screen (remember it is in landscape orientation ) but the problem is, player 2 do not see the alert rotated, I mean, the alert is supposed to be shown in his orientation, in front of me.
As there any way to do this? I want to rotate an Alert for the player 2  will  not see the information of the alert turned.
Here the alert code I have:
@IBAction func ShowAlert(){
let message = "Test"
let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)

let action = UIAlertAction(title: "OK", style: .Default, handler: nil)

    alert.addAction(action)

    presentViewController(alert, animated: true, completion: nil)
}

A: Here is a way to rotate an alert controller view, although it is not perfect. The controller tries to present based on the orientation and I found that attempting to transform it before it is presented is unsuccessful.
In order to not see "incorrect" orientation initially, you must set the alert to hidden and then make it visible once it is "presented".
let alert // setup

alert.view.hidden = true;
[self presentViewController:c animated:YES completion:^{
    alert.view.transform = CGAffineTransformMakeRotation(M_PI);
    alert.view.hidden = false;
}];

The only outstanding issue I have with this is that after the user interacts with the alert, it flashes back to the initial transformation (orientation dependent). I currently have not found a solution for this, but will update if I ever do.

Alternatively, using a custom "alert" would solve this problem as you would have more control over its view. This is probably the more reliable approach.

A: Here is my solution.
presentViewController with no animation to avoid flash when present the alert controller.
[self presentViewController:alert animated:NO completion:^{
    [alertController.view setTransform: CGAffineTransformMakeRotation(M_PI_2)];
 }];

then create a UIAlertController category named e.g. UIAlertController+Orientation,
hide the view in viewWillDisappear to avoid flash back when dismiss the alert controller.
#import "UIAlertController+Orientation.h"

@implementation UIAlertController (Orientation)

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.view setHidden:YES];
}

- (BOOL) shouldAutorotate {
    return NO;
}

@end


text:
Q: OptionParse in Ruby and params not starting with '-' I want to have params like this:
program dothis --additional --options

and:
program dothat --with_this_option=value

and I can't get how to do that. The only thing I managed to do is to use params with -- at the beginning.
Any ideas?

A: To handle positional parameters using OptionParser, first parse the switches using OptionParser and then fetch the remaining positional arguments from ARGV:
# optparse-positional-arguments.rb
require 'optparse'

options = {}
OptionParser.new do |opts|
  opts.banner = "Usage: #{__FILE__} [command] [options]"

  opts.on("-v", "--verbose", "Run verbosely") do |v|
    options[:verbose] = true
  end

  opts.on("--list x,y,z", Array, "Just a list of arguments") do |list|
    options[:list] = list
  end
end.parse!

On executing the script:
$ ruby optparse-positional-arguments.rb foobar --verbose --list 1,2,3,4,5

p options
# => {:verbose=>true, :list=>["1", "2", "3", "4", "5"]}

p ARGV
# => ["foobar"]

The dothis or dothat commands can be anywhere. The options hash and ARGV remains the same regardless:
 # After options
 $ ruby optparse-positional-arguments.rb --verbose --list 1,2,3,4,5 foobar

 # In between options
 $ ruby optparse-positional-arguments.rb --verbose foobar --list 1,2,3,4,5


text:
Q: How can i get data in Servlet, which is Sending from Android app? I am new in android, i have searched for solution, but i could not get the suitable one, that s why i am
posting  this Qn,
I can't get any value in servlet,And no Errors in LogCat, Some Toast are in my code to check execution flow, The all Toast will work only in the first attempt, If i click my button second time, Only the first Toast will work,
Please help me to find a solution,
This is my android code
public void onClick(View v) {
    final   String u=txt_name.getText().toString();
    final   String p=txt_pswd.getText().toString();
    Toast.makeText(getApplicationContext(), u+p,Toast.LENGTH_LONG).show();
    new AsyncTask<String , Void, Void>() {

        @Override
        protected Void doInBackground(String... params) {

            try{
                //Log.d("Asynctask", ""+params);
                //Looper.prepare();

                URL url=new URL("http://10.0.2.2:8080/LoginExample/LoginServlet");

                HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection();
                urlConnection.setDoInput(true);
                urlConnection.setDoOutput(true);
                urlConnection.setRequestMethod("GET");
                //Toast.makeText(getApplicationContext(), "connecting..",Toast.LENGTH_LONG).show();
                urlConnection.connect();
                //Toast.makeText(getApplicationContext(), "connected",Toast.LENGTH_LONG).show();
                urlConnection.getOutputStream().write(("key1="+u+"&key2="+p).getBytes());
                //Toast.makeText(getApplicationContext(), "sending....",Toast.LENGTH_LONG).show();
            }catch(Exception e)
            {
                System.out.println("ERROR IN URL CONNECTION---"+e);
            }

            //Looper.loop();
            return null;
        }
    }.execute();
});

And this is my servlet,
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
                   throws ServletException, java.io.IOException {

        try
        {
            System.out.println("-----servlet--------------");
            // UserBean user = new UserBean();
            String uname=request.getParameter("key1");
            String password=request.getParameter("key2");

            System.out.println("uname ins ervlet==="+uname);

            System.out.println("password in servlet==="+password);
        }
        catch (Throwable theException)
        {
            System.out.println(theException);
        }

    }

}

A: AsyncTask is not written correctly. There is NO NEED to write Looper in doINBAckground. In ideal cases,doInBackground don't deal with UI elements. Remove Toasts statement too. Use Log class to print log.
You request part seems wrong. If its get tye request try
URL url=new URL("http://10.0.2.2:8080/LoginExample/LoginServlet?"+"key1="+u+"&key2="+p);

Also check Internet permission in your manifest file.
Provide Stacktrace of your error.

A: This is my solution,
public void onClick(View v) {
    final   String u=txt_name.getText().toString();
    final   String p=txt_pswd.getText().toString();
        Toast.makeText(getApplicationContext(), u+p,Toast.LENGTH_LONG).show();
        new AsyncTask<String , Void, Void>() {

            @Override
            protected Void doInBackground(String... params) {

                try{

                        URL url=new URL("http://10.0.2.2:8080/LoginExample/LoginServlet?"+"key1="+u+"&key2="+p);

                    HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection();

                    urlConnection.setRequestMethod("GET");
                    urlConnection.connect();
                    BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                    String result = br.readLine();
                    Log.d("MainActivity", result);

                }catch(Exception e)
                    {
                    e.printStackTrace();
                    System.out.println("ERROR IN URL CONNECTION---"+e);
                    }

            //  Looper.loop();
                return null;
            }
        }.execute();
    }


text:
Q: Find opus files on Android Since recently I'm using the OPUS file format in my music library.
Even though Android seems to support the OPUS file format natively there are not many music players listing music tracks encoded in this format.
I've wanted to create my own simple music player listing OPUS encoded audio tracks. However I couldn't figure out how to find the files on the system.
The best way would be to use a query/cursor. However OPUS files are just ignored:
Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                                           null, null, null, null);

System.out.println(cursor.getCount()); //The size of my music library without .opus files

while (cursor.moveToNext()) {
  //.mp3 and .flac files but no .opus files
  System.out.println(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)));
}

Then I tried to access my music files manually but without success:
File musicDirectory = new File(getExternalFilesDir(Environment.DIRECTORY_MUSIC).toURI());
//This directory seems to be empty, length: 0
System.out.println(musicDirectory.list().length);

And:
File file = new File(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI.getPath());
//Exists: false
System.out.println(file.exists());

Has anybody got any idea what the problem is, or know any workarounds?
Any help would be appreciated.

A:
The best way would be to use a query/cursor. However OPUS files are just ignored

If your Opus files are of a similar vintage as your MP3 and FLAC files (i.e., they have been on your test device for a long time), then MediaStore might not know to automatically index them.

Then I tried to access my music files manually but without success:

There are few problems here:

*

*The File constructor and toURI() stuff is pointless, as getExternalFilesDir() returns a File

*That File points to your app-specific portion of external storage, so unless your Opus files are there, this File will not list them

*If you wanted to switch to the device-level music directory (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)), that is not available to you on Android 10 and higher

And:

A Uri is not a file. Calling getPath() on a Uri whose scheme is anything other than file is pointless, and the scheme for MediaStore.Audio.Media.EXTERNAL_CONTENT_URI is content

know any workarounds?

You could try your MediaStore query, but:

*

*Constrain based on MIME type, and

*Use MediaStore.Files instead of MediaStore.Audio
That too will not work on Android 10 and higher, but if it worked it would be faster than scanning the music directory tree yourself.
And unless MediaStore.Audio starts indexing Opus files, there is no great solution for you on Android 10 and higher. The best would be ACTION_OPEN_DOCUMENT_TREE, so the user can point you to a document tree containing Opus files, and you would scan that tree for documents with the Opus MIME type. That might work, but it may also be slow.


text:
Q: Show message in div in submit form I'm trying to show() a div whenever the user submits the form. The whole site is one page. Currently when you submit it, the form is submitted, then .confirmation div shows up for about 1 second and then it goes away, the page refreshes and the div is gone.
This is my HTML
    <form id="contactform" class="col s12 l6" action="mailer.php" method="post" >

Thanks for contacting us. We will be in touch with you shortly.

          <input name="inputName" type="text" class="validate">
          Name

          <input name="inputEmail" type="email" class="validate">
          Email

          <input name="inputPhone" type="text" class="validate">
          Phone

          <textarea class="materialize-textarea" name="inputMessage"></textarea>
          Message

          <button id="submit-button" class="btn waves-effect waves-light cyan col s6" type="submit">Submit

          </button>

    </form>

CSS
.confirmation {
  display: none;
}

This is my PHP
    <?php
    /* Set e-mail recipient */
    $myemail = "krm218@gmail.com";

    /* Check all form inputs using check_input function */
    $name = $_POST['inputName'];
    $email = $_POST['inputEmail'];
    $phone = $_POST['inputPhone'];
    /* $inquiry = $_POST['inputInquiry']; */
    $message = $_POST['inputMessage'];

    /* Let's prepare the message for the e-mail */

    $subject = "Cleaning Services Contact or Estimate";

    $message = "

    Victorias Cleaning Services Contact Form

    Name: $name
    Email: $email
    Phone: $phone

    Message:
    $message

    ";

    /* Send the message using mail() function */
    mail($myemail, $subject, $message);

    /* Redirect visitor to the thank you page */
    header('Location: index.html#contact');

    exit();
    ?>

and a scripts.js file
$('#submit-button').click(function(){
    $(".confirmation").show();
});

Thanks in advance!!

A: Try this in scripts.js:
$('#contactform button[type=submit]').click(function(e){
  e.preventDefault();
  $('.confirmation').show();
  setTimeout(function(){
    $('#contactform').submit();
  }, 5000);
});

5000 means it will show the message for 5000 milliseconds (5 seconds) then submit the form.
(All the other files can stay like they originally were)

A: When the page refreshes, that is the form submitting. If you want it to be delayed, you can use preventDefault and window.setTimeout(), or you can send the form over AJAX and redirect the page later. Good luck!


text:
Q: Single Sign On using Identity Server 4 I have a question about the SSO flow.
Let's say we have 2 MVC applications as clients and an authentication provider
Client 1 has a cookie lifetime of 40 minutes.
Client 2 has a cookie lifetime of 10 minutes (maybe it's more strict for security reasons)
The expiration for the cookies is sliding, e.g. if a user logs in at 12:00 the cookie will expire in 12:40, however if the user makes a call to a page at 12:05 the expiration will subsequently be at 12:45
Now, what we want to do is implement SSO using Identity Server 4

*

*User tries to login to Client A

*User is redirected to Identity Server

*User logs in on IS - User is redirected back to Client A with tokens

then

*

*User tries to login on Client B

*User is redirected on Identity Server

*Identity Server cookie exists

*User is redirected back to Client B with tokens

What is the correct approach regarding the Identity Server cookie expiration?
For example, upon logging in to the second client, the Identity Server cookie is already set to be 40 minutes long from the previous login. This is a problem due to the need of the second client for a cookie expiration time of 10 minutes.


text:
Q: error upgrading System.Net.Http I am currently trying to upgrade many solutions that use a beta version of System.Net.Http (-v 2.0.20126.16343) to version 2.0.20710.0.
I also have a reference to System.Json -v 4.0.20126.16343, however, when I reload the website in a browser I get the error.
Could not load file or assembly 'System.Json, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.

I have checked and the files are in the packages folder, and the bin folder is being populated.
Anyone have any ideas?

A: The issue here was actually in the cproj file. It just needed to have the reference to the dll updated to the new version number.


text:
Q: How to separate a data frame based on a column's range of values with pandas? This is a bit of weird question, but I have been importing property data from an api in the format of a json file within python. I then use Pandas to convert the json into a dataframe.
I am having trouble manipulating the data within the data frame. My current data is set up as to be formatted like this table.

Each Property is assigned a name and a property id and address, and there is a record for every unit within a property. Ideally, I would like to create multiple data frames separated by property id, such that it would look like this.

My only problem here is that due to their being some organization issues, there are about 100 different property ids, and none of the ids are in order. They all have a random number from 1 - 1000.
Is there a way to automatically separate dataframes based on property id by using some sort of unique identifier combined with a for loop ?
I don't really know how to approach the scenario. Thanks!

A: Try this:
list_of_dataframes = [x for _, x in df.groupby(df['Property Id'].ne(df['Property Id'].shift(1)).cumsum())]

Now list_of_dataframes is a list of dataframes, where each dataframe contains the rows where the Property Id was consecutively the same. So Property Ids 1 1 1 9 9 9 1 1 1 would return 3 dataframes, one containing the first three 1's, the second containing the next three 9's, and the last containing the last three 1's.
If don't want the groups to be based on the consective order (i.e., you want 1 1 1 9 9 9 1 1 1 to be two dataframes, the first containing all six 1's, and the second containing the three 9's), you can do this:
list_of_dataframes = [x for _, x in df.groupby(df['Property Id'])]


text:
Q: Resetting the Authorization policies on run-time I'm trying to bring down the size of my JWT token which internally gets the claims by User Role. For that to happen I created policies with the name same as of the Claim name and set the policy.RequireRole property in my policy registration like this:
 public static IServiceCollection RegisterPolicies(this IServiceCollection services, IClaimApplication claimApplication)
        {

            var applicationClaim = new ApplicationClaim();

            services.AddAuthorization(async options =>
            {
                var ClaimList = await claimApplication.GetList(applicationClaim);
                foreach (var item in ClaimList)
                {
                    //Commented this code for Testing in development env:

                    //if (item.ClaimType == "Inventory.Get")

                    if (item.ClaimType == "some claim")
                    {

                        options.AddPolicy(item.ClaimCode, policy => policy.RequireRole("admin","test"));

                    }
                    else
                    {
                        options.AddPolicy(item.ClaimCode, policy => policy.RequireClaim(item.ClaimCode));
                    }
                }
            });

            return services;
        }

this works fine as it brings down the token size, as now I only have to return user roles and I bind the policies with claims having some role from the database.
this call is registered through the database, but the problem is as this is policy is only registered on application startup, any addition to the claims for that user role won't take effect until the application startup.
I somehow need to dynamically reset some policy based upon the change in the database but had no luck finding something that might help me with this. can someone please point me in the right direction?
I can't make this use-case work with custom Policy Requirements either


text:
Q: Instantiate XMLConfiguration from spring I'm trying to instantiate XMLConfiguration from spring appcontext, my configuration file is in
src/main/resources/

But when I try to pass the constructor args like this :
<constructor-arg type="java.lang.String" value="classpath:/config.xml"/>

or
<constructor-arg type="java.lang.String" value="classpath:config.xml"/>

The spring cannot locate the file :

org.apache.commons.configuration.ConfigurationException: Cannot locate configuration source classpath:/config.xml

But I can see it inside the war, in
\WEB-INF\classes

Can anyone think what I'm doing wrong ?

A: classpath:/config.xml is Spring-style, and Commons Config doesn't know what that means.  You need to pass a path to XMLConfiguration that it knows how to interpret.  The javadoc link that you posted suggests that XMLConfiguration requires an actual file path, not a classpath reference.


text:
Q: Is $3(2k+1)(2^{2k+1}-1)>(2^{k+3}-1)(2^{k+1}-1)$? Let $k$ be an integer. I need to prove that:
 $$3(2k+1)(2^{2k+1}-1)>(2^{k+3}-1)(2^{k+2}-1)$$
where $k>a$ for a suitable $a$.
thanks in advance.

A: For any $k\geq 1$ we have:
$$(2^{k+3}-1)(2^{k+2}-1)=2^{2k+5}-3\cdot 2^{k+2}+1\leq16(2^{2k+1}-1)$$
and for any $k\geq 3$ we have:
$$3(2k+1)\geq 16,$$
hence we have to check only the cases $k=1,2$.

A: The right side simplifies to $6 \times 2^k + 1$. Replacing $x = 2^k$ means the equation is $3(2k+1)(2x^2-1) > 6x + 1$.
$2x^2-1 > 6x + 1$ for $x \ge 4$, so checking cases from here is sufficient


text:
Q: Add points if someone checks checkbox html I need help, I want this page to add one point on every check, but this code isn't doing what i quite expect.. Even i check all 3 its only adds 1 ( I know its because of if else logic ), but is there any way around it, or any solution:
Here's my Code:
app.get('/', (req, res) => {

res.send(`
        <form method='POST' action='/test'>
            Work<input type="checkbox" name="a1" />

            Gym<input type="checkbox" name="a2" />

            Go out<input type="checkbox" name="a3" />

            <input type='submit' value='Submit' />

        </form>
        `)
})

var points = 0

app.post('/test', (req, res) => {

    const a1 = req.body.a1
    const a2 = req.body.a1

    if (a1) {
        points += 1
    }
    else if (a2) {
        points += 1
    }
    else if (a3) {
        points += 1
    }

    console.log(points)
    res.redirect('/')
})

You can also tell me jquery but i should be able to add points to a specific varible in backend


text:
Q: python-social-auth tutorial or project social-auth (facebook) in django project, but I have a problem. Now I can loging by Facebook but account (email) must exist in User table. But I cannot log in when User not exist in db. Next question is about some good python-social-auth tutorial or maybe some body can show me some code how to do it. Ps I read official doc but I still have a problem

A: The docs for python-social-auth have a section for Django: http://psa.matiasaguirre.net/docs/configuration/django.html.
By default, you will have separate Facebook users and separate Django users.
Note that your settings.py you should have something like this:
AUTHENTICATION_BACKENDS = (
  'social_auth.backends.facebook.FacebookBackend',
  'django.contrib.auth.backends.ModelBackend',
)

That means you have different backends creating different users.  You would have to do some work to synchronize them.


text:
Q: HDF5 file to diagram in python I'm trying to generate some diagrams from an .h5 file but I don't know how to do it.
I'm using pytables, numpy and matplotlib.
The hdf5 files I use contains 2 sets of data, 2 differents curves.
My goal is to get diagrams like this one.
This is what I managed to do for the moment:
import  tables  as tb
import  numpy   as np
import  matplotlib.pyplot   as plt

h5file = tb.openFile(args['FILE'], "a")
for group in h5file.walkGroups("/"):
     for array in h5file.walkNodes("/","Array"):
          if(isinstance(array.atom.dflt, int)):
               tab = np.array(array.read())
               x = tab[0]
               y = tab[1]
               plt.plot(x, y)
               plt.show()

x and y values are good but I don't know how to use them, so the result is wrong. I get a triangle instead of what I want ^^
Thank you for your help
EDIT
I solved my problem.
Here is the code :
fig = plt.figure()

tableau = np.array(array.read())
x = tableau[0]
y = tableau[1]
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)

ax1.plot(x)
ax2.plot(y)

plt.title(array.name)
plt.show()


text:
Q: TikZ grid - filling a cell by directly accsessing it I discovered TikZ the day before yesterday and now I try to create a grid with 10 columns and 10 rows. It would be convenient to fill the grid boxes with color in a constant and clear manner. I hope to do this from outside of the grid matrix.
I am able to name the matrix with (M). In the user manual of pgf I can only find one instance where the naming command is used.
In the picture below you can see a horizontal black line which resulted from directly accessing two nodes.
How could I use the command 'fill' instead of 'draw', in order to fill one cell in a clear manner?
Thank you.

\documentclass{article}
\usepackage{tikz}

\usetikzlibrary{matrix}

\begin{document}

\begin{tikzpicture}
    \matrix[matrix of nodes, nodes={draw,minimum size=1cm}, nodes in empty cells,column sep=-\pgflinewidth, row sep=-\pgflinewidth](M){
 |[fill=green]|  &  |[fill=red]|     & |[fill=blue]| & |[fill=purple]|  \\
 |[fill=yellow]| &  |[fill=orange]|  & |[fill=green]| & |[fill=brown]|  \\
      };

\draw[black] (M-1-1) -- (M-1-3) ;

\end{tikzpicture}

\end{document}

A: Welcome to TeX.SE! If I correctly understood you, than you afer the following:

Edit:
What embarrassing, My previous explanation was wrong, so I delete it and recover last example from first solution . Yo have correct setting of matrix ...
In the first attempt I overlooked the problems with drawing cells' borders. Concerning it, use of rectangle cover borders. So visually correct result you get only if rectangle fill is black(as are cells' borders), at other fill colors, borders of colored cells are covered byfill. This can be avoided by use fit` library and painting cells only inside borders:
\documentclass[border=3.141592, varwidth]{standalone}
\usepackage{tikz}
\usetikzlibrary{fit,
                matrix}

\begin{document}
    \begin{tikzpicture}
\matrix (m) [matrix of nodes,
             nodes={draw, minimum size=1cm},
             nodes in empty cells,
             column sep=-\pgflinewidth, % <---
             row sep=-\pgflinewidth]    % <---
{
    &   &   &   \\
    &   &   &   \\
};

\node[fill, inner sep=-\pgflinewidthpt, fit=(m-2-3)] {}; % <---
    \end{tikzpicture}

    \begin{tikzpicture}
\matrix (m) [matrix of nodes,
             nodes={draw, minimum size=1cm},
             nodes in empty cells,
             column sep=-\pgflinewidth,  % <---
             row sep=-\pgflinewidth]     % <---
{
    &   &               &   \\
    &   & |[fill=teal]| &   \\
};
    \end{tikzpicture}
\end{document}


text:
Q: how to automate cygwin and mintty I currently have this under my shortcut
C:\cygwin\bin\mintty.exe -i /Cygwin-Terminal.ico -
after that is run i have to type in
cd x:ENTER
then i run a curl script which does not change.
I tried to automate it by running the following command but it does not seem to work
my SH file
#!/bin/bash

cd x:
curl http://thedomain.com/update.json --connect-timeout 10000 --max-time 10000 --data-binary @jsonfilename -H 'Content-type:application/json;charset=utf-8;X-Vendor-Email=myemail@.com;'

this is what i run in CMD
mintty.exe --exec 'c:/cygwin/bin/test.sh'

cygwin popup for 2 seconds and disappear.
please help
update
New error
$ /bin/test.sh
      0 [main] bash 12000 child_info_fork::abort: cygreadline7.dll: Loaded to different address: parent(0x3B0000) != child(0x320000)
/bin/test.sh: fork: retry: Resource temporarily unavailable
      0 [main] bash 12052 child_info_fork::abort: cygreadline7.dll: Loaded to different address: parent(0x3B0000) != child(0x2B0000)
/bin/test.sh: fork: retry: Resource temporarily unavailable
      0 [main] bash 9304 child_info_fork::abort: cygreadline7.dll: Loaded to different address: parent(0x3B0000) != child(0x3A0000)
/bin/test.sh: fork: retry: Resource temporarily unavailable
      0 [main] bash 9036 child_info_fork::abort: cygreadline7.dll: Loaded to different address: parent(0x3B0000) != child(0x3A0000)
/bin/test.sh: fork: retry: Resource temporarily unavailable
      0 [main] bash 9588 child_info_fork::abort: cygreadline7.dll: Loaded to different address: parent(0x3B0000) != child(0x3C0000)
/bin/test.sh: fork: Resource temporarily unavailable

A: for whoever is interested in this .. here is the solution
create a shortcut in windows for Mintty with the following taret
Assuming your shell file is located in c:\cygwin\bin
C:\cygwin\bin\mintty.exe /bin/bash -l -e '/cygdrive/c/cygwin/bin/test.sh'
once you have the shortcut working, you can do a windows task scheduler and take it from there.
Windows 7 Pro:
Create a basic task with Windows Task Scheduler to start DAILY and go through all the steps.  Once you have created the task, go to Properties and then go to TRIGGERS tab and click EDIT
under ADVANCED SETTINGS frame, you'll se REPEAT TASK EVERY.... self-explanatory from there.

A: Your command is telling mintty to start up and run your script, which is what it proceeds to do, then exit. That "popup" as you call it, is the terminal opening, running the command you passed it, and then exiting since it has done its job.

A: Does mintty.exe evaluate arguments to --exec with a filesystem root of c:\ or the cygwin environment /?  Try this.
mintty.exe --exec '/bin/test.sh'

or
mintty.exe --exec '/cygdrive/c/cygwin/bin/test.sh'

Also, if you haven't done so, you should chmod 755 /bin/test.sh to make it executable.


text:
Q: nested series expansion I have to invert the following matrix in which the functions U[t,x,y,r] and K[t,x,y,r] and all their derivatives are "small";
matr={{(1 - 2*U[t, x, y, r]/c^2 - 2*D[K[t, x, y, r], t]/c), -D[
    K[t, x, y, r], x], -D[K[t, x, y, r], y], -D[K[t, x, y, r],
    r]}, {-D[K[t, x, y, r], x], -(1 + 2*U[t, x, y, r]/c^2), 0,
  0}, {-D[K[t, x, y, r], y], 0, -(1 + U[t, x, y, r]/c^2),
  0}, {-D[K[t, x, y, r], r], 0, 0, -(1 + 2*U[t, x, y, r]/c^2)}}

furthermore I need the final expression only up to the order c^-2. I am using the code:
Simplify[Series[
  Series[Series[
    Series[Series[
      Series[Inverse[matr], {c, Infinity, 2}], {D[K[t, x, y, r], r],
       0, 1}], {D[K[t, x, y, r], y], 0, 1}], {D[K[t, x, y, r], x], 0,
     1}], {U[t, x, y, r], 0, 1}], {D[K[t, x, y, r], t], 0, 1}]]

The problem is that inevitably, there are terms of the type:
D[K[t,x,y,r],t]*D[K[t,x,y,r],x]

and so on.
Is it possible to tell Math. that those terms are small too, without adding them to the series?
Even better: how can I simplify my nested series expansion?
EDIT
To answer  @Daniel Lichtblau
The "small" terms must be at first order.
There are no problem in terms of the type c.small=TooSmallToKeep.

A: The factors $c^2$ should be no problem, so I'll focus on the question how we can tell Mathematica that all the functions are small. It boils down to introducing a bookkeeping parameter $\epsilon$ that is eventually set to $1$ after it has served its purpose of keeping track of powers of the small quantities:
replacementRule = {U :> (ϵ u[##] &),
   K :> (ϵ k[##] &)};

matr = ReleaseHold[
   Hold[
     {{(1 - 2*U[t, x, y, r]/c^2 - 2*D[K[t, x, y, r], t]/c), -D[
         K[t, x, y, r], x], -D[K[t, x, y, r], y], -D[K[t, x, y, r],
         r]}, {-D[K[t, x, y, r], x], -(1 + 2*U[t, x, y, r]/c^2), 0,
       0}, {-D[K[t, x, y, r], y], 0, -(1 + U[t, x, y, r]/c^2),
       0}, {-D[K[t, x, y, r], r], 0, 0, -(1 + 2*U[t, x, y, r]/c^2)}}
     ] /. replacementRule
   ];

Normal[Series[Inverse[matr], {ϵ, 0, 1}]] /. ϵ ->
   1 // MatrixForm

the replacementRule takes your function names and replaces them with new functions (of the same number of arguments (##) using lower case names. But these new functions are multiplied by the parameter ε.
To do the replacement, I take your initial definition and wrap it in Hold so  the derivatives aren't done until the renaming has occurred, at which time ReleaseHold allows the evaluation. This is something you could of course also do by hand, but maybe not if your real application is larger.
Then the Series expansion requires only a single expansion, in terms of ε. You have to use Normal to convert the SeriesData object to a "normal" expression before finally setting ε to 1.
This is closely related to the question Multivariable Taylor expansion does not work as expected, except that here we have to work with functions.


text:
Q: Getting "Authentication Credentials Were not Provided" when testing DRF endpoint on Locust I am trying to load test an endpoint that allows users to create posts using locust, it is worth mentioning that users need to be authenticated before they can access this endpoint.
Problem:
When I hit the endpoint using locust, I keep getting the error saying "Authentication provided were not provided" even though I have done so and I have also configured my endpoint to accept token (I am using the default DRF token feature). Any idea what I am doing wrong? any help will be appreciated. Below is my code:
Locust file
class ListPostUser(HttpUser):
    wait_time = between(1, 5)

    @task(3)
    def create_post(self):
        data = {
            "title": "This is another random title",
            "body": "This is the body of a randomly titled post"
        }
        headers = {
            "Authorization": "Token 508e650b0ca1613818939089190a1661a75865b1"
        }
        response = self.client.post("blog/create", json=data, headers=headers)

        print(response)
        print(response.json())

    @task
    def comment_detail(self):
        self.client.get("blog/comment/1")

    @task(2)
    def post_detail(self):
        self.client.get("blog/post/1")

    def on_start(self):
        self.client.post("login/", json={"username": "username", "password": "mypassword"})

views file
class CreatePostAPI(APIView):
    permission_classes = (IsAuthenticated, )

    def post(self, request):
        serializer = CreatePostSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save(user=self.request.user)
            return Response(serializer.data, status=status.HTTP_200_OK)

I should also note that the endpoint works fine on POSTMAN, I only get the error when I am load testing with locust

A: Not sure if this will help you find the real issue, but you can investigate the exact payload sent by examining response.request, like this:
print(response.request.headers) print(response.request.data)

A: I finally found a solution to the issue, All I needed to do was add TokenAuthentication to the list of default authentication classes in settings.py file
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES':
    [
        'rest_framework.authentication.TokenAuthentication',
        ...
    ],
}


text:
Q: Print out the distribution of words in multiple files I am trying to make an executable that will take in any number of text files and give an output that is the distribution of words by number of occurrences. This is to be done in bash scripting, and what I have so far is:
#!/bin/bash
y=$(cat $* | wc -w)

cat $* | tr ' ' '//' |  tr '[:upper:]' '[:lower:]' | tr -d '[:punct:]' |
grep -v '[^a-z]'| sort | uniq -c | sort -rn | head -$y

I get an error trying to set y and I can't figure out how to get head to print out every word otherwise.
Is there a better way to print it out?

A: Why run head at all?  There's no guarantee that there will be as many words as there are words in the files; indeed, it is practically guaranteed that there won't be (since there'll be some repeated words).  And if you want to see all the data, then show all the data; don't filter the output from sort -nr.
The first tr only needs one slash, I think.  Normally, you'd map blanks and punctuation to newlines (with a -s option to tr to squeeze adjacent newlines to one).  The slashes from the first tr count as punctuation in the third tr, so it isn't obvious what you're up to there.  I think I'd expect to see something like:
cat "$@" |
tr -cs '[:alpha:]' '\n' |      # Convert any non-alpha character to newline
tr '[:upper:]' '[:lower:]' |   # Case-convert to lower case
sort | uniq -c | sort -nr

Note the use of "$@" rather than $*; there's no difference when the file names you specify don't contain blanks (newlines, tabs, etc); when they do, the "$@" form is correct and $* is not, so you may as well always use "$@".  It is correct far more often than $* is.
For some C source code I had lying around, the output from the script was:
 246 n
 217 i
 153 int
 141 list
 124 if
 118 t
 103 char
  99 a
  97 size
  90 buffer
  89 context
  82 d
  81 void
  79 include
  79 h
  78 s
  65 for
  62 j
  55 ptr
  54 r
  54 const
  53 static
  53 sem
  51 pthread
  49 z
  49 oldneedle
  49 err
  47 to
  47 return
  46 mutex
  44 printf
  43 error
  43 c

Note that the word 'h' appears as often as the word 'include'; there's a reason for that!  The word t appears a lot, but that's because, for example, size_t is treated as two words by the filtering.  Preserving underscores is possible; change the first tr to use '[:alpha:]_' (note the underscore).  You eliminated digits, but you can keep those too if you want.


text:
Q: Permutations of 3 elements within 6 positions: one equal neighbour Taking into account the answers in this post Permutations of 3 elements within 6 positions, I think it's worth to open a new discussion about how ordering the elements.
The first condition was to have always sequences with alternate elements:
#   Var1 Var2 Var3 Var4 Var5 Var6     V7
# 1    b    c    a    b    c    a bcabca
# 2    c    a    b    c    a    b cabcab
# 3    a    b    c    a    b    c abcabc
# 4    b    a    b    c    a    b babcab
# 5    c    b    c    a    b    c cbcabc
# 6    a    c    a    b    c    a acabca

However, the rest of the permutations could have value even if there is one coincidence of elements in like-neighbour restriction. For instance:
    #   Var1 Var2 Var3 Var4 Var5 Var6 Coincidence
    # 1    b    b    a    b    c    a     -->[bb]
    # 2    c    c    b    c    a    b     -->[cc]
    # 3    a    b    c    a    a    c     -->[aa]
    # 4    b    a    c    c    a    b     -->[cc]

Is it possible to use expand.grid for that too?

A: If it's "only one more", then I suggest the simplest way to allow it is to force it.
Using the start from the previous question:
r <- replicate(6, seq_len(length(abc)-1), simplify=FALSE)
r[[1]] <- c(r[[1]], length(abc))

We now copy this single list (that is passed to expand.grid) and replace each of the 2nd through last elements with 0. Recall that we are using these numbers with cumsum to change from the previous value, so replacing 1:2 with 0 means that we are forcing the next element to be the same.
rs <- lapply(seq_len(length(r)-1) + 1, function(i) { r[[i]] <- 0; r; })
#            ^^^^^^^^^^^^^^^^^^^^^^^^ or: seq_len(length(r))[-1]
str(rs[1:2])
# List of 2
#  $ :List of 6
#   ..$ : int [1:3] 1 2 3
#   ..$ : num 0             <--- the second letter will repeat
#   ..$ : int [1:2] 1 2
#   ..$ : int [1:2] 1 2
#   ..$ : int [1:2] 1 2
#   ..$ : int [1:2] 1 2
#  $ :List of 6
#   ..$ : int [1:3] 1 2 3
#   ..$ : int [1:2] 1 2
#   ..$ : num 0             <--- the third letter will repeat
#   ..$ : int [1:2] 1 2
#   ..$ : int [1:2] 1 2
#   ..$ : int [1:2] 1 2
### other rs's are similar

We can verify that this works as we think it should:
# rs[[1]] repeats the first 2
m <- t(apply(do.call(expand.grid, rs[[1]]), 1, cumsum) %% length(abc) + 1)
m[] <- abc[m]
head(as.data.frame(cbind(m, apply(m, 1, paste, collapse = ""))), n=3)
#   Var1 Var2 Var3 Var4 Var5 Var6     V7
# 1    b    b    c    a    b    c bbcabc
# 2    c    c    a    b    c    a ccabca
# 3    a    a    b    c    a    b aabcab

# rs[[3]] repeats the 3rd-4th
m <- t(apply(do.call(expand.grid, rs[[3]]), 1, cumsum) %% length(abc) + 1)
m[] <- abc[m]
head(as.data.frame(cbind(m, apply(m, 1, paste, collapse = ""))), n=3)
#   Var1 Var2 Var3 Var4 Var5 Var6     V7
# 1    b    c    a    a    b    c bcaabc
# 2    c    a    b    b    c    a cabbca
# 3    a    b    c    c    a    b abccab

From here, let's automate it by putting all of these into one list and lapplying them.
rs <- c(list(r), rs)
rets <- do.call(rbind.data.frame, c(stringsAsFactors=FALSE, lapply(rs, function(r) {
  m <- t(apply(do.call(expand.grid, r), 1, cumsum) %% length(abc) + 1)
  m[] <- abc[m]
  as.data.frame(cbind(m, apply(m, 1, paste, collapse = "")), stringsAsFactors=FALSE)
})))
head(rets)
#   Var1 Var2 Var3 Var4 Var5 Var6     V7
# 1    b    c    a    b    c    a bcabca
# 2    c    a    b    c    a    b cabcab
# 3    a    b    c    a    b    c abcabc
# 4    b    a    b    c    a    b babcab
# 5    c    b    c    a    b    c cbcabc
# 6    a    c    a    b    c    a acabca
tail(rets)
#     Var1 Var2 Var3 Var4 Var5 Var6     V7
# 331    b    c    b    a    c    c bcbacc
# 332    c    a    c    b    a    a cacbaa
# 333    a    b    a    c    b    b abacbb
# 334    b    a    c    b    a    a bacbaa
# 335    c    b    a    c    b    b cbacbb
# 336    a    c    b    a    c    c acbacc

Walkthrough of additional steps:

*

*rs <- c(list(r), rs) makes the first (non-repeating r) an enclosed list, then prepends it to the rs list.

*lapply(rs, function(r) ...) does the ... from the previous question once for each element in the rs list. I named it r inside the anon-function to make it perfectly clear (inside the function) that each time it gets a new r, it does exactly the same steps as the last question.

*do.call(rbind.data.frame, c(stringsAsFactors=FALSE, ... because each return from the lapply will be a data.frame, and we want to combine them into a single frame. I prefer no factors, but you can choose otherwise if you need. (Instead of rbind.data.frame, you could use data.table::rbindlist or dplyr::bind_rows, both without stringsAsFactors.)

Now the first 96 rows have no repeats, then the remaining five batches of 48 rows each (total 336 rows) have one repeat each. We "know" that 48 is the right number for each of the repeat-once lists, since by changing one of the positions from "1 2" possible to "0" (from 2 to 1 possible value) we halve the total number of possible combinations (96 / 2 == 48).
If for some reason your next question asks how to expand this to allow two repeats ... then I wouldn't necessarily recommend brute-forcing this aspect of it: there are 6 or 10 possible combinations (depending on if "aaa" is allowed) of repeats, and I would much prefer to go to a more programmatic handling than this brute-force appending of the one-constraint.


text:
Q: Scrapy xpath for nested elements I think I am using Scrapy wrong, but I am trying to use xpath to select only the text from the H2's on a page and strip out the inner tags.
eg.

Welcome to my page

Welcome to my Page

I have tried using //h2//text(),  but it produces an array like this
item["h2s"] = response.xpath('//h2//text()').extract()

['Welcome to my',
'page',
'Welcome to my Page']

I have tried number of combinations and just can't seem to get an array like I want below
['Welcome to my page',
'Welcome to my Page']

A: You may join all the text nodes for every h2:
In [1]: [''.join(h2.xpath(".//text()").extract()) for h2 in response.xpath("//h2")]
Out[1]: [u'Welcome to my page', u'Welcome to my Page']

This topic is also quite relevant:

*

*How can I get all the plain text from a website with Scrapy?


text:
Q: Lenovo laptop BSODs at semi-random times My Lenovo laptop is 2 years old so it is right at the point where I can't decide if this is a hardware failure or not.
I've managed to trigger BSODs in various conditions, resulting in IRQL_NOT_LESS_OR_EQUAL (most common), MEMORY_MANAGEMENT, or BAD_POOL_HEADER (less common).
I haven't pinpointed the exact causes yet but these are what I've noticed tend to trigger BSODs:
Moving the laptop while in use (not necessarily a jolt, slight shuffling causes BSODs too) (most common cause)
Using the laptop in warm conditions
Moving the battery
So far I've tried a system refresh, total drivers and Windows Updates update run, and upgrading to Windows 10, but the problem has still persisted.
The Minidump and other debug files are here: https://onedrive.live.com/redir?resid=33847DD02D83E981!400&authkey=!APOXx1UfGagY5y8&ithint=folder%2c
Note: the computer froze while collecting the Minidump files during the BSOD so they may be incomplete.
Thanks!

A: Moving the laptop while in use (not necessarily a jolt, slight shuffling causes BSODs too) (most common cause) sounds like a hardware problem.
Unreliable memory tends to result in BSODs. Run a memtest86 (which is a part of almost all Linux installation or live CDs) to see if it is your memory which causes problems. It might probably be a bad contact, so try to open your laptop and re-seat all removeable extensions (especially memory, WiFi card, etc.). While at it, clean it from dust which might get into the sockets.
If the problem persists, it might be related to some soldering joints becoming bad and there is relatively little you can do.


text:
Q: ASP.NET MVC2 : How to use radiobuttons in a grid? Again a question about RadioButtons/ RadioButtonList
I've the following Model:
public class SkillLevelModel
    {
        public long? Id { get; set; }
        public int? SelectedLevel { get; set;}
    }

I've the following Controller:
public class SkillController : BaseController
    {
        public ActionResult Index()
        {
            var skills = new List<SkillLevelModel>();

            for (int i = 0; i < 10; i++)
                skills.Add(new SkillLevelModel() { Id = i, SelectedLevel = new Random().Next(0,5) });

            return View(skills);
        }

I've the following code in the View:
<% foreach (var item in Model) { %>

            <%= Html.Encode(item.Id) %>

            <% Html.RenderPartial("UCSkillLevel", item); %>

    <% } %>

I've the following code in the PartialView:
<% for (int i = 0; i <= 5; i++) { %>

        <%= Html.RadioButton("SelectedLevel", i, new { id = Model.Id + "_" + i })%>

<% } %>

The problem is that no radiobutton is checked, althought they have a level.
What's wrong here?

A: Code in the partial view foreach loop should be
<%= Html.RadioButton("SelectedLevel_" + Model.Id, i, Model.SelectedLevel == i) %>

A: You have to specify if the radiobutton is selected:
Html.RadioButton("SelectedLevel", i, i == (Model.SelectedLevel ?? -1), new { id = Model.Id + "_" + i })


text:
Q: Is "I am who(m) God made me" grammatical? SAH asked an interesting question about case, I am [who/whom] G-d made me, but one issue that came up in the comments repeatedly is that many people said that they find the example sentence unacceptable with either pronoun.
This suggests that the sentence could be ungrammatical, but I'm having trouble figuring out why it would be. It is possible in general for the verb "make" to take a direct object and an object complement. The object complement can be an adjective, as in "They made me unhappy", or a noun phrase, as in "It made me a believer". We can say "It made me who I am", and things like "Your personality is what makes you you" or "These are the things that made me, me" (people seem to vary in how they punctuate sentences like these, but it's not that hard to find examples).
One thing I considered was that maybe it is grammatical, but hard to parse because it is a kind of "garden path sentence": many of the commenters expressed the idea that having both "who(m)" and "me" is redundant, which to me seems like a misunderstanding of the syntax of the sentence.
For example, Mitch said:

*

*
The relative pronoun should replace the subject or object in the relative clause but both are still there. It would be "I am who/whom G-d made" or "I am who made me".(who or whom both work; whom is hardly used at all in normal speech nowadays, but religious speech holds on to some archaism me like 'whom'.
[...] "X is who Y made Z" not grammatical. "Adjective is how Y made Z" grammatical (from "Y made Z Adjective") "X is who/whom Y loves" (from "Y loves X")

If the sentence is actually ungrammatical, and not just difficult to parse, it would seem to indicate some restriction on the ability of who or whom in this position to correspond to anything but a subject or direct object. I wonder if this is related to the dubious acceptability of "who(m)" in contexts like "the girl whom I gave the ring" (where many speakers feel a "to" has to be added to complete the sentence).
Surprisingly to me, it seems like there may be a difference between the animate wh-pronoun who(m) and the inanimate wh-pronoun what, since I received comments suggesting that similar sentences with what do sound acceptable to Araucaria and Mitch:

*

*
"What they named Christopher was the boy" doesn't seem to bear a good relation to the original, it seems to me . "What they named the boy was Christopher" seems ok to me ... (but grammaticality is in the ear of the beholder, no doubt!) – Araucaria

*
"What they named the boy was Christopher." sounds fine to me. Also "Christopher was what they named the boy" is fine too. – Mitch

In "Christopher was what they named the boy", the word "what" doesn't seem to be either a subject or a direct object, but nevertheless the sentence appears to be grammatical. So what's the relevant difference between this sentence and "I am who(m) G-d made me"?
I'm interested in knowing if there are any grammatical theories that explain why who(m) would be ungrammatical in this context, but any evidence (in addition to the already-established unacceptability judgements of a fair number of commenters here) that you can provide showing that the sentence with who(m) is ungrammatical would suffice as an answer to this question. (Or if you can show that the sentence is grammatical, that would also make a great answer!)

A: It's grammatical. As per my answer at SAH's question, it's grammaticality is flushed out when one adds what has been (or can be taken to  have been) elided, so:

I am who/m God made me to be.

For which I vote for who based on "it sounds better" (the be-all-and-end-all of descriptive linguistics).
Thus

I am who God made me (to be)

is grammatical...
as is the reordered

I am who God made me.

A: The reason is that traditionally, you can't use who in fused relative clauses; that is, you cannot use who when it figures in two clauses, being the subject (object) of one and the subject (object) of another.
Shakespeare used fused relative clauses:

who steals my purse steals trash.

And they seem to be coming back into use in English today:

I can help who's next.

(Although some people say that this is ungrammatical.)
But traditionally , you can't use who as the pronoun for two overlapping clauses, even though you can use whoever, whatever, or what.

I will do what is right.

There is a good discussion of this on this LanguageLog post, which says much more about it in greater depth than I could.

A: My theory is that the "who" version is rejected by some because they have adopted a "fix-up" rule to satisfy prescriptive grammarians which says: Use relative "who" only when it is the subject of the relative clause -- otherwise use "whom".  That often works okay to produce the archaic supposedly correct "whom" forms.  It doesn't work here, since "whom" is ungrammatical, so there is no solution for this example. It's all bad. (I don't use "whom" ever,  so "who" is okay with me.)

A: I am whom God made.
I am who God made.
The first is indubitably correct, but unfortunately suggests that God just made this one person, and that you are it (cf. "I am whom God sent" - only angels and Jesus and perhaps a prophet or two can make this claim). The second can be read as elliptical for "I am (such) as God made me" which is what is meant, and how you should say it if you wish to sound natural.


text:
Q: connecting to wcf service hosted on domain from a client that is not on the domain I would like an example or explanation of how to connect a client to a wcf service when the client is not on the domain.
I imagine there is a way to specify domain credentials with the client and the wcf service could talk to the authority (dc) to see if the client is secure.
I followed the examples on the msdn and can connect to see the metadata (methods available) but when using wshttpbinding I get "An unsecured or incorrectly secured fault was received from the other party".
Thanks in advance!

A: By default, wsHttpBinding will use Windows credentials - this only works if both your service and your calling client are member of the same domain (or member of domains with a mutual trust relationship).
If you want to authenticate using username/password, there's a number of things you need to do:

*

*the service needs a certificate to authenticate itself to the caller, and to provide an encryption mechanism for the exchange of username/passwords and messages. So you will need to create a security certificate and install it on the server machine, and configure it:
<system.serviceModel>
  <behaviors>
     <serviceBehaviors>
        <behavior name="Internet">
            <serviceCredentials
                 findValue="MyServiceCertificate"
                 storeLocation="LocalMachine"
                 storeName="My"
                 X509FindType="FindBySubjectName" />
        </behavior>
     <serviceBehaviors>
  <behaviors>
  <services>
      <service name="MyService" behaviorConfiguration="Internet">
         ......
     </service>
  </services>
</system.serviceModel>

*the client needs to set up a config that defines wsHttpBinding with message security, and username/password client credentials
<system.serviceModel>
  <bindings>
     <wsHttpBinding>
        <binding name="UserNameWS">
            <security mode="Message">
                <message clientCredentialType="UserName" />
            </security>
        </binding>
     <wsHttpBinding>
  <bindings>
  <client>
      <endpoint name="Default"
          address="........."
          binding="wsHttpBinding" bindingConfiguration="UserNameWS"
          contract="........." />
  </client>
</system.serviceModel>

*on the server side, you need to set up a mechanism to authenticate those username/passwords - typically, the easiest way is to use the ASP.NET membership system
<system.serviceModel>
  <behaviors>
     <serviceBehaviors>
        <behavior name="Internet">
            <userNameAuthentication
                userNamePasswordValidationMode="MembershipProvider" />
            <serviceCredentials

   .....
</system.serviceModel>

*before each call from the client, you need to set the username/password on your client-side proxy (this is one of the few things you cannot do in config - works only in code).
proxy.ClientCredentials.UserName.UserName = "YourUserName";
proxy.ClientCredentials.UserName.Password = "Top$Secret";

Read all about WCF security at the WCF Security Guidance site on Codeplex.

A: The error message "An unsecured or incorrectly secured fault was received from the other party" is a rather misleading one. A common cause is a difference in the bindings configuration between the client and the server. Check the system.serviceModel section of the web.config at the service side, and modify your client settings to match.

A: The reason why you can access metadata and cannot call service is that you are using WsHttpBinding probably with default configuration. It uses message security wich is involved only for service usage - not service metadata. It uses Windows credentials and Windows security to encrypt and sign message. Because of Windows security it works only when both client and server are on the same domain.
Your client is not part of domain - you can send windows credentials either with message security or transport security. In case of message security you will have to use clientCredentialType="UserName", default password validator and you will have to configure X509 certificate in service behavior to support encryption and signing. In case of transport security will either use HTTPS (X509 certificate configured in http.sys/IIS) or TransportCredentialOnly mode which will send windows user name and password as a plain text over HTTP (this is bad solution). In case of transport security set clientCredentialType="Basic".


text:
Q: What would be a good  way to request comments? In the project/team I'm working the frequency of comments is a little low.
One reason might be that it is not clear to the long-time devs what lines in the code really needs a comment (each part of the project has quite fixed devs).
To increase this we plan to let team members review the code and check in "requests for comments", which the main dev of that part should replace with useful comments.

*

*Do you think this could work?

*If "yes": what tags should we use to mark? (e.g. //TODO please comment)

*Can you think of alternatives for this process?

Edit: I appreciate your answers about best practice in commenting and writing code, and I completey agree.
But my question targets the cases where refactoring is not an option (not wanting to change working code, not wanting to "accuse" main dev of producing code that needs refactoring,...) - so only more or better comments are an option (at least for this question).

A: First and foremost, code should be self-documenting. Each line of code should be easy to decipher, and the sum total of those lines of code should be easy to trace through. This generally means that methods and variables should have descriptive yet concise names, operations should be clearly defined, design patterns that encourage smaller, single-purpose methods should be employed, and "hacks", including code reliant on arcane details of the implementation behind the language spec, should be avoided. Given these things, any reasonably-experienced coder should be able to decipher your code without any comments needed.
That said, you will not always be able to do this. Time, resources, technical ability, etc will at some point force you to do something in a way that is unclear or kludgy. To mitigate the murkiness of your code, comments that state what you are doing and why can sometimes be necessary. It can be difficult for a programmer going flat-out, heads-down at an algorithm to realize when they may be necessary, so a code review step is a good idea. Have another developer go over the code, and if they point to something and ask "why", that's a good candidate for some comments.
Another thing I often find useful is "comment-driven development". When you create a new method, write out lines of comments detailing how the method should progress through its designed task. You're basically making notes about what the method should do, even if at this point in your coding you won't actually write any of the code in that method. This can be invaluable in collaborative programming, where an algorithm for something critical or extremely involved was designed on a whiteboard by the team and then given to one or two coders to implement. Then, as you code, the comments detail the task performed in each stage. They can be removed if the operation is plainly obvious, or they can stay if the logic is more complex than the conceptual idea of that code. However, when using this technique, it's important to understand that what you thought you were going to do isn't always what you ended up doing; you have to identify those cases and either update or rewrite the comments.

A: IMHO lack of comments is not necessarily a bad thing. Most of the time the code can be written to be self-explaining, thus it needs no comments (apart from API documentation). The few exceptions are when the code is intentionally difficult, e.g. it implements a known algorithm, contains performance optimizations etc.
Overall, the quantity (and even the quality and correctness) of comments is a bad indicator of overall code quality. You should rather focus on the full picture: creating (and keeping) clean, readable, maintainable code - of which comments are only a small part.
So if you see a piece of code which you feel is in need of comments, consider refactoring first. Most often the code can be refactored to be easy to read, and this eliminates the need for comments.
E.g. if you see a long method performing some lengthy operation which clearly has several distinct phases / steps, you may feel it necessary to add comments before each phase, like
void SomeLongCalculation(...) {
  // Calculate the foo coefficient
  ...

  // Determine the bar factor
  ...

  // Sum up the blorg values
  ...

  // Calculate the yearly average
  ...

}

whereas you could extract each step into a separate method with a descriptive name instead:
void SomeLongCalculation(...) {
  CalculateFooCoefficient(...);
  DetermineBarFactor(...);
  SumBlorgValues(...);
  CalculateYearlyAverage(...);
}

This makes each step explicit, keeps all the code in your method on the same abstraction level, thus making it clean and easy to read. Moreover, it enables you to unit test each substep in isolation.

A:
Can you think of alternatives for this process?

Yes, I can. When you are going to review a piece of code, do it pairwise - one reviewer and the dev who wrote it, directly sitting in front of the same screen. Instead of adding "request for comments", let the main dev explain what the code does (and why!), and the reviewer directly add a comment with words he understands.
And think about allowing some refactoring during that process - at least, when you have automatic refactoring tools at hand, which give you only a very small risk of destroying something. I am here with Péter Török - small methods with self-describing names and small scope need less comments and are much better than big methods with lots of block-comments.

A: I think it is a good idea to do that, if the team is big enough and there is enough time. Comments are necessary in code, the question is how it is done. Your team probably has, or is planning on implementing a comprehensive way of commenting. Either way, the right kind of commenting will speed up the development process, combined with the answer by Péter Török.
On my project last semester, the supervisor used gerrit for the code review. This is the same system that is used in the whole department and it functions quite well. He simply reviewed our code and indicated all the parts that needed more comments or improvements. This can be an answer to your last two questions, or you could find a similar system that does this.


text:
Q: Spring Security Ajax login I have implemented this security proccess in my project:
Spring Security 3 - MVC Integration Tutorial (Part 2).
My problem is that I need to turn it into an Ajax-based login.
What do I need to do in order to make this XML suitable with just returning string/JSON to the client?
I understand that the problem might be in the form-login tag.
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                           http://www.springframework.org/schema/security
                           http://www.springframework.org/schema/security/spring-security-3.0.xsd">

    <!-- This is where we configure Spring-Security  -->
    <http auto-config="true" use-expressions="true" access-denied-page="/Management/auth/denied" >

        <intercept-url pattern="/Management/auth/login" access="permitAll"/>
        <intercept-url pattern="/Management/main/admin" access="hasRole('ROLE_ADMIN')"/>
        <intercept-url pattern="/Management/main/common" access="hasRole('ROLE_USER')"/>

        <form-login
                login-page="/Management/auth/login"
                authentication-failure-url="/Management/auth/login?error=true"
                default-target-url="/Management/main/common"/>

        <logout
                invalidate-session="true"
                logout-success-url="/Management/auth/login"
                logout-url="/Management/auth/logout"/>

    </http>

    <!-- Declare an authentication-manager to use a custom userDetailsService -->
    <authentication-manager>
            <authentication-provider user-service-ref="customUserDetailsService">
                    <password-encoder ref="passwordEncoder"/>
            </authentication-provider>
    </authentication-manager>

    <!-- Use a Md5 encoder since the user's passwords are stored as Md5 in the database -->
    <beans:bean class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" id="passwordEncoder"/>

    <!-- A custom service where Spring will retrieve users and their corresponding access levels  -->
    <beans:bean id="customUserDetailsService" class="com.affiliates.service.CustomUserDetailsService"/>

</beans:beans>

A: It depends on the implementation of your ajax-login. In any case, I guess you need to implement a custom filter. There are two good tutorials for using Spring Security with ExtJs:
Integrating Spring Security 3 with Extjs
Integrating Spring Security with ExtJS Login Page
It should work very similar for other Ajax login-forms.

A: Spring is shifting away from XML based configurations and towards Java @Configuration classes. Below is @Configuration version of the setup explained in the post above (Spring Security Ajax login).  Steps 2 & 3 remain the same, replace Step 1 with this code.  The order is once again important, more specific definitions needs to be loaded before more generic ones, use @Order(1) and @Order(2) to control that.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;

@Configuration
@EnableWebSecurity
public class WebMvcSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Bean(name = "requestCache")
    public RequestCache getRequestCache() {
        return new HttpSessionRequestCache();
    }

    @Configuration
    @Order(1)
    public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {

            @Autowired private RequestCache requestCache;

            @Override
            protected void configure(HttpSecurity http) throws Exception {
                http
                    .regexMatcher("/rest.*")
                    .authorizeRequests()
                        .antMatchers("/rest/calendar/**")
                            .hasAuthority("ROLE_USER")
                        .antMatchers("/rest/**")
                            .permitAll()
                        .and()
                   .headers()
                        .xssProtection()
                        .and()
                   .logout()
                       .logoutUrl("/rest/security/logout-url")
                       .and()
                    .requestCache()
                        .requestCache(requestCache)
                        .and()
                    .formLogin()
                        .loginProcessingUrl("/rest/security/login-processing")
                        .loginPage("/rest/security/login-page")
                        .failureUrl("/rest/security/authentication-failure")
                        .defaultSuccessUrl("/rest/security/default-target", false)
                        .and()
                    .httpBasic();
           }
    }

    @Configuration
    @Order(2)
    public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

        @Autowired private RequestCache requestCache;

       @Override
       protected void configure(HttpSecurity http) throws Exception {
           http
                .authorizeRequests()
                    .regexMatchers("/calendar/.*")
                        .hasAuthority("ROLE_USER")
                    .regexMatchers("/.*")
                        .permitAll()
                   .and()
               .logout()
                   .logoutUrl("/security/j_spring_security_logout")
                   .and()
                .requestCache()
                    .requestCache(requestCache)
                    .and()
                .formLogin()
                    .loginProcessingUrl("/security/j_spring_security_check")
                    .loginPage("/login")
                    .failureUrl("/login?login_error=t" )
                    .and()
                .httpBasic();
       }
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web
            .ignoring()
                .antMatchers("/resources/**")
                .antMatchers("/sitemap.xml");
    }
}

A: This is an old post, but it still comes up as one of the top results for "spring security ajax login," so I figured I'd share my solution.  It follows Spring Security standards and is pretty simple to setup, the trick is to have 2 <http> elements in your security configuration, one for REST/Ajax and one for the rest of the app (regular HTML pages).  The order in which <http>'s appear is important, it has to go from more specific to more generic URLs, just like <url-intercept> elements inside of a <http>.
Step 1: Setup Two Separate <http>'s
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">

    <!-- a shared request cache is required for multiple http elements -->
    <beans:bean id="requestCache" class="org.springframework.security.web.savedrequest.HttpSessionRequestCache" />

    <!-- remove security from static resources to avoid going through the security filter chain -->
    <http pattern="/resources/**" security="none" />

    <!-- http config for REST services (AJAX interface)
    =================================================== -->
    <http auto-config="true" use-expressions="true" pattern="/rest/**">
        <!-- login configuration
            login-processing-url="/rest/security/login-processing" front-end AJAX requests for authentication POST to this URL
            login-page="/rest/security/login-page" means "authentication is required"
            authentication-failure-url="/rest/security/authentication-failure" means "authentication failed, bad credentials or other security exception"
            default-target-url="/rest/security/default-target" front-end AJAX requests are redirected here after success authentication
        -->
        <form-login
            login-processing-url="/rest/security/login-processing"
            login-page="/rest/security/login-page"
            authentication-failure-url="/rest/security/authentication-failure"
            default-target-url="/rest/security/default-target"
            always-use-default-target="true" />
        <logout logout-url="/rest/security/logout-url" />

        <!-- REST services can be secured here, will respond with JSON instead of HTML -->
        <intercept-url pattern="/rest/calendar/**" access="hasRole('ROLE_USER')" />

        <!-- other REST intercept-urls go here -->

        <!-- end it with a catch all -->
        <intercept-url pattern="/rest/**" access="isAuthenticated()" />

        <!-- reference to the shared request cache -->
        <request-cache ref="requestCache"/>
    </http>

    <!-- http config for regular HTML pages
    =================================================== -->
    <http auto-config="true" use-expressions="true">
        <form-login
            login-processing-url="/security/j_spring_security_check"
            login-page="/login"
            authentication-failure-url="/login?login_error=t" />
        <logout logout-url="/security/j_spring_security_logout" />

        <intercept-url pattern="/calendar/**" access="hasRole('ROLE_USER')" />

        <!-- other intercept-urls go here -->

        <!-- in my app's case, the HTML config ends with permitting all users and requiring HTTPS
             it is always a good idea to send sensitive information like passwords over HTTPS -->
        <intercept-url pattern="/**" access="permitAll" requires-channel="https" />

        <!-- reference to the shared request cache -->
        <request-cache ref="requestCache"/>
    </http>

    <!-- authentication manager and other configuration go below -->
</beans:beans>

Step 2: REST Authentication Controller
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import flexjson.JSONSerializer;

@Controller
@RequestMapping(value = "/rest/security")
public class RestAuthenticationController {

    public HttpHeaders getJsonHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        return headers;
    }

    @RequestMapping(value="/login-page", method = RequestMethod.GET)
    public ResponseEntity<String> apiLoginPage() {
        return new ResponseEntity<String>(getJsonHeaders(), HttpStatus.UNAUTHORIZED);
    }

    @RequestMapping(value="/authentication-failure", method = RequestMethod.GET)
    public ResponseEntity<String> apiAuthenticationFailure() {
        // return HttpStatus.OK to let your front-end know the request completed (no 401, it will cause you to go back to login again, loops, not good)
        // include some message code to indicate unsuccessful login
        return new ResponseEntity<String>("{\"success\" : false, \"message\" : \"authentication-failure\"}", getJsonHeaders(), HttpStatus.OK);
    }

    @RequestMapping(value="/default-target", method = RequestMethod.GET)
    public ResponseEntity<String> apiDefaultTarget() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        // exclude/include whatever fields you need
        String userJson = new JSONSerializer().exclude("*.class", "*.password").serialize(authentication);
        return new ResponseEntity<String>(userJson, getJsonHeaders(), HttpStatus.OK);
    }
}

Step 3: Submit AJAX form and process the response, required jQuery's ajaxForm library
<form action="/rest/security/login-processing" method="POST">
...
</form>

$('form').ajaxForm({
    success: function(response, statusText, xhr, $form)  {
        console.log(response);
        if(response == null || response.username == null) {
            alert("authentication failure");
        } else {
            // response is JSON version of the Spring's Authentication
            alert("authentication success");
        }
    },
    error: function(response, statusText, error, $form)  {
        if(response != null && response.message == "authentication-failure") {
            alert("authentication failure");
        }
    }
});

A: You can use HttpServletRequest.login(username,password) to login, just like:
@Controller
@RequestMapping("/login")
public class AjaxLoginController {

    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public String performLogin(
        @RequestParam("username") String username,
        @RequestParam("password") String password,
        HttpServletRequest request, HttpServletResponse response) {
    try {
        request.login(username,password);
        return "{\"status\": true}";
    } catch (Exception e) {
        return "{\"status\": false, \"error\": \"Bad Credentials\"}";
    }
}


text:
Q: How to set MX records for Google Apps and for own Service I want to set MX records on my domain correctly. My problem is - Im using Google Apps for only one email, lets call it admin@xyz.com now I have installed Froxlor on my server (admin panel, mail service etc.) and now I want to create new email, lets call it contact@xyz.com on my server.
Here are my MX records for Google Apps on my domain:
(clear) MX ASPMX.L.GOOGLE.COM.         1    3600
(clear) MX ALT1.ASPMX.L.GOOGLE.COM.    5    3600
(clear) MX ALT2.ASPMX.L.GOOGLE.COM.    5    3600
(clear) MX ASPMX2.GOOGLEMAIL.COM.      10   3600
(clear) MX ASPMX3.GOOGLEMAIL.COM.      10   3600

Now I want to add new MX record for my server and it should take 1. prio.
(clear) MX xyz.com 1 3600

So I had to change ASPMX from Google to "2".
Now Ive got a trouble with receiving Messages on my google email, but I can fully use my "server" account.
How do I have to set thous MX records to get it work.
Im really new in this, so I can do some mistakes, so sorry for that and for my bad English.
Thank you very much!

A: So, that's not how MX records work. Essentially, the first record is where all mail is going and any subsequent records are backups. For example, if (clear) MX xyz.com 1 3600 failed for some reason, then all mail would go to Google's servers in the order you've specified in priority.
You're going to want to look into implementing Split Delivery. This would mean that, you could have the following setup:

*

*MX Records pointed to Google

*Someone emails admin@xyz.com and it goes to their Apps mailbox

*Someone mails user@xyn.com and, because they don't have an Apps account, it's forward on to you legacy or secondary system

You can find a bit more information on Priorities on Google Support site here.
Hope this helps!


text:
Q: DISTINCT ON fields is not supported by this database backend I am using distinct to get the distinct latest values but it is giving me an error:

DISTINCT ON fields is not supported by this database backend

views.py
class ReportView(LoginRequiredMixin, generic.TemplateView):
    template_name = 'admin/clock/report.html'

    def get_context_data(self, **kwargs):
        context = super(ReportView, self).get_context_data(**kwargs)
        context['reports'] =  TimesheetEntry.objects.filter(
                                  timesheet_jobs__job_company = self.request.user.userprofile.user_company,
                              ).distinct('timesheet_users')
        return context

Basically I want to query on TimesheetEntry model where there will be lot of entries of user which is a foreign key in User in-built model.
So I want to query with distinct user so that latest entry of the user will be displayed. It is very important for me to get the latest entry of user.
models.py
class TimesheetEntry(models.Model):
    timesheet_users = models.ForeignKey(User, on_delete=models.CASCADE,related_name='timesheet_users')
    timesheet_jobs = models.ForeignKey(Jobs, on_delete=models.CASCADE,related_name='timesheet_jobs')
    timesheet_clock_in_date = models.DateField()
    timesheet_clock_in_time = models.TimeField()

A: distinct('field_name') is not supported in MySQL. It only support distinct(). distinct('field_name') will only work on PostgresSQL. For more details, please check the documentation.
Examples (those after the first will only work on PostgreSQL):(Copy Pasted from Documentation:)
>>> Author.objects.distinct()
   [...]

>>> Entry.objects.order_by('pub_date').distinct('pub_date')
   [...]

>>> Entry.objects.order_by('blog').distinct('blog')
   [...]

>>> Entry.objects.order_by('author', 'pub_date').distinct('author', 'pub_date')
   [...]

>>> Entry.objects.order_by('blog__name', 'mod_date').distinct('blog__name', 'mod_date')
   [...]

>>> Entry.objects.order_by('author', 'pub_date').distinct('author')
   [...]

A: May you should this one
>>> queryset = TimesheetEntry.objects.distinct()
>>> context['reports'] = queryset .filter(timesheet_jobs__job_company = self.request.user.userprofile.user_company, )


text:
Q: ¿Cambiar base de datos mediante parámetros? Estoy intentando crear una consulta, la cual me permite cambiar de base de datos mediante un parámetro hasta el momento lo que he intentado es;
DECLARE @sqlCommand varchar(1000)
DECLARE @codbodega varchar(5)
DECLARE  @dbase sysname

SELECT TOP 1 @codbodega = codbodega FROM vista_saldos_fecha

SET @sqlCommand = 'SELECT ' + @codbodega + ' FROM vista_saldos_fecha where codigo=''PT-1485'''
SET @dbase ='nombre_db'
EXEC (@sqlCommand , @dbase)

la consulta se ejecuta, pero no retorna datos , ni cambia base de datos
o como más puedo realizar este proceso?

A: Puedes concatenar la variable de la base a la misma consulta del select:
SET @dbase ='nombre_db'
SET @sqlCommand = 'SELECT ' + @dbase + '..' + @codbodega + '
                          FROM vista_saldos_fecha where codigo=''PT-1485'''

EXEC(@sqlCommand)

Recuerda que este tipo de sentencias son suceptibles de sufrir inyección de SQL, por lo que lo mejor siempre es que el motor controle los parámetros ingresados, en tu caso @codbodega, para esto te recomiendo el uso de sp_executesql().


text:
Q: validation error in node.js using postman mongodb in javascript I had task to make new service using post man I have written module controller and routes code but unfortunately when I send mission to create object using postman it gives me validation error and I have no idea what it is

I know that validation error means that problem is in module but I cant figure out what it wants

A: Since you have madepost_id as required field so,when you are creating document you are missing post_id in your req.body.So you have to either send post_id in body or if you don't want to save post_id every document them you can remove required:true from your model.


text:
Q: Windows Updates not downloading when set to Download Only I am running Windows server 2016, with Windows Updates set to Download Only, however when I run the following script, it shows all outstanding updates as not downloaded, how do I investigate why they are not downloading in the background?
$updatesession =  [activator]::CreateInstance([type]::GetTypeFromProgID("Microsoft.Update.Session"))
$updatesearcher = $updatesession.CreateUpdateSearcher()
$searchresult = $updatesearcher.Search("IsInstalled=0")
$searchresult


text:
Q: Can't extend main partition to use free space How can I extend the C partition so that it uses the "Free space" partition?
The extend option is greyed out when right clicking the C partition:

A: Although @Ramhound has already solved the problem, I'll just elaborate a bit here.
Under BIOS (non UEFI), it is possible to have only a limited number of physical partitions (say n). As a result, to have more that that many partitions, you create n-1 physical and 1 extended partition. Now you cannot use this partition directly, but you can create several logical partitions inside this. However, if there is free space inside the extended partition, it belongs to that partition and hence cannot be accessed from outside. Thus, while you have supposedly free unpartitioned space, the disc actually sees it as a separate unformatted partition.
Now, if you delete this extended partition, then the OS correctly recognises the available empty space as unallocated, and hence you can extend the partition before it, which was earlier not possible.


text:
Q: Subdomain does not send my forms larger than 3 's I have this weird form behaviour on all my subdomains of my server:
I can send and display a form with 1 input field, but when I add mulptiple input's nothing really happens.
I wrote a little test script to get a better understanding of the behaviour. So this is the one that works normally (check out live version here):
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
?>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
  Name: <input type="text" name="name">

  <input type="submit" name="submit">
</form>

Name: <?php f(isset($_POST['submit']))  { echo($_POST['name']); } ?>

And from the moment that I add some input fields, it does not echo the results (without error reporting) (live version here):
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
?>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Name: <input type="text" name="name">

Superman: <input type="text" name="superman">

Place: <input type="text" name="place">

<input type="submit" name="submit">
</form>

Name: <?php if(isset($_POST['submit']))  { echo($_POST['name']); } ?>

superman: <?php if(isset($_POST['submit']))  { echo($_POST['superman']); } ?>

place: <?php if(isset($_POST['submit']))  { echo($_POST['place']); } ?>

Same problem occurs when I want to install third party forums like esotalk or FluxBB (I cannot send the installation form). As if the server is just ignoring my forms. This only happens on my subdomains for some bizarre reason..
My server is a (dv) vps hosted at Media Temple. I contacted them 3 times but they couldn't help me. I tried file permissions, compared php.ini settings,... Anyone who might have a clue?

A: The error it's related to POST size. Try to specify an encoding type to form: enctype="multipart/form-data"


text:
Q: How to resize JTable column to string length? I have a JTable that will have the last column data field change to different string values. I want to resize the column to the string length. What is the formula for string length to width?
I'm going to be using JTable.getColumnModel().getColumn().setPreferredWidth() so I want to know how to translate string length to width value.

A: This method will pack a given column in a JTable -
/**
 * Sets the preferred width of the visible column specified by vColIndex. The column
 * will be just wide enough to show the column head and the widest cell in the column.
 * margin pixels are added to the left and right
 * (resulting in an additional width of 2*margin pixels).
 */
public static void packColumn(JTable table, int vColIndex, int margin) {
    DefaultTableColumnModel colModel = (DefaultTableColumnModel)table.getColumnModel();
    TableColumn col = colModel.getColumn(vColIndex);
    int width = 0;

    // Get width of column header
    TableCellRenderer renderer = col.getHeaderRenderer();
    if (renderer == null) {
        renderer = table.getTableHeader().getDefaultRenderer();
    }
    java.awt.Component comp = renderer.getTableCellRendererComponent(
        table, col.getHeaderValue(), false, false, 0, 0);
    width = comp.getPreferredSize().width;

    // Get maximum width of column data
    for (int r=0; r<table.getRowCount(); r++) {
        renderer = table.getCellRenderer(r, vColIndex);
        comp = renderer.getTableCellRendererComponent(
            table, table.getValueAt(r, vColIndex), false, false, r, vColIndex);
        width = Math.max(width, comp.getPreferredSize().width);
    }

    // Add margin
    width += 2*margin;

    // Set the width
    col.setPreferredWidth(width);
}

A: Table Column Adjuster works both statically and dynamically and the user can control this.

A: you are not really interested in the string length (nor its mapping to a particular font/metrics). You're interested in the preferredSize of the renderingComponent which renderers the cell content. To get that, loop through all rows and query the size, something like
 int width = 0;
 for (row = 0; row < table.getRowCount(); row++) {
     TableCellRenderer renderer = table.getCellRenderer(row, myColumn);
     Component comp = table.prepareRenderer(renderer, row, myColumn);
     width = Math.max (comp.getPreferredSize().width, width);
 }

Or use JXTable (in the SwingX project): it has a method pack() which does the work for you :-)
Edit: the reason to prefer the table's prepareRenderer over manually calling getXXRendererComponent on the renderer is that the table might do decorate visual properties of the renderingComponent. If those decorations effect the prefSize of the component, a manual config is off.


text:
Q: Segmentation fault output is suppressed when piping stdin into a function. Why? Let's define a function to execute a binary:
function execute() { ./binary; }

Then define a second function to pipe a text file into the first function:
function test() { cat in.txt | execute; }

If binary crashes with a segfault, then calling test from the CLI will result in a 139 return code, but the error - "Segmentation fault" - will not be printed to the terminal.
"Segmentation fault" does get printed if we define test to call binary directly:
function test() { cat in.txt | ./binary; }

It also gets printed if we define to call execute without piping stdin into it:
function test() { execute; }

Finally, it also gets printed if we redirect in.txt into execute directly instead of through a pipe:
function test() { execute <in.txt; }

This was tested on Bash 4.4. Why is that?

A: This diagnostic message is generated by the interactive shell's job control system, for the benefit of the user - it's not from the underlying program that crashed. When you pipe into a shell function a subshell is spawned to run the function, and this subshell is not treated as user-facing. If you call the function normally, it runs within the original shell, and the message is printed.
You can test this out by disabling job control in your current shell
set +m

and then running ./binary again: now it won't print anything there either. Re-enable job control with set -m.
Even a bare subshell has the same effect:
( : ; ./binary )

will print no diagnostic (two commands are required in there to avoid a subshell-eliding optimisation). Piping out of the function does it too.
Job control is disabled in the subshell, and even with it enabled manually, it's silenced. This is an unfortunate gap in the system. In a non-interactive shell the message would always be reported through a different mechanism, and anywhere else in an interactive shell it would as well.

If printing the diagnostic is important to you, making a script instead of a function will allow you to make sure it's always included. Since you're using the function in a pipeline, you can't do anything that requires a function anyway, so there's not a major cost to doing so.

I wouldn't go quite as far as to say this is a bug. One possible reason to behave in this way is to make command substitution $(...), which also runs a subshell, behave appropriately:
foo=$(echo|test)

shouldn't result in the diagnostic message being stored in foo, so that pipeline failures result in empty expansions. Another is as a way to temporarily suppress the diagnostic messages deliberately.


text:
Q: Simple Modal issues - Multiples, Disappearing Content I'm a jQuery newbie and have rigged Simple Modal to allow me to have more than one modal on a page by doing this in my script:
$('input.basic, a.basic').click(function (e) {
        e.preventDefault();
            $(this).next('.basicModalContent').modal();
        });
here's my HTML:
    Link Heading

This Resource Requires Login

    Cancel

The issue I'm running into is everything works fine on first click & close. The second click launches the modal, but all the content is gone from inside the box.
see this link for the bug in action: http://blanksky.com/test/ebenefits21/modal.html

A: I would suggest something like:
Links:
link1
link2
link3

Hidden content (via CSS or inline style)

content

content

content

JavaScript:
$(document).ready(function () {
      $('#basic-modal input.basic, #basic-modal a.basic').click(function (e) {
              e.preventDefault();
              var content = '#' + this.id + '-content';
              $(content).modal();
      });
});

Something like that should do the trick.

A: When you hide the dialog, jQuery changes the position of the div in the DOM, then wanting to locate it with "$(this).next(...)", you can not do. You should have some ID or a reference to locate otherwise.
EDIT:
Well, you have me thinking a little echo. I hope it is useful the code that I'm going through. I'm not tested:
$('input.basic, a.basic').click(function (e)
{
   e.preventDefault();
   var el = "";

   if($(this).data("xid")!=undefined)
   {
      el = $($(this).data("xid"));
   }
   else
   {
     var xid = "xid_" + ((new Date()).getTime());
     el = $(this).next('.basicModalContent');
     $(this).data("xid", xid);
     if (el.lenght>0)
       el.attr("id", xid);
   }

   if (el.lenght>0)
   {
     el.modal();
   }
});

A: A solution that requires less markup is to use a single modal "window." See the following example:

<!doctype html>

 <meta charset="utf-8" />
 <title>Simple Modal Demo</title>

Login Required Link

Login Required Link

Login Required Link

http://example.com/

Sorry, you must login to click unknown.

Cancel


text:
Q: Can't dismiss flags from question page Manually dismissing a flag from a question page appears to be broken; nothing happens when I click the "no action needed" button. Tried on Chromium 32.0.1700.19 and Firefox 25.0, on Linux. Dismissing from the flag list still works fine.

A: I added individual flag dismissing and there was an issue on the Question/Show page - it should now be resolved.
Going to be honest, there are some UI issues still, e.g. after clearing a single flag, the UI might disappear from Question/Show.  Trying to sort it out, but the code isn't very extensible.


text:
Q: raising .net events from another class? can I call shared events contained in one class from another class?
for example:
logonclass.vb : handles login logic and authenticates against database
logonmanager.vb: hold current user reference and some logon and timeout events
Logon.vb: A form with a submit button.
I would like to do something like this but I can't get the compiler to agree with it
If VerifyEntries() Then
        Try
            privLvl = LoginClass.AttemptLogin(txtUserName.Text, txtPassword.Text)
        Catch
        End Try
        If privLvl > 0 Then
            'RaiseEvent LoginClass.UserLoggedIn()
            'RaiseEvent LoginManager.UIdisplaychange(privLvl)
            Me.Close()
        End If

    End If

If this isn't the proper way to wire things together let me know so I can learn to structure differently. In my planning it seemed like I was raising a lot of extra duplicate events from my logonclass to my loginmanager class. Then the loginmanager had to raise it again for the main form to see the change event. It got me thinking that if I publicly shared the events and could raise them from wherever then it would cut down on the amount of events I needed in code and the amount of them flying around at runtime.

A: I'd be creating a Friend method that raises the event.  Call that method instead or raising the event externally.
Class LoginClass

    Public Shared Event UserLoggedIn As EventHandler

    Friend Shared Sub OnUserLoggedIn(e As EventArgs)
        RaiseEvent UserLoggedIn(Me, e)
    End Sub
End Class

A: In C# the "event" keyword generates a private delegate member object. So it can be accessed only for the class where is defined. But you can expose a public method that will fire the event, and this method can be accessed from outside.
I think that in VB is the same.