text:
Q: "User interaction is not allowed" trying to sign an OSX app using codesign Our automated build is running on Jenkins. The build itself is running on slaves, with the slaves being executed via SSH.
I get an error:
00:03:25.113 [codesign-app] build/App.app: User interaction is not allowed.

I have tried every suggestion I have seen so far in other posts here:

*

*Using security unlock-keychain immediately before signing to unlock the keychain.

*Moving the signing key out into its own keychain.

*Moving the signing key into the login keychain.

*Moving the signing key into the system keychain.

*Manually setting list-keychains to only the keychain which contains the key.

In all cases, I get the same error.
In an attempt to diagnose the issue, I tried running the "security unlock-keychain" command on my local terminal and found that it doesn't actually unlock the keychain - if I look in Keychain Access, the lock symbol is still there. This is the case whether I pass the password on the command-line or whether I let it prompt me for it. Unlocking the same keychain using the GUI will prompt me for the password and then unlock it. Additionally, if I run "security lock-keychain", I do see the key lock immediately after running the command. This makes me think that unlock-keychain doesn't actually work. I experience the same behaviour on Lion (which we're using for the build slaves) and Mavericks (which I'm developing on.)
Next, I tried adding -v to all the security commands:
list-keychains "-d" "system" "-s" "/Users/tester/.secret/App.keychain"
Listing keychains to see if it was added: ((
        "/Library/Keychains/System.keychain"
))
unlock-keychain "-p" "**PASSWORD**" "/Users/tester/.secret/App.keychain"
build/App.app: User interaction is not allowed.

From this, it would seem that list-keychains is what isn't working. Maybe neither work. :/
There is a similar question here. The solution is interesting - set "SessionCreate" to true in launchctl. But I'm not building on the master - my build process is started from SSH on a slave build machine. Maybe there is a command-line way to do what launchctl is doing when you run "SessionCreate"?

A: Well, I guess I get to answer my own question today, because after stabbing at it over two and a half days, one of the things I tried seems to have worked. I'm just going to back away from it now and hope it keeps working.
Essentially, it looks like it comes down to -d system not actually working. So a lot of answers to other questions around here should probably be updated to reflect that.
security -v list-keychains -s "$KEYCHAIN" "$HOME/Library/Keychains/login.keychain"
security list-keychains # so we can verify that it was added if it fails again
security -v unlock-keychain -p "$KEYCHAIN_PASSWORD" "$KEYCHAIN"
codesign --sign "$SIGNER_IDENTITY" --force --signature-size 9600 \
         --resource-rules src/AppResourceRules.plist --timestamp --verbose \
         "$APP"

A: So this is the command that works. -A is to prevent Mac from asking password. Importing to system.keychain doesn't require an GUI.
sudo security import <cert.p12> -k "/Library/Keychains/System.keychain" -P <passphrase> -A

A: Using Security to create a Keychain for /usr/bin/codesign
Importing the certificate and having it work with codesign programmatically isn't a matter of using login or System keychains or praying to some god of codesign. You just need to have the correct permissions set. I recommend creating a new keychain specifically for codesign purposes.
These days to get codesign to not yield an errSecInternalComponent you need to get the partition list (ACLs) correct.  I'll walk through the steps:
Create the Keychain
security create-keychain -p "${KEYCHAIN_PASSWORD}" "${KEYCHAIN_NAME}"

at this point the keychain is unlocked but won't appear in Keychain Access.
Add the new Keychain to the search list
security list-keychains -s "${KEYCHAIN_NAME}" "${OLD_KEYCHAIN_NAMES[@]}"

Add the new Keychain to the list. If you don't first grab out the original list from list-keychains you'll no longer have login.keychain in your search-list.
Unlock the keychain
security unlock-keychain -p "${KEYCHAIN_PASSWORD}" "${KEYCHAIN_NAME}"

This is redundant if you created the Keychain above, but if the Keychain already existed it is necessary.
Remove the defaults from the Keychain
security set-keychain-settings "${TESTING_KEYCHAIN}"

By not specifying any arguments this will set the auto-lock timeout to unlimited and remove auto-lock on sleep.
Import your signing certs from a .p12
security import "${DIST_CER}" -P "${CERTIFICATE_PASSWORD}" -k "${KEYCHAIN_NAME}" -T /usr/bin/codesign

Import the certs and gives codesign access through the -T option.
Set the ACL on the keychain
security set-key-partition-list -S apple-tool:,apple: -s -k "${KEYCHAIN_PASSWORD}" "${KEYCHAIN_NAME}"

This is a requirement that many people miss. You can see what macOS does by using dump-keychain. Which in the case of codesigning requires apple: and apple-tool:. -s refers to signing certificates.
Where's my signing certificate?
Always a good idea to make sure you can find your certificates
security find-identity -p codesigning -v /path/to/keychain

Gitlab-Runner, Jenkins and the like
One very important thing for any CI-type runner or build system is to make sure the process is started from launchd correctly. Make sure your plist contains <SessionCreate> </true>.
Not correctly matching the the owner of the keychain with the build process and making sure a security session is created will result is all sorts of headaches. Diagnostically speaking you can introduce list-keychains and see if the output matches your expectations.
This is from the launchd.plist man-page:
SessionCreate <boolean>

This key specifies that the job should be spawned into a new security
audit session rather than the default session for the context is belongs
to. See auditon(2) for details.

UserName <string>

This optional key specifies the user to run the job as. This key is only
applicable for services that are loaded into the privileged system
domain.

GroupName <string>

This optional key specifies the group to run the job as. This key is only
applicable for services that are loaded into the privileged system
domain. If UserName is set and GroupName is not, then the group will be
set to the primary group of the user.

Example /Library/LaunchDaemons/com.company.gitlab-runner.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
  <dict>
    <key>Label</key>
    <string>com.company.gitlab-runner</string>
    <key>SessionCreate</key><true/>
    <key>KeepAlive</key><true/>
    <key>Disabled</key><false/>
    <key>UserName</key>
    <string>bob</string>
    <key>GroupName</key>
    <string>staff</string>
    <key>ProgramArguments</key>
    <array>
      <string>/usr/local/opt/gitlab-runner/bin/gitlab-runner</string>
      <string>run</string>
      <string>--working-directory</string>
      <string>/Users/bob/gitlab-runner</string>
      <string>--config</string>
      <string>/Users/bob/gitlab-runner/config.toml</string>
      <string>--service</string>
      <string>gitlab-runner</string>
      <string>--syslog</string>
    </array>
    <key>EnvironmentVariables</key>
      <dict>
        <key>PATH</key>
        <string>/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
    </dict>
  </dict>
</plist>

Register the runner
gitlab-runner register \
  --non-interactive \
  --tls-ca-file "{{ gitlab_runner_dir }}/certs/git.company.com.crt" \
  --config "{{ gitlab_runner_dir }}/config.toml" \
  --builds-dir "{{ gitlab_runner_dir }}/builds" \
  --url "{{ gitlab_ci }}" \
  --registration-token "{{ gitlab_token }}" \
  --name "{{ computername }}" \
  --tag-list "{{ gitlab_runner_tags }}" \
  --output-limit 16384 \
  --executor shell \
  --shell bash

Finally codesign
You can lookup the signing certificates hash using find-identity
security find-identity -p codesigning -v

Before beginning signing Xcode sets the environment variable CODESIGN_ALLOCATE to use the codesign_allocate that comes with Xcode, not in /usr/bin.
export CODESIGN_ALLOCATE="$( xcrun --find codesign_allocate )"

Codesign a framework, dylib, etc.
If you're codesigning manually, start with the frameworks and dylibs and after they are all signed, then sign the .app. Or in other words - you codesign from the bottom up.
/usr/bin/codesign --verbose=4 -f -s "$SIGNER_HASH" "$SIGNABLE"

Codesign the app bundle
After all the other signables are signed, sign the .app itself. In theory, you could do this all in one go with --deep, however, you would still need to make sure your app has entitlements and possibly other flags.
/usr/bin/codesign --verbose=4 -f -s "$SIGNER_HASH" "$SIGNABLE"

Flag passed to all items:

*

*--timestamp=none disable timestamps

Other flags to the app signing step:

*

*--entitlements /path/to/entitlements.xcent new entitlements

*--preserve-metadata=entitlements keep current entitlements

New codesign requirement - DER encoded entitlements
Apple has recently started requiring entitlements to not be embedded only in plist form, but also in DER encoded form. If you are using an older Mac/Xcode you might encounter the error...
The code signature version is no longer supported

A: My keychain was locked. It resisted my advances to change that fact...
Keychain Access -> Keychain First Aid -> Repair, et voilá!

A: I too have been fighting this.  Nothing helped until I tried the suggestion on http://devnet.jetbrains.com/thread/311971.  Thanks ashish agrawal!
Login your build user via the GUI and open Keychain Access.  Select your signing private key, right-click, choose Get Info, change to the Access Control tab and select the "Allow all applications to access this item".

A: Unlocking the keychain is not enough. You also have to set the private key access to "Allow all apps to access this item". And to do that from command line requires reimporting the key. So to take things at a time:
Unlock the login keychain if it is locked. It shouldn't be locked though, but anyway here's how you do that:
security -v unlock-keychain -p "$KEYCHAIN_PASSWORD" "~/Library/Keychains/login.keychain"

If for some reason your build machine has the login keychain locked, and you don't want to expose that password in a script, then you should use a different keychain. You can create one on the spot and use that in the previous and the following command. To create one on the spot:
security create-keychain -p 'temporaryPassword' MyKeychain.keychain
security list-keychains -d user -s login.keychain MyKeychain.keychain

Then import your certificates and associated private keys into the login keychain using the -A parameter. Note that you don't need to sudo for all this...
security import <cert.p12> -k "~/Library/Keychains/login.keychain" -P <passphrase> -A

The -A parameter is what will make your private key to be set to "Allow all apps to access this item"
So using all these you should be able to make a script that installs the required certificate to build a release ipa and sign it without prompt. You can store the .p12 file in your repo, so any machine can build your ipa without requiring manual setup.

A: Apart from unlocking keychain (as mentioned in another answers), you need to allow access from all applications to Xcode authentication token in keychain:

*

*Select "login" keychain

*Select "All Items" category

*Search for "xcode" keyword

*Select "Allow all applications to access this item" for all Xcode tokens

*Don't forget to add unlock keychain step (from previous answers)

A: None of the other answers worked for me.
What eventually saved me was this post
To sum it up, this can be caused by a default timeout of 5 minutes, that will trigger this error after a long build.
To fix:
security set-keychain-settings -t 3600 -l ~/Library/Keychains/login.keychain

A: Try to call security unlock-keychain and codesign as an one-line command. This helped me. Something like:
security unlock-keychain -p <password> /Users/<user>/Library/Keychains/login.keychain && codesign --force --verify --verbose --sign "<certificate id>" <app name>

A: Put your keys in the System keychain

A: Import your keys to System keychain. You can use this command:
sudo security import YourKey.p12 -k /Library/Keychains/System.keychain -P PasswordToYourKey -T /usr/bin/codesign

A: So I tried every answer here and something wasn't quite adding up.  Finally I figured out when I rebooted my CI service, it was running under a different user than I had expected.  Changing to the user that actually had access to the key in their login chain fixed everything.  This may not be a common problem, but wanted to document my specific reason for this error, in case it happens to others.

A: For me nothing worked seems have to reinstall Xcode all over again. Jenkins keeps giving the same error.
You would save lot of time if you just move Xcode installation to Trash and reinstall. Ensure you run the codesign command from command line atleast once.
Even after if you get the same error try setting 'Unlock Keychain?' property within Jenkins and give path to your login.keychain under /Users/${USER}/Library/Keychains/login.keychain
I hope god be with you after that.

A: In my case, this was caused by a keychain being created with a default timeout of 300s and a long xcode compile lasting more than 300s. The workaround, for me, was to invoke:
security set-keychain-settings -t <longer timeout in seconds> <keychain>

immediately after creating the temporary keychain.

A: I ran through all these suggestions and was still having problems using fastlane's gym in a Jenkins job. I had the certificate installed and keychain unlocked, and was able to codesign on the slave when I manually ran the codesign command on the command line.
As a workaround, if Jenkins connects to the slave using JNLP instead of SSH, you'll be able to codesign.

A: For me it happens when there is a second keychain added manually and it's locked. For some reason codesign tries to access the locked keychain and fails even though the certificates are in the login keychain (and is unlocked). Unlocking the second one solves the problem. Just doesn't make sense to me.

A: After trying a number of the above solutions.  I realized that one factor I had, was that I was starting the build using the ION Console.  When I switched back to making the build from the Terminal app, everything worked just fine.


text:
Q: Calling a function from cloud code I need to run a function from my Parse.com afterSave method but I'm new to javascript and something with the signature doesn't seem to work.
The function I'm trying to call follows the Parse.Cloud reference:
<static> {Parse.Promise} Parse.Cloud.run(name, data, options)

This is the function I want to call:
function funcToRun(data, response) {
    console.log("running funcToRun");
}

I'm trying to call it like this:
var data = "FilmName";
Parse.Cloud.run('funcToRun', data, "");

But no matter what I do the funcToRun doesn't get called.

A: Parse.Cloud.run runs a Cloud Function [1], not a regular JavaScript function. To make your code work, you need to define the function in the correct way.
In your case it would look like this:
Parse.Cloud.define('funcToRun', function(request, response) {
    console.log('running funcToRun');
    response.success();
});

[1] https://www.parse.com/docs/cloudcode/guide#cloud-code-cloud-functions

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I use Pandas to add a combination of dataframe loops that are not listed in python a = [["a1","b1"],["a2","b2"],["a3","b3"],["a4","b4"],["a5","b5"]]

df = pd.DataFrame({'A' : ["a1","a2","a3","a4"], 'B' : ["b1","b2","b3", "b4"] , 'mean' : ["13.4","12,1","10.0","11.5"]})

How do I add a combination that is not in the list "a" to the data frame row?
I want to use contains() or isin()
expected result
The list that does not exist populates the average of the values with the default 0.
pd.DataFrame({'A' : ["a1","a2","a3","a4","a5"], B' : ["b1","b2","b3", "b4","b5"] ,'mean' : ["13.4","12,1","10.0","11.5", "0"]})

A: Create DataFrame constructor and DataFrame.append to original, then remove duplicates by DataFrame.drop_duplicates by specify columns and last replace missing values by fillna:
a = [["a1","b1"],["a2","b2"],["a3","b3"],["a4","b4"],["a5","b5"]]

df1 = df.append(pd.DataFrame(a,columns=['A','B'])).drop_duplicates(subset=['A','B']).fillna(0)

print (df1)
    A   B  mean
0  a1  b1  13.4
1  a2  b2  12,1
2  a3  b3  10.0
3  a4  b4  11.5
4  a5  b5     0

Another idea with merge:
df1 = pd.DataFrame(a, columns=['A','B']).merge(df, how='left').fillna(0)


text:
Q: What kind of Doxygen (if any) is used in Linux Kernel and ccan? I am a bit baffled because some files in Linux kernel (notably include/linux/list.h) and all files is ccan have documentation comments resembling Doxygen ones (i.e.: enclosed in `/** ... */), but semantically different and Doxygen (at least with pretty standard options) chokes on them.
Typical example is (linux list.h):
/**
 * INIT_LIST_HEAD - Initialize a list_head structure
 * @list: list_head structure to be initialized.
 *
 * Initializes the list_head to point to itself.  If it is a list header,
 * the result is an empty list.
 */
static inline void INIT_LIST_HEAD(struct list_head *list)
{
        WRITE_ONCE(list->next, list);
        list->prev = list;
}

where I (and also Doxygen, I suspect) would have expected something like:
/**
 * INIT_LIST_HEAD - Initialize a list_head structure
 *
 * Initializes the list_head to point to itself.  If it is a list header,
 * the result is an empty list.
 *
 * @param list list_head structure to be initialized.
 */
static inline void INIT_LIST_HEAD(struct list_head *list)
{
        WRITE_ONCE(list->next, list);
        list->prev = list;
}

Is this kind of documentation supposed to be digested by some other tool or am I simply missing some obscure (to me) parameter/configuration?
UPDATE:
I am aware (as @albert commented) that order is unimportant; what I find disconcerting is usage of @variable_name: doc string instead of @param variable_name doc string.
Trying to use Doxygen without specific care results in:
list.h:195: warning: Found unknown command '@list'

I could find no Doxyfile in either project and that's one reason why I suspect they're using some other tool, but I cannot divine what and how they're using it.
I will try to contact ccan maintainer directly.


text:
Q: Cedilla no longer working with US Intl. keyboard layout I'm using Ubuntu 20.04.4 LTS with the US Intl. keyboard layout, but when I type ', then c, I'm now getting a ć instead of the regular ç. How can I fix this?

A: Found the solution in another forum/website:
Append this line to /etc/environment:
export GTK_IM_MODULE=cedilla

Log in again. Cedilla now works as expected: ' + c
Source: https://forums.linuxmint.com/viewtopic.php?t=30102


text:
Q: Physics in OO game programming So I am in the process of trying to learn how to develop 2D games.
I am playing around with both Android and C#.
The issue that I am having is this.
It is easy enough to draw a sprite of some sort. Where I struggle is to visualize how one can code interactions of various objects on screen.
For example lets say I have the following Object.
public class MyGenericObject {
    public MyGenericObject() {}
    public Int32 Width { get; set; }
    public Int32 Height { get; set; }
    public Int32 X { get; set; }
    public Int32 Y { get; set; }
    public Image ObjectImage { get; set; }
}

Lets say I want to model the behavior of an interaction between N number of these Objects. What is a typical pattern one would utilize in such a scenario?
So for example would you simply call a method such as MyPhysicsSim.DoPhysics(List<MyGenericObjects>);
Assuming this is not a huge stretch. Inside of this method then, how do you calculate the interactions and resulting movements? I just can't get my head around it (Obviously I do understand that there are basic equations that can solve direction and speed and so forth but I just can't seem to work out how to apply these as an algorithm).
I have looked at numerous tutorials and all of them seem to concentrate on just drawing an object or assume a level of understanding about the internals that is way over my head. So I am hoping for a really simple, dumbed down response.
So basically what I am asking is how do you approach interactions between 2D objects in a OO paradigm for dummies?

A: Traditionally, most games have a loop similar to the one below somewhere at the core:
while (1) {
    World.respondToInput();
    World.updatePhysics();
    World.renderScene();
    Timer.waitUntilFrameExpires();
}

and the 'updatePhysics()' method can do something very basic, such as:
for (Object obj1 in World.trackedObjects()) {
    for (Object obj2 in World.trackedObjects()) {
        if (obj1.influences(obj2)) {
            obj1.update(); obj2.update();
        }
    }
}

So you basically have a 'tick' in the world you're simulating, and your code works to reflect the delta in the scene that would have occurred.


text:
Q: Create and execute .bat file in spring web mvc I have several questions:

*

*How to create and execute .bat file in Spring MVC?

*While the execution process show in progress bar

A: If I'm not mistaken, what you're asking for has less to do with Spring, and more related to the underlying Java solution.
Creating a batch .bat file with Spring is as straight forward as opening a new FileWriter(new File()) and writing in everything you need, but making sure to append ".bat" as the filename's extension.
As for execution, you can use Spring's SimpleAsyncTaskExecutor on a custom created class of yours, provided that it implements Runnable. If you're looking for a recommendation as to how exactly to run the bat, this little snippet will work perfectly:
Runtime.getRuntime().exec("cmd /c start batchFile.bat");

The idea here is that you can get the Java runtime to execute the Windows command line with those arguments. ("/c" closes cmd on finish).
On the topic of a progress bar, I suspect you will have much difficulty with that, but a solution may lie with having the batch file output progress to System.out(the underlying system resource) and then having your Spring app redirect(?) and read from it.


text:
Q: Usage of joda.time in icCube I would like to use the following MDX statement:
with member [x] as now()->plusMonths(1)->withDayOfMonth(1)->minusDay(1)
select [x] on 0
from sales

But I get the error "withDayOfMonth" is unknown.
I know the function "plustMonths()" works fine. How can I make this other Joda function work?
The following line is active in the icCube.xml. The help explicitely states to add child packages as well if these are required, but I do not know if withDayOfMonth is a child package and I do not know where to find that:
<allowedPackage>org.joda.time</allowedPackage>

A: Unfortunately, now() is creating an internal date/time object that do not support yet all the JODA methods (we'll add them in the next release). In the meantime, here are several way to compute the end of month:
with
 // Be aware it is the server's end of month not the client, if you don't see the problem you've been lucky...for the time being.

 // using MDX functions ( function can be added to the schema )
 function ic3_EOM() as DateTime( now().year() , now().month() +1, 1 )->plusDays(-1)

 // using JODA DateTime ( function can be added to the schema )
 function ic3_EOM_2() as J!org.joda.time.DateTime()->plusMonths(1)->withDayOfMonth(1)->minusDays(1)->toLocalDate()

 member [ic3_EOM] as ic3_EOM()
 member [ic3_EOM_2] as ic3_EOM_2()

select { [ic3_EOM], [ic3_EOM_2] } on 0 from [sales]


text:
Q: Sending string from wpf application to an asp.net website in secure way I'm trying to send a string to a asp.net website and get a result string from the website.
Found this code to send string
How could I get this string on an asp.net website.
string dataToSend = "data=" + HttpUtility.UrlEncode("ABCDEFGH12345678");
var dataBytes = System.Text.Encoding.UTF8.GetBytes(dataToSend);

HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://www.babels.ir");
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = dataBytes.Length;
req.Method = "POST";

using (var stream = req.GetRequestStream())
{
    stream.Write(dataBytes, 0, dataBytes.Length);
}

// -- execute request and get response
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
if (resp.StatusCode == HttpStatusCode.OK)
    Console.WriteLine("Activation code received");


text:
Q: password reset with jwt structure I'm trying to write the password reset part of my authentication app. I chose to use JWT, node.js and express where I use the following logic: first, the user enters their email and a token is generated and sent to the user's mail in a password reset link. second, when the user presses the link  a function is set to check if the token is correct and if it's still valid and third i have a function to save the new password to the database.
What I'm uncertain about is the second step where the token is supposed to be checked. Some tutorials say that you're supposed to save the token to your database and then compare the token in the link to the token in the database. But isn't the point with using JWT to not save anything to the database as reference? Shouldn't I just use jwt.verify to get the information saved in the token and then check for the user in the database and if it's still active?
Is this the correct way of using JWT? Or would you recommend me to use session instead of JWT?

A: There's a good suggestion in this answer. You can use some hash of your currently stored password value as part of the password reset JWT.
So the payload might contain { sub: user_id, exp: "now + 10 minutes", purpose: "password_reset", key: hash(hashed_password_from_db).substr(0, 6) }. This token can only be used successfully once.

A: There is a simple flaw in the use of JWT for reset password implementation.
From your current implementation, A user can generate the reset password link multiple times. So a user can have many active reset token in a given time.
Yes, JWT statelessness can be adopted, but it is not efficient in this case as you can have multiple tokens which can be used to reset the password even after the user has reset the password(depending on your approach).
I work in an organisation where testing and security is paramount. Your implementation would not be allowed.
The rule is that only one reset password link can be active at a time.
So JWT token is not the best option for us.
So what I do is to generate a random token saved in the DB(also with the current time). This token is to identify the user and, the time is to validate that the user is resetting withing a given time.
While the token is active, if a user decides to generate the token again, the former token is made inactive before a new one is generated.
The advantage of this method is that you can only have one active token at a time.
Lastly, JWT should be used if you don't mind a user having multiple active tokens/links at a time.


text: Q: Caracteres extraños mysqli_set_charset en mi base de datos le asigne como siempre el utf-_Spanish_ci para los acentos y demas esto va bien a ecepcion de la letra  ñ me la esta lanzando con un simbolo muy extraño un signo de interrogacion dentro de un diamante por asi decirlo intente poner en el archivo de conexion mysqli_set_charset("utf8",$con) esto funciono osea me arroja la letra ñ normal pero entonces las letras con acentos aparecen mal con mas simbolos extraños alguien puede decirme que esta pasando si tengo el cotejamiento de mi base de datos bien es decir utf-_Spanish_ci me imagino que es lo correcto


text:
Q: Recieving an "errorCode: ERROR_RESOURCE_GONE" when trying to send play command I have been trying to figure out the sonos api over the past few days, but unfortuanetly have hit a road block. I have already gotten my tokens and room names and and favorites Id, but when I send the curl request to play a song I get the error described above.
Curl Code :
curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer {TOKEN}" "https://api.ws.sonos.com/control/api/v1/groups/RINCON_48A6B88A5B14014XX:XXXXXXXXXX/favorites" --data @play.json
I keep the body in a .json file called play which contains the code:
{
"favoriteId":2,
"playOnCompletion":true
}
I have not been able to find any documentation on this issue online, so any and all help is very appreciated.

A: The "ERROR_RESOURCE_GONE" HTTP 410 response indicates that the
groupID you are using in your request (RINCON_48A6B88A5B14014XX:XXXXXXXXXX) no longer exists. Group IDs are not static and may change depending on a number of factors - grouping and ungrouping, power cycling, etc.
If you re-run the request to get groups, you should get an up-to-date list of group IDs. Try doing that and using a returned Group ID in your favorites request.
The "Subscribe" section of the documentation describes how to automatically listen for group ID changes: https://developer.sonos.com/build/direct-control/connect/

A: Have you made sure that the groupId or the favoriteId are still valid? Based on the ERROR_RESOURCE_GONE, it seems one of those has likely changed.


text:
Q: Spring Security web app can't remove auto login I want to remove the login that is required after every time I start the app. I go to localhost:3306 and it redirects me to the /login. I will have a login button on the webpage but I cannot get to that because this is in the way.
I tried this but it still wants me to login when the app starts.
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .antMatchers("/profile").authenticated()
            .anyRequest().permitAll()
            .and()
        .formLogin()
            .usernameParameter("email")
            .defaultSuccessUrl("/profile")
            .permitAll()
            .and()
        .logout()
            .logoutSuccessUrl("/")
            .permitAll();
}

A: try this in your file application.properties...
security.basic.enabled=false

I dont know your project but you can try disable formLogin in your security configuration too...
http.formLogin().disable()

A: To disable security you must try the following lines in your

application.properties

security.basic.enabled=false
management.security.enabled=false


text:
Q: Mutt PGP Error: "Could not decrypt PGP message" & "Could not copy message" on Ubuntu machine but works on macOS machine Configuration files are identical on both machines since they are shared from a cloud drive.
Messages sent as a test to myself from the Ubuntu machine 'can' be decrypted and read on the macOS machine in mutt with no problems. Also, both machines sending to themselves work.
The problem is decrypting the messages on the Ubuntu machine sent from the macOS.
The Ubuntu machine has a GnugPG version which is a little older (2 years) than the macOS machine but both are above version 2.1 which saw some changes from previous versions.
I'm not using gpgme or its gpg-agent in the configuration files since I had issues with it a) defaulting to s/mime instead of PGP, b) not accepting self-signed X509 certs.
Pure PGP config
MUTT ERROR MSG
On selecting a message in mutt's message index, I get the following:
Invoking PGP ...
Could not decrypt PGP message
Could not copy message

QUESTION

*

*Is this a GnuPG backward compatibility issue?

*Can this be resolved and how?

Version Details
macOS:
$ gpg --version
gpg (GnuPG) 2.3.4
libgcrypt 1.10.0
Copyright (C) 2021 Free Software Foundation, Inc.
License GNU GPL-3.0-or-later <https://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Home: /Users/tonybarganski/.gnupg
Supported algorithms:
Pubkey: RSA, ELG, DSA, ECDH, ECDSA, EDDSA
Cipher: IDEA, 3DES, CAST5, BLOWFISH, AES, AES192, AES256, TWOFISH,
        CAMELLIA128, CAMELLIA192, CAMELLIA256
AEAD: EAX, OCB
Hash: SHA1, RIPEMD160, SHA256, SHA384, SHA512, SHA224
Compression: Uncompressed, ZIP, ZLIB, BZIP2

---
Mutt 2.2.1 (2022-02-19)
Copyright (C) 1996-2022 Michael R. Elkins and others.

Compile options:
-DOMAIN
+DEBUG
-HOMESPOOL  +USE_SETGID  +USE_DOTLOCK  +DL_STANDALONE  +USE_FCNTL  -USE_FLOCK
+USE_POP  +USE_IMAP  +USE_SMTP
+USE_SSL_OPENSSL  -USE_SSL_GNUTLS  +USE_SASL  -USE_GSASL  +USE_GSS  +HAVE_GETADDRINFO
+HAVE_REGCOMP  -USE_GNU_REGEX
+HAVE_COLOR  +HAVE_START_COLOR  +HAVE_TYPEAHEAD  +HAVE_BKGDSET
+HAVE_CURS_SET  +HAVE_META  +HAVE_RESIZETERM  +HAVE_FUTIMENS
+CRYPT_BACKEND_CLASSIC_PGP  +CRYPT_BACKEND_CLASSIC_SMIME  +CRYPT_BACKEND_GPGME
-EXACT_ADDRESS  -SUN_ATTACHMENT
+ENABLE_NLS  -LOCALES_HACK  +HAVE_WC_FUNCS  +HAVE_LANGINFO_CODESET  +HAVE_LANGINFO_YESEXPR
+HAVE_ICONV  -ICONV_NONTRANS  -HAVE_LIBIDN  -HAVE_LIBIDN2  +HAVE_GETSID  +USE_HCACHE
+USE_SIDEBAR  -USE_COMPRESSED  -USE_INOTIFY
-ISPELL

Ubuntu20.04
gpg (GnuPG) 2.2.19
libgcrypt 1.8.5
Copyright (C) 2019 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Home: /home/tony/.gnupg
Supported algorithms:
Pubkey: RSA, ELG, DSA, ECDH, ECDSA, EDDSA
Cipher: IDEA, 3DES, CAST5, BLOWFISH, AES, AES192, AES256, TWOFISH,
        CAMELLIA128, CAMELLIA192, CAMELLIA256
Hash: SHA1, RIPEMD160, SHA256, SHA384, SHA512, SHA224
Compression: Uncompressed, ZIP, ZLIB, BZIP2

---
Mutt 1.13.2 (2019-12-18)
Copyright (C) 1996-2016 Michael R. Elkins and others.
Mutt comes with ABSOLUTELY NO WARRANTY; for details type `mutt -vv'.
Mutt is free software, and you are welcome to redistribute it
under certain conditions; type `mutt -vv' for details.

System: Linux 5.13.0-35-generic (x86_64)
ncurses: ncurses 6.2.20200212 (compiled with 6.2)
libidn: 1.33 (compiled with 1.33)
hcache backend: tokyocabinet 1.4.48

Compiler:
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/9/lto-wrapper
OFFLOAD_TARGET_NAMES=nvptx-none:hsa
OFFLOAD_TARGET_DEFAULT=1
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu 9.3.0-17ubuntu1~20.04' --with-bugurl=file:///usr/share/doc/gcc-9/README.Bugs --enable- languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++,gm2 --prefix=/usr --with-gcc-major-version-only --program-suffix=-9 --program-prefix=x86_64-linux- gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-     nls --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-  vtable-verify --enable-plugin --enable-default-pie --with-system-zlib --with-target-system-zlib=auto --enable-objc-gc=auto --enable-multiarch --      disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-           targets=nvptx-none=/build/gcc-9-HskZEa/gcc-9-9.3.0/debian/tmp-nvptx/usr,hsa --without-cuda-driver --enable-checking=release --build=x86_64-linux-     gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 9.3.0 (Ubuntu 9.3.0-17ubuntu1~20.04)


text:
Q: total up json data? [UPDATE]
Thanks guys,final code:
        var EUR_share_cost = 0;
        var USD_share_cost = 0;
        var GBP_share_cost = 0;
        var EUR_total_cost = 0;
        var USD_total_cost = 0;
        var GBP_total_cost = 0;

        $.ajax({
            url: '/producer/json/index/period/month/empties/'+empties+'/fields/'+fields+'/start/'+start+'/end/'+end+'',
            async: false,
            success: function(returned_values) {

                 $.each(returned_values.aaData, function(index, item) {

                    if (item[2] == 'EUR') {
                        EUR_share_cost  += parseFloat(item[5]);
                        EUR_total_cost  += parseFloat(item[3]);

                    } else if (item[2] == 'USD') {
                        USD_share_cost += parseFloat(item[5]);
                        USD_total_cost += parseFloat(item[3]);

                    } else if (item[2] == 'GBP') {
                        GBP_share_cost += parseFloat(item[5]);
                        GBP_total_cost += parseFloat(item[3]);
                    }
                });
            }
        });

        $('#EUR_share_cost').html(EUR_share_cost);
        $('#USD_share_cost').html(USD_share_cost);
        $('#GBP_share_cost').html(GBP_share_cost);

    }

});

A: When you're in $.each(), the callback has 2 parameters, the first is the index (that incrementing number you're seeing), the second is the actual item, you'd actually want something like this:
 $.each(returned_values || {}, function(index, item) {
   console.log(item);
 });

I think overall you're looking for this:
var eur_total = 0;
$.each(returned_values && returned_values.aaData || {}, function(index, item) {
   if(item[2] == "EUR") eur_total += parseFloat(item[3]);
});
$('#EUR-total').val(eur_total);

This would total up the third column...not sure which column you're after (maybe 5th?), you can give it a try here.

A: The first part of $.each is the index, the second part is the data see the documentation for details.
Your code should instead look like this:
$.ajax({
    url: '/area/json/index/period/month/',
    async: false,
    success: function(returned_values) {
        console.log(returned_values);
        $.each(returned_values || {}, function(index,item) {
            console.log(item);
        });
    }
})


text:
Q: How can I split a long HTML table using print-CSS, so that the split in the table on the first page leaves space for a div at the bottom of the page? I have a mutli-page document that is displayed in a browser window. The document is a long table and a legend.
I want the table to stop printing some 300 pixels before the bottom of the page, then print the legend, and then continue printing the table on the second page.

The red line indicates where I want the table to break.
How ?
What I have so far:
Currently I was able to print the legend at the bottom of the first page, using CSS below:
    @media print {
        #legend {
            position: absolute;
            bottom: 0;
        }
    }

But my table is printing right over the legend div, superimposing itself over the legend.
What I need is for the table div to stop printing before the legend div, then print the legend div, then continue the table on the next page.
Hack #1
I could force a page break on a certain row, by using

This kinda works but not exactly great, since it's hardcoded.  Table data changes, moving table border up and down.
I would like to ideally find a better way to handle these.


text:
Q: UnableToDeserializePostBody when trying to create a teams meeting with php Microsoft Graph Api Calling Graph API endpoint
POST https://graph.microsoft.com/v1.0/me/events

resulted in a 400 Bad Request with response:
{
    "error": {
      "code":"UnableToDeserializePostBody",
      "message":"were unable to deserialize..."
    }
}

This is my code:
$token = GraphHelper::getUserToken();
GraphHelper::$userClient->setAccessToken($token);

$CreateMeetingBody =
array(
    'message' => array (
        'subject' => 'Test afspraak Marloes',
        'body' => array (
            'content' => 'Does morning work for you?',
            'contentType' => 'HTML'
        ),
        'start' => array (
            'dateTime' => '2022-07-17T18:00:00',
            'timeZone' => 'Europe/Paris'
        ),
        'end' => array (
            'dateTime' => '2022-07-17T19:00:00',
            'timeZone' => 'Europe/Paris'
        ),
        'location' => array (
            'displayName' => 'Microsoft Teams',
        ),
        'attendees' => array (
            array (
                'emailAddress' => array (
                    'address' => 'stijnd0413@icloud.com',
                    'name' => 'Stijn Deckers'
                ),
                'type' => 'required'
            )
        ),
        'allowNewTimeProposals' => false,
        'isOnlineMeeting' => true,
    )
);

$headers = [
        'Content-Type' => 'application/json',
    ];

header('Content-Type: application/json; charset=utf-8');

$CreateMeetingJSON = json_encode($CreateMeetingBody);

GraphHelper::$userClient->createRequest('POST', '/me/events')
                        ->attachBody($CreateMeetingJSON)
                        ->addHeaders(['Content-Type' => 'application/json',])
                        ->execute();

'''
The rest of the code works and I am able to authenticate.

A: Remove message object from $CreateMeetingBody and keep its content only.
$CreateMeetingBody =
array(
        'subject' => 'Test afspraak Marloes',
        'body' => array (
            'content' => 'Does morning work for you?',
            'contentType' => 'HTML'
        ),
        'start' => array (
            'dateTime' => '2022-07-17T18:00:00',
            'timeZone' => 'Europe/Paris'
        ),
        'end' => array (
            'dateTime' => '2022-07-17T19:00:00',
            'timeZone' => 'Europe/Paris'
        ),
        'location' => array (
            'displayName' => 'Microsoft Teams',
        ),
        'attendees' => array (
            array (
                'emailAddress' => array (
                    'address' => 'stijnd0413@icloud.com',
                    'name' => 'Stijn Deckers'
                ),
                'type' => 'required'
            )
        ),
        'allowNewTimeProposals' => false,
        'isOnlineMeeting' => true
);

Now json_encode($CreateMeetingBody) will produce the correct json body
{
  "subject": "Test afspraak Marloes",
  "body": {
    "content": "Does morning work for you?",
    "contentType": "HTML"
  },
  "start": {
    "dateTime": "2022-07-17T18:00:00",
    "timeZone": "Europe/Paris"
  },
  "end": {
    "dateTime": "2022-07-17T19:00:00",
    "timeZone": "Europe/Paris"
  },
  "location": {
    "displayName": "Microsoft Teams"
  },
  "attendees": [
    {
      "emailAddress": {
        "address": "stijnd0413@icloud.com",
        "name": "Stijn Deckers"
      },
      "type": "required"
    }
  ],
  "allowNewTimeProposals": false,
  "isOnlineMeeting": true
}


text:
Q: UFW Firewall rule not working I have an ubuntu vm which runs the UFW and a microsoft xp professional. The ip address of the ubuntu is 192.168.254.132 and so I made the xp have a static ip address of 192.168.254.131 so they will be on the same network. I tried using telnet to connect to the Ubuntu it failed, which was suppose to happen because of the implicit deny. However when I typed sudo ufw allow from 192.168.254.131 to any port 23 to allow telnet it still did not work. I do not know what is wrong.

A: You have to delete the deny rule as the deny rule will trump the allow rule.
Because the deny is still in place, allow will not work.


text:
Q: Dense subgroup of a compact connected Lie group generated by two words Let $G$ be a compact connected Lie group and $w_1$, $w_2$ be two positive words in alphabet  $\{a, b\}$ which are not the powers of some another word $w$. Positive means that $a^{-1}$ and $b^{-1}$ can not be used.
For example the pair $w_1=ab$ and $w_2=ba$ is allowed. And the pair $w_1=ababab$ and $w_2=abab$ is not allowed. The pair $w_1=aba^{-1}b^{-1}$, $w_2=a$ is also not allowed, as $w_1$ is not positive.
Question: is it true that for a typical ( with respect to the Haar measure on $G$) pair $(a, b)\in G^2$ the subgroup generated by $w_1(a,b)$ and $w_2(a,b)$ is dense in $G$?

A: See the result of Gerstenhaber-Rothaus, which says that if the abelianization of the word map has full rank, then the map $G\times G\to G\times G$ has non-zero degree. This is a necessary condition, as one can see if $G$ is abelian or has an abelian quotient (e.g. $U(n)$).
So this won't apply to $\{ab,ba\}$.
Once the map is non-zero degree, the pushforward of the Haar measure on $G\times G$ should be absolutely continuous with respect to Haar measure. This is because the map is also algebraic, and hence the preimage of points are smaller dimension, so the preimage of a set of measure $0$ will be measure $0$.
A theorem of Weyl implies that a compact subgroup of an algebraic group over $\mathbb{R}$ is an algebraic subgroup. Now we follow the argument in Barnea-Larsen, section 3.
Barnea, Y.; Larsen, M., Random generation in semisimple algebraic groups over local fields., J. Algebra 271, No. 1, 1-10 (2004). ZBL1049.20028.
Let's assume that $G$ is semisimple; I think that the general case can be reduced to this case. Since $G$ is compact, we may complexify to get a semisimple algebraic group $G^{\mathbb{C}}$ over $\mathbb{C}$. By Lemma 3.2, there is a countable set $\{X_0,X_1,\ldots\}$ of proper closed subvarieties such that if $\gamma\in G^{\mathbb{C}}- \cup_i X_i(\mathbb{C})$, then the Zariski closure of $\gamma$ is a maximal torus. Passing to $G=G^{\mathbb{R}}$, the real subgroup, we see that the same is true for $G$. Hence with probability $1$, any element $\gamma\in G$ will have closure a maximal torus.
Proposition 3.3 states that there is a proper closed subvariety $X \subset G^{\mathbb{C}}\times G^{\mathbb{C}}$ so that for any proper algebraic subgroup $H$ containing a maximal torus, $H\times H \subset X$.
Now choose a random pair of elements $(\gamma_1,\gamma_2)\in G\times G$ with respect to a measure absolutely continuous with respect to Haar measure. Then with probability $1$, $\overline{\langle\gamma_i\rangle}$ is a maximal torus, since $\cup_i{X_i(\mathbb{R})}$ has measure $0$. Then if $\langle \gamma_1,\gamma_2\rangle$ is not dense in $G$, then $\overline{\langle \gamma_1,\gamma_2\rangle}=H < G$, where $H$ is closed and contains a maximal rank torus. So $(\gamma_1,\gamma_2)\in X$, again occurring with probability $0$.
I think this gives an outline of a proof under these assumptions.


text:
Q: How to setup rounded corner menu in joomla Does anyone know how to setup a round corner menu in joomla? I need each item in the menu to have rounded corner.

A: Are you having trouble creating the rounded corner images or trouble using them in the template?
I would go to SpiffyBox.com (http://spiffybox.com) or CoolText.com (http://cooltext.com/) to easily generate the buttons or background image you want to use for the menus.
To use your new images in the menu, you will probably have to connect to the website via FTP, upload your images to the correct folder, and then edit the template so that it uses the correct images.
The easiest way to do this is to find the folder on the server where the current menu images are stored, name your new buttons the same names as the ones being used, and upload the new images, overriding the current images with the new ones. Then you won't have to edit the path to the images, the template will automatically display your new ones since they have the same name the old ones did. Of course, before you do override the old images, I would download and save the current images so you have them if the new buttons dont work!
A few things you will need to be careful about are: either the new buttons need to have the exact same dimensions as the current buttons; or (if the new buttons don't have the same dimensions) you will need to edit the menu attributes (height, width, etc.) in your template's stylesheet so that the new buttons display properly without throwing off the whole template.
Hope this helps! let me know if you have questions...


text:
Q: Assigning var to var in C float p, q, x1, x2;

p=(-b-sqrt(b*b-4*a*c))/(2*a);
q=(-b+sqrt(b*b-4*a*c))/(2*a);

if(p<q){
    p=x1;
    q=x2;
}

else{
    p=x2;
    q=x1;
}

I want to assign these values if the conditions are true, however, I get only 0 values from x1 and x2.
Can you point out where I'm wrong?

A: float p, q, x1, x2;

p=(-b-sqrt(b*b-4*a*c))/(2*a);
q=(-b+sqrt(b*b-4*a*c))/(2*a);

if(p<q){
    x1=p;
    x2=q;
}

else{
    x2=p;
    x1=q;
}

I think you are trying to calculate p and q using some math formulae and then assigning them to x1 and x2. However the way you are doing the assignment is reverse. So I've corrected it. Hope it helps.


text:
Q: Sorting and outputting in another file How can I sort a file and output it to a newly created file?
Let's say I have Names.txt containing a list of names. I want to reverse sort Names.txt; create a new file called SortedNames.txt; and output the sort to the newly created file; ideally, these should be done in a single statement.

A: To sort Names.txt in a reverse sort order and output it into SortedNames.txt:

sort -r Names.txt > SortedNames.txt
The file SortedNames.txt does not have to exist. If it does exist and you have write-permission to that file, the command above will overwrite its contents.
The sort command has many more options.


text:
Q: Unknown pointer glitch on my windows 10 Hi I am using windows 10 with wireless mouse and Recently I started facing this issue please check below link which shows video capture of the issue
https://streamable.com/5t3c0
Not sure what this issue is called but frustrates me to the highest point, it doesn't allow me to work with pointer being blinking in the circles
I contacted Microsoft help they ran some troubleshooting steps still issue is not solved, I tried resetting the laptop but still issues exists can anyone throw some light if anyone faced this kind of issue


text:
Q: E-Mail Validation with JavaScript & Error logging using Arrays The following code pushes "eMail" into the errors array even when a valid e-mail address is entered. What am I doing wrong?
if ( /^([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x22([^\x0d\x22\x5c\x80-\xff]|\x5c[\x00-\x7f])*\x22)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x22([^\x0d\x22\x5c\x80-\xff]|\x5c[\x00-\x7f])*\x22))*\x40([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x5b([^\x0d\x5b-\x5d\x80-\xff]|\x5c[\x00-\x7f])*\x5d)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x5b([^\x0d\x5b-\x5d\x80-\xff]|\x5c[\x00-\x7f])*\x5d))*$/.test( $("input[name=email]").val() ) != true ) errors.push("eMail");

Relevant HTML:
E-Mail Address:<br><input name="eMail">

A: $("input[name=email]").val() is never a valid e-mail address because the actual name of the input is eMail, not email, meaning that the input value of email is always empty.
The regular expression can be found at http://badsyntax.co/post/javascript-email-validation-rfc822 or by Googling "RFC822 JavaScript E-Mail"


text:
Q: Any flaw in the logic of using qtimer and qthread? I have a GUI developed using pyqt4 which has a run button. on run button click, I invoke a timer and a thread. the timer keeps monitoring the thread. on the thread I invoke a command prompt to execute the test cases. I want the thread to be alive till the command prompt is opened and want to say it as dead once I close the command prompt.
The code that I had written to achieve this is as below. Any logic flaws? or any better way to achieve this?
self.connect(self.run_button, SIGNAL('clicked()'), self.runscript)

 def runscript(self):
    self.timer = QTimer()
    self.timer.connect(self.timer, SIGNAL("timeout()"),self.sendData)
    self.timer.start(1000)

def sendData(self):

    if self.run_timer:
        run_monitor_object = RunMonitor()
        print 'Starting the thread...........'
        run_monitor_object.start()
        self.run_timer = False

    if run_monitor_object.isAlive():
        print 'Thread Alive...'
    else:
        print 'Thread is Dead....'

class RunMonitor(threading.Thread):
    def __init__(self, parent=None):
        threading.Thread.__init__(self)
    def run(self):
        print 'Invoking Command Prompt..........'
        subprocess.call(["start", "/DC:\\Scripts", "scripts_to_execute.bat"], shell=True)

When I run this, I get the following error...
UnboundLocalError: local variable 'run_monitor_object' referenced before assignment at if run_monitor_object.isAlive():
Just wondering how else, I could

A: This code:
if self.run_timer:
    run_monitor_object = RunMonitor()
    print 'Starting the thread...........'
    run_monitor_object.start()
    self.run_timer = False

if run_monitor_object.isAlive():
    print 'Thread Alive...'
else:
    print 'Thread is Dead....'

Is wrong. If the first branch isn't taken (perhaps in a second invocation when self.run_timer is already True), run_monitor_object isn't assigned, and you attempt to use it in the second if.
To make this work, make run_monitor_thread an instance variable of the class.
Also, why start the thread in the timer? This is just needlessly complicating your logic. Start it when you create the timer. The timer will then be used to monitor it.


text:
Q: Can adobe photoshop run with a screen resolution below the requirements? If adobe photoshop CS5 link to requirements page says that it requires 1024x768 display (1280x800 recommended), will it run on a computer with Resolution 1024 x 600 at all? Will it be the case of an aesthetic hindrance or it won't run properly (severe problems like tools not being visible, crashes etc)? I would like to run it on a netbook of 10.1inch such as this one.

A: You will be able to install, but your the program will go off the screen. (Tools won't be visible.)
I might consider reccomending that you use an external monitor (you may need an external graphics card also) or jsut using another computer.
See this fourm for more info.

A: Due to the differing resolution being the vertical value (1024 is the width of the screen), the things that may not appear would be the status bar at the bottom of the application.
Generally, application positions are plotted from the upper left corner. In this case this means the application is looking for an extra 168 pixels on the bottom of the screen (768 - 600), but width should be just fine (1024).
So you'll probably see your toolbars and menus just fine, unless you happen to keep those toolbars and menus on the bottom of the screen.


text:
Q: bootstrap modal body doesn't appear hello everyone i need help. i wanna show dinamic data to bootstrap modal body.
here is my code so far :

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

Detail

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


text:
Q: How to upgrade WinForm infragistics v12.1 to 14.1 I have add new infragistics references version 14.1 to my references(v12.1) by using utility and so when i add references with new version than i got some errors...

"Error 6404    The type or namespace name 'Infragistics' could not be found (are you missing a using directive or an assembly reference?  ...etc"

it is still finding references of the old version

A: After installing Infragistics 2014, you should see a menu item in Visual Studio called INFRAGISTICS.  Click on that and click on Check for Updates.  It will scan your projects for old references, and upgrade all the namespaces and controls to the latest versions.  Click on the Upgrade button next to each project that comes up in the list.  This will remove all the errors.

A: Check references to Infragistics dll(s) in your application's config file.


text:
Q: sshd: Could not load host key Running /usr/sbin/sshd produces the following results:
Could not load host key: /etc/ssh/ssh_host_rsa_key
Could not load host key: /etc/ssh/ssh_host_dsa_key
Could not load host key: /etc/ssh/ssh_host_ecdsa_key
Could not load host key: /etc/ssh/ssh_host_ed25519_key
Missing privilege separation directory: /var/run/sshd

I checked in /etc/ssh and all 4 host keys (and their .pub files) seem to be available, although /var/run/sshd is missing.
What can I do to let it load the host keys?

A: Run the command with sudo:
sudo /usr/sbin/sshd

If you still get the privilege separation directory error:
sudo mkdir /var/run/sshd && sudo chmod -R 755 /var/run/sshd


text:
Q: "Unexpected end of JSON input" on a Void SpringMVC Ajax Controller I have a SpringMVC/Thymeleaf applications where the following Ajax handling works perfectly fine if I return a boolean. However, as soon as the method is void, then I get the error
Unexpected end of JSON input in Firebug. This is a POST request.
@ResponseBody
@PostMapping("/addOrUpdate")
public void /*boolean works!*/ addOrUpdate(@RequestBody String json) throws Exception {
    service.addOrUpdateUserRoles(json);
    /*boolean works - return true;*/
}

JS
 $.ajax({
        type : "post",
        dataType : 'json',
        contentType : 'text/plain',
        url : 'addOrUpdate',
        data : id
 })
 .then(function() {
     //...
 })
 .fail(function(jqXHR, textStatus, errorThrown) {
     //...
 });

If I just remove @ResponseBody from the method definition, Thymeleaf complains,
org.thymeleaf.exceptions.TemplateInputException: Error resolving template [addOrUpdate], template might not exist or might not be accessible by any of the configured Template Resolvers
I followed the ResponseEntity example here, but it didn't help -- same error, JS goes into the Error section with Unexpected End of Input.
@ResponseBody
@PostMapping("/addOrUpdate")
public ResponseEntity addOrUpdate(@RequestBody String json) throws Exception {
    service.addOrUpdate(json);
    return new ResponseEntity(HttpStatus.OK);
}

A: With dataType : 'json', you are telling jQuery that you're expecting JSON as a response. An empty response is no valid JSON, and the error message Unexpected end of JSON input is telling you exactly that.
If you intend not to return anything from the addOrUpdate controller method, remove the @ResponseBody annotation, as there is no response body, and stick to the ResponseEntity but use HttpStatus.NO_CONTENT instead to inform clients in your response that there's no content to be expected. Also, change your dataType to something that may be empty, like 'text'.

A: As the exception says, the point of failure is input.
You need to send json format input.
$.ajax({
        type : "post",
        dataType : 'json',
        contentType : 'text/plain',
        url : 'addOrUpdate',
        data : {id: id}
...

A: FINAL SOLUTION based on digitalbreed's answer
Controller
@PostMapping("/addOrUpdate")
public ResponseEntity<String> addOrUpdate(@RequestBody String json) throws Exception {
    try {
        service.addOrUpdate(json);
        return new ResponseEntity<String>(HttpStatus.OK); // No exceptions
    }
    catch (Exception e) {
        log.error("Error", e);
        return new ResponseEntity<String>(HttpStatus.BAD_REQUEST); // This will enable JS to catch the Exception from Ajax
    }
}

JS
 $.ajax({
        type : "post",
        dataType : 'text', // Returns a ResponseEntity, not JSON (Void method)
        contentType : 'text/plain',
        url : 'addOrUpdate',
        data : somedata
 })
 .then(function() {
      //...
 })
 .fail(function(jqXHR, textStatus, errorThrown) {
      //... - will come here for a ResponseEntity of 'Bad Request'
 });


text:
Q: How to remove green hyperlink box in preview? Is it possible to disable the obnoxious green hyperlink bounding boxes in Preview (PDF)?
I do not have access to the latex. The link to the paper is here: https://arxiv.org/pdf/1806.01261.pdf.
When viewed on google there are no boxes, but when I download it for editing the pdf becomes a green swamp. I could not find any setting in Preview to disable this (on High Sierra).

A: Found a simple solution. If you print the pdf and download the print preview you will get a flattened version of your pdf.

A: That's not a Preview thing, the boxes are written into the PDF. I see the exact same display (green or red outlines for all links) using the built-in HTML PDF viewer in Firefox, or when opening it in Adobe Acrobat Pro. The author chose this link color, apparently.
Updating answer to include a screenshot taken in Adobe Acrobat. The link in the paper is explicitly set to render with a green, visible rectangle around the text. rendering engine. The PDF renders exactly the same (with green, visible rectangle around the text) on a Windows machine running Adobe Acrobat. If it renders with green visible rectangle around the hyperlink in multiple independent PDF engines across 2 platforms, AND a PDF editing tool shows that the links are explicitly set to render with this green rectangle, it is not logical to assume that this is a macOS or Preview bug.


text:
Q: suitescript 2.0:How to set excel style when export po to a csv file There is a funtion that I need to export a Purchase Order to csv file.I have got the data and put it into a cvs file.Now I want adjust excel style,like merged cells,center my text,through script or set template.But I do not know how to do it. Is there any demo or suggestion?
Thanks

A: If it is a csv file, you can't put special formatting on it when creating it. Its just plain text file with each column separated by comma.


text:
Q: RN 0.62 - 18 duplicate symbols for architecture armv7 I have recently upgraded the react-native app from 0.60.4 to 0.62.0 and I have solved tons of problems already, though I don't know how far I am from success but I feel close, here is how my pod file looks -
platform :ios, '10.0'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'
use_native_modules!

target 'MyProject' do
    pod 'FBLazyVector', :path => "../node_modules/react-native/Libraries/FBLazyVector"
    pod 'FBReactNativeSpec', :path => "../node_modules/react-native/Libraries/FBReactNativeSpec"
    pod 'RCTRequired', :path => "../node_modules/react-native/Libraries/RCTRequired"
    pod 'RCTTypeSafety', :path => "../node_modules/react-native/Libraries/TypeSafety"
    pod 'React', :path => '../node_modules/react-native/'
    pod 'React-Core', :path => '../node_modules/react-native/'
    pod 'React-CoreModules', :path => '../node_modules/react-native/React/CoreModules'
    pod 'React-Core/DevSupport', :path => '../node_modules/react-native/'
    pod 'React-RCTActionSheet', :path => '../node_modules/react-native/Libraries/ActionSheetIOS'
    pod 'React-RCTAnimation', :path => '../node_modules/react-native/Libraries/NativeAnimation'
    pod 'React-RCTBlob', :path => '../node_modules/react-native/Libraries/Blob'
    pod 'React-RCTImage', :path => '../node_modules/react-native/Libraries/Image'
    pod 'React-RCTLinking', :path => '../node_modules/react-native/Libraries/LinkingIOS'
    pod 'React-RCTNetwork', :path => '../node_modules/react-native/Libraries/Network'
    pod 'React-RCTSettings', :path => '../node_modules/react-native/Libraries/Settings'
    pod 'React-RCTText', :path => '../node_modules/react-native/Libraries/Text'
    pod 'React-RCTVibration', :path => '../node_modules/react-native/Libraries/Vibration'
    pod 'React-Core/RCTWebSocket', :path => '../node_modules/react-native/'

    pod 'React-cxxreact', :path => '../node_modules/react-native/ReactCommon/cxxreact'
    pod 'React-jsi', :path => '../node_modules/react-native/ReactCommon/jsi'
    pod 'React-jsiexecutor', :path => '../node_modules/react-native/ReactCommon/jsiexecutor'
    pod 'React-jsinspector', :path => '../node_modules/react-native/ReactCommon/jsinspector'
    pod 'ReactCommon/callinvoker', :path => "../node_modules/react-native/ReactCommon"
    pod 'ReactCommon/turbomodule/core', :path => "../node_modules/react-native/ReactCommon"
    pod 'Yoga', :path => '../node_modules/react-native/ReactCommon/yoga', :modular_headers => true
    pod 'RNCharts', :path => '../node_modules/react-native-charts-wrapper'
    pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec'

end

post_install do |installer|
    installer.pods_project.targets.each do |target|
        target.build_configurations.each do |config|
            config.build_settings['SWIFT_VERSION'] = '4.2'
        end
    end
end

Now I also have a bridging header which looks something like this -
//
//  Use this file to import your target's public headers that you would like to expose to Swift.
//

#import "React/RCTBridge.h"
#import "React/RCTViewManager.h"
#import "React/RCTUIManager.h"
#import "React/UIView+React.h"
#import "React/RCTBridgeModule.h"
#import "React/RCTEventDispatcher.h"
#import "React/RCTEventEmitter.h"
#import "React/RCTFont.h"

I am facing below errors -
ld: 18 duplicate symbols for architecture armv7
clang: error: linker command failed with exit code 1 (use -v to see invocation)

And apparently this indicate below 18 duplicated files -
RNBarChartManager.o
RNBarChartManager.o
RNBubbleChartManager.o
RNBubbleChartManager.o
RNCandleStickChartManager.o
RNCandleStickChartManager.o
RNCombinedChartManager.o
RNCombinedChartManager.o
RNHorizontalBarChartManager.o
RNHorizontalBarChartManager.o
RNLineChartManager.o
RNLineChartManager.o
RNPieChartManager.o
RNPieChartManager.o
RNRadarChartManager.o
RNRadarChartManager.o
RNScatterChartManager.o
RNScatterChartManager.o

Most of it belongs to react-native-charts-wrapper pakage. I do not know from where and how should i remove these duplicates.

A: The most likely cause is that you have enabled linking with Cocoapods and auto-linking, but you have not removed the manually linked framework from your Xcode project.
If you open the workspace in Xcode, and then look in the "Linked binaries and frameworks" section of the project setting. You likely have a framework linked called something like react-native-chart-wrapper.a. If you remove that, then everything should work.
You can also look for the Libraries group in the file list on the left and remove that. Now you're using Cocoapods, you won't need it anymore. When it asks, only press "Remove references" and not "Move to trash". Removing that should also remove the corresponding listing in "Linked binaries and frameworks".


text:
Q: End task when access is denied (even when using cmd taskkill / powershell kill) I have found a process running on my computer "rsEngineSvc.exe" and i want to uninstall this application from my laptop, meaning i must end the process to do so.
I have tried using taskkill in CMD and kill in powershell but it still pops up with the error message "The operation could not be completed" "Access is denied". (I'm on windows 11)

A: Most anti-virus programs have anti-kill protections on their processes. This protects them from being killed by malware.
The correct way to end the processes is to remove the software using the correct uninstallation method.
If this method is not working, most AV makers have uninstall utilities or guides for manual removal, but as you haven't told us you've tried uninstalling yet, you should start with that.


text:
Q: adding new key value in javascript array not affecting I have array like this,
var serialize={};

Now, i have form and i am serializing that form and adding that to serialize in array like this,
var c=12;
ser[c]=$(elem).find('input[name!=material_id],select').serializeArray();

Which generates array like this,
ser[127][0][name]   quantity_1_127
ser[127][0][value]  100
ser[127][1][name]   single_1_127
ser[127][1][value]  11
ser[127][2][name]   double_1_127
ser[127][2][value]  17.5

Now i just want to insert new key and value and i am doing it like this
ser[c]['test']='test';

But which is not affecting. What is the reason of this? Am i doing anything wrong here? Any alternate solution?

A: That's because ser[c] is an array and you are trying to use it as an object.
Add that test/test thing with:
ser[c].push({'test': 'test'});

Or, as your other values in the object are set:
ser[c].push({ 'name': 'test', 'value': 'test'});

This is not PHP where your indices in an associative array can be either strings or integers. This is javascript, where, if your indices in an object are integer, than that object is an array and if your indices are strings, your object is an ... well, object.
So, if you want to have something like ser[c]['mykey'] = value, you'll have to do something like:
ser[c] = { 'mykey': 'value'};

But this means that the ser[127][0] type of elements will be gone.


text:
Q: Symmetrization and antisymmetrization of tensor products How do I achieve something like

or

in LaTeX? The curved lines indicate symmetrization with respect to the indices they join, and the straight lines indicate antisymmetrization.

A: Here is a simpleminded proposal.
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{tikzmark}
\begin{document}
$u^{\tikzmarknode{i1}{i}\tikzmarknode{j1}{j}}
\tikzmarknode{v1}{v}^{\tikzmarknode{k1}{k}\tikzmarknode{l1}{\ell}}$
\begin{tikzpicture}[overlay,remember picture]
\draw[blue,thick] (i1.north east) to[out=30,in=150] (l1.north west);
\draw[blue,thick] (j1) -- ++(0,-1.5ex)  -| (k1);
\end{tikzpicture}
\end{document}

As for your comments:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{tikzmark}
\begin{document}
$u^{\tikzmarknode{i1}{i}\tikzmarknode{j1}{j}}
\tikzmarknode{v1}{v}^{\tikzmarknode{k1}{k}\tikzmarknode{l1}{\ell}}$
\begin{tikzpicture}[overlay,remember picture]
\draw[blue,thick] (i1.north east) to[out=30,in=150] (l1.north west);
\draw[blue,thick] (j1) -- ([yshift=-2pt]v1.south -| j1)  -| (k1);
\end{tikzpicture}
\quad
$u^{\tikzmarknode{i2}{i}\tikzmarknode{j2}{j}}
\tikzmarknode{v2}{v}^{\tikzmarknode{k2}{k}\tikzmarknode{l2}{\ell}}$
\begin{tikzpicture}[overlay,remember picture]
\draw[blue,thick] (j2.north east) to[out=30,in=150] (k2.north west);
\draw[blue,thick] (i2) -- ([yshift=-2pt]v2.south -| i2)  -| (l2);
\end{tikzpicture}
\quad
$u^{\tikzmarknode{i3}{i}\tikzmarknode{j3}{j}}
\tikzmarknode{v3}{v}^{\tikzmarknode{k3}{k}\tikzmarknode{l3}{\ell}}$
\begin{tikzpicture}[overlay,remember picture]
\draw[blue,thick,rounded corners=2pt] (j3) --
([yshift=-2pt]v3.south -| j3) -| (k3);
\draw[blue,thick] (i3.north) -- ++(0,3pt)  -| (l3);
\end{tikzpicture}
\end{document}

A: Also with pstricks (compile with xelatex):
\documentclass{article}
\usepackage{pst-node}

\begin{document}

$u^{\rnode{i}{i}\rnode{j}{j}} v^{\rnode{k}{k}\rnode{l}{\ell}}$
\ncarc[linecolor=blue,nodesep=1pt,arcangle=60]{i}{l}
\ncbar[linecolor=blue,nodesep=1pt,arm=3pt,angle=-90]{j}{k}

\end{document}


text:
Q: How to extract coordinates falling in a bbox from a geopandas data frame? I have a geopandas dataframe with coordinates and long with data frame I have a bbox. Now I want to apply the bbox on the data frame and extract the coordinates that's falling in that bbox. I tried using gpd.clip to extract but it is returning an empty data frame. What is the best way to extract the coordinates that are falling inside a bbox?
from shapely.geometry import box
import geopandas as gpd
from shapely.geometry import Point

print(df)

         lat           lon         geometry
    0   30.302228   -87.475474  POINT (-87.4754735 30.3022278)
    1   30.302249   -87.475305  POINT (-87.4753053 30.3022495)
    2   30.302268   -87.475203  POINT (-87.4752034 30.3022676)
    3   30.302284   -87.475118  POINT (-87.4751181 30.3022838)
    4   30.299260   -87.473474  POINT (-87.473474 30.2992603)
    5   30.299501   -87.473526  POINT (-87.473526 30.299501)
    6   30.299285   -87.481937  POINT (-87.4819365 30.299285)
    7   31.176753   -86.579765  POINT (-86.5797648 31.1767528)
    8   31.176670   -86.579352  POINT (-86.5793519 31.1766701)
    9   31.176644   -86.579243  POINT (-86.5792434 31.1766441)
    10  31.176596   -86.579159  POINT (-86.5791589 31.1765959)
    11  31.176503   -86.579115  POINT (-86.5791153 31.1765032)
    12  31.173518   -86.578724  POINT (-86.578724 31.173518)
    13  31.170868   -86.578374  POINT (-86.578374 31.170868)
    14  31.170122   -86.578270  POINT (-86.57827 31.170122)
    15  31.161356   -86.577077  POINT (-86.577077 31.161356)
    16  31.160598   -86.576931  POINT (-86.576931 31.160598)
    17  31.160147   -86.576831  POINT (-86.576831 31.160147)
    18  31.109081   -85.516056  POINT (-85.516056 31.109081)
    19  31.109327   -85.515871  POINT (-85.515871 31.109327)
    20  31.161638   -85.736218  POINT (-85.736218 31.161638)
    21  31.169062   -85.741498  POINT (-85.7414983 31.1690619)
    22  31.109349   -85.056092  POINT (-85.0560924 31.1093492)
    23  27.713963   -82.679369  POINT (-82.6793689 27.7139633)
    24  27.714265   -82.679379  POINT (-82.6793793 27.7142646)
    25  30.299501   -81.619310  POINT (-81.61931 30.299501)

bbox = box(*[30.902576115004003,-85.72642861167968,31.072530650777363,-85.57774194396336])
geometry = [Point(xy) for xy in zip(nodes.lon, nodes.lat)]
gdf = gpd.GeoDataFrame(nodes, crs="EPSG:4326", geometry=geometry)
df_clipped = gpd.clip(gdf, mask=bbox)
print(df_clipped)
lon lat geometry

A: I would recommend to try with .cx() method as described here https://gis.stackexchange.com/questions/266730/filter-by-bounding-box-in-geopandas
Alternatively, there is always a crazy option to make a spatial join of you bbox and the points.

A: gpd.clip will work fine. The issue is that like all shapely objects, the order of arguments for shapely.geometry.box is  x then y, in this case, xmin, ymin, xmax, ymax. You've used latitude, longitude order, but these should be reversed. So your bounding box should be:
bbox = box(
    -85.72642861167968,
    30.902576115004003,
    -85.57774194396336,
    31.072530650777363,
)


text:
Q: tomcat or apache automatically encodes redirect url I have a simple redirect in my Spring controller as follow:
if (url != null) {
    String username = request.getParameter("j_username");
    if(username != null) {
         username = URLEncoder.encode(username, "UTF-8");
    }
    url = url + (url.contains("?")? "&":"?") + "j_username=" + username;
    getRedirectStrategy().sendRedirect(request, response, url);
}

The username should be prepopulated in the next form. This works fine in my local jetty and dev(Tomcat) environment (username shows up as "abc@mysite.com" correctly).  But when it gets to QA which is on apache/tomcat, the username gets double encoded, it shows "j_username=abc%2540mysite.com" on the browser address bar and it shows as "abc%40mysite.com" on the form. Never seen this problem before.  Any pointers? thanks.

A: Try using org.springframework.web.util.UriUtils.encodeQueryParam(String, String) for encoding query parameter, URLEncoder is just too generic and does not know the context you're in.


text:
Q: Main menu lags and renders twice in fragment How to fix stuttering while clicking on main menu in fragment. It also renders main menu twice. I'm using custom toolbar and calling this on fragment.
Attaching code and video for reference.
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setHasOptionsMenu(true)
    }

   override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) :Boolean {
      inflater.inflate(R.menu.main_menu,menu)
      return true
}

override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
             R.id.about -> {
                 Log.d("MainFragment","About")
                 true
             }

            R.id.starred -> {
                Log.d("MainFragment","Starred")
                true
            }

            else -> super.onOptionsItemSelected(item)
        }
    }

A: I have checked your onCreateOptionsMenu(menu: Menu?): Boolean signature and it doesn't seem right.
First of all it shouldn't return a Boolean which makes me think you are writing this code inside an AppCompatActivity() instead of a Fragment() Class.
You need to move your code from the Activity Class to the Fragment Class instead and use this method to inflate your menu.
 override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
       inflater.inflate(R.menu.main_menu,menu)
        super.onCreateOptionsMenu(menu, inflater)
    }

Instead of returning a Boolean, do call the super class' onCreateOptionsMenu i.e.  super.onCreateOptionsMenu(menu, inflater).
Be sure to call setHasOptionsMenu(true) to show the menu preferrably inside the Fragment's onCreateView() method.

A: I think that there's not enough information provided to come up with a good answer. Based on the video it looks like there might be some logic reloading your fragment/activity a bunch of times which could cause the lag.
I'd recommend setting a breakpoint in the code where the menu is inflated and seeing if it is hit a bunch of times. Could also try setting one in the view somewhere and see if it's getting reloaded a ton.


text:
Q: Keystore loading I would like to know what's the equivalent in java of the following :
-Djavax.net.ssl.trustStore=keystore.jks -Djavax.net.ssl.keyStore=keystore.jks
-Djavax.net.debug=ssl -Djavax.net.ssl.keyStorePassword=test JavaFile

I would like to load the keystore otherwise than sending it as arguments from the command line. I've been working with :
private TcpLink createSSL() {
        KeyStore keyStore = null;
        TrustManagerFactory tmf = null;
        SSLContext ctx = null;
        SSLSocket socket = null;
        TcpLink smscLink = null;

        try {
            keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            LOGGER.info("Got keystore");
            keyStore.load(new FileInputStream("/root/keystore.jks"), "test".toCharArray());
            LOGGER.info("Loaded keystore");
            tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmf.init(keyStore);
            LOGGER.info("Inited keystore");
            ctx = SSLContext.getInstance("TLSv1");
            ctx.init(null, tmf.getTrustManagers(), null);
            SSLSocketFactory factory = ctx.getSocketFactory();
            socket = (SSLSocket)factory.createSocket("100.100.201.189", 8807);
            LOGGER.info("Got socket");
            smscLink = new TcpLink(socket);

            return smscLink;

        } catch (KeyStoreException e) {
            LOGGER.error("Key store exception : " + e);
        } catch (NoSuchAlgorithmException e) {
            LOGGER.error("NoSuchAlgorithmException : " + e);
        } catch (CertificateException e) {
            LOGGER.error("CertificateException : " + e);
        } catch (FileNotFoundException e) {
            LOGGER.error("FileNotFoundException : " + e);
        } catch (IOException e) {
            LOGGER.error("FileNotFoundException : " + e);
        } catch (KeyManagementException e) {
            LOGGER.error("KeyManagementException : " + e);
        } catch (Exception e) {
            LOGGER.error("Exception : " + e);
        }
        return null;
    }

but I get :
javax.net.ssl.SSLException: Connection has been shutdown: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
        at com.sun.net.ssl.internal.ssl.SSLSocketImpl.checkEOF(SSLSocketImpl.java:1293)
        at com.sun.net.ssl.internal.ssl.AppInputStream.read(AppInputStream.java:65)
        at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)

Any ideas are welcome !
Thx

A: You can set the System properties this way:
System.setProperty("javax.net.ssl.keyStore", '/path/to/keystore.jks');
System.setProperty("javax.net.ssl.keyStorePassword", 'your-password-here');

They will be used system-wide (in this instance of JVM), so probably you want to do it at initialisation time.

A: It works using this piece of code :
KeyManagerFactory kmf =
    KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(this.getCertificateContent(), "test".toCharArray());
kmf.init(keyStore, "test".toCharArray());

TrustManagerFactory tmf =
    TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keyStore);
SSLContext ctx = SSLContext.getInstance("TLSv1");
ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
SSLSocketFactory factory = ctx.getSocketFactory();
socket = (SSLSocket)factory.createSocket("100.125.100.1", 8775);

A: If you want, here's an API to create SSLSocket and SSLServerSocket easyly:
https://github.com/gpotter2/SSLKeystoreFactories
It does not require any other jars.... just get the files and use them like:
SSLSocket s = SSLSocketKeystoreFactory.getSocketWithCert(ip, port, Main.class.getResourceAsStream("/mykey.jks"), "password")

Or:
SSLServerSocket s = SSLServerSocketKeystoreFactory.getSocketWithCert(port, Main.class.getResourceAsStream("/mykey.jks"), "password")

That's much easier to use :)


text:
Q: How to do something after a time in C#? I wanted to make a simple AI in unity that follows you and shoots BTW a certain time but I don't know how to write a code that shoots after a certain time.
Simply, The question is : How to make a Timer?

A: Simply, there is no AI.
You can use a countdown timer (using frame count or delta time):
int timer = 10; // 10 seconds
bool stopped = false;
void Update() {
    if (timer <= 0 && !stopped) {
        // put your code here
        stopped = true;
    } else
        timer -= Time.deltaTime;
}

when timer stops; you can find the target direction with this code:
var heading = target.position - player.position;
var distance = heading.magnitude;
var direction = heading / distance; // This is now the normalized direction.

after, you can shoot in that direction.

A: use Time.deltaTime to create a timer. Time.deltaTime gives you the time since the last frame, and by subtracting from a constant will allow you to create a timer.
var timeLeft = 30;

 function Update()
 {
     timeLeft -= Time.deltaTime;
     if ( timeLeft < 0 )
     {
         //function here
     }
 }


text:
Q: How to change projection for layer? i use two seperate datasource for my layers:

*

*sql database for main map data, this is using EPSG:900913

*osm file for some extra features, this data use EPSG:4326 projection

tiles for both layers are created on server side.
what i need to do to generate tiles for EPSG:900913 projection from data in EPSG:4326 projection?
is it somewhere in tilecache configuration? in definition map or layer in osm file, or somewhere else?
tilecache.cfg
[test]
type=Mapnik
mapfile=/var/www/tc/osm/test.xml
tms_type=google
layers=global

test.xml
<Map background-color="#00000000" srs="+proj=latlong +ellps=WGS84 +datum=WGS84 +no_defs" >
  <Style name="style">
    <Rule>
      <PolygonSymbolizer fill="#ff0000" />
      <LineSymbolizer stroke="#00ff00" stroke-width="100" />
    </Rule>
  </Style>
  <Layer name="global" srs="+proj=latlong +ellps=WGS84 +datum=WGS84 +no_defs" status="on">
  <StyleName>style</StyleName>
  <Datasource>
      <Parameter name="type">osm</Parameter>
      <Parameter name="file">/var/www/tc/osm/test.osm</Parameter>
    </Datasource>
  </Layer>
</Map>

test.osm
<osm version='0.6' upload='true' generator='JOSM'>
  <node id='-186' action='modify' visible='true' lat='50.0' lon='50.0' />
  <node id='-184' action='modify' visible='true' lat='50.0' lon='-50.0' />
  <node id='-182' action='modify' visible='true' lat='-50.0' lon='-50.0' />
  <node id='-180' action='modify' visible='true' lat='-50.0' lon='50.0' />
  <way id='-91' action='modify' visible='true'>
    <nd ref='-186' />
    <nd ref='-184' />
    <nd ref='-182' />
    <nd ref='-180' />
    <nd ref='-186' />
  </way>
</osm>

map.html
...
var   map = new OpenLayers.Map ("map", {
                controls:[
                    new OpenLayers.Control.MousePosition(),
              numZoomLevels:zoomLev,
                maxResolution: 156543.0339,
                units: 'm',
                projection: new OpenLayers.Projection("EPSG:900913"),
                maxExtent: new OpenLayers.Bounds(-20037508.34, -20037508.34, 20037508.34, 20037508.34),
                displayProjection: new OpenLayers.Projection("EPSG:4326")
            } );

var test = new OpenLayers.Layer.WMS( "test", "http://localhost/tc/tilecache.cgi?",
    {layers: 'level_1', format: 'image/png'}, { isBaseLayer: false} );
...

A: you can do it on your tilecache.cfg configuration file to changing tms_type parameter to #tms_type=google... you can get some information here...
tms_type
    Setting this to "google" will cause tiles to switch vertical order (that is,
    following the Google style x/y pattern).

i hope it helps you...


text:
Q: Set value for Django DurationField type in query I want to pass value to DurationField of Django and store it into database.
After check the documentation, I thought we should use timedelta datatype to set Duratioin Field value. Like following code
record = Record(ID = 1,Duration = DurationField(timedelta(minutes=20)))
I also tried to using string type and integer type to set Duration's value, but they can't work. So I wander how should we set the value for DurationField type? I'm using the SQLite database.
My model:
TimeRecord(models.Model):
    duration = models.DurationField()

Instantiate:
record = TimeRecord(duration = timedelta(hours=5))
record.save()

A: Here is an example:
from datetime import timedelta
from django.db import models

class TimeRecord(models.Model):
    duration = models.DurationField(default=timedelta(minutes=40))

And you can create a record like this :
from datetime import timedelta

# create a new record
record1 = TimeRecord.objects.create()
record1.duration
# output : datetime.timedelta(0, 2400)
# you can create an another
record2 = TimeRecord.objects.create(duration=timedelta(minutes=20))
record2.duration
# output : datetime.timedelta(0, 1200)


text:
Q: Optimize hive query requesting data from two parition currently, I am using hive with s3 storage.
I have total 1000000 partitions right now. I am facing a problem where:
If I do:
Query execution time is less than 1 second.
select sum(metric) from foo where pt_partition_number = 'bar1'

select sum(metric) from foo where pt_partition_number = 'bar2'

But if I do
select sum(metric) from foo where pt_partition_number IN ('bar1','bar2')

The query is taking near about 30 seconds. I am thinking hive is doing directory scan in case of second query.
Is there a way to optimize query:
My request pattern always access two partition data.


text:
Q: MVC4 AntiForgery token cookie name is appended with random string I am encountering an issue with MVC4's
@Html.AntiForgeryToken()

html helper. On my development machine, when I run the project, upon inspecting the headers (using Fiddler) , the name of the token returned is
__RequestVerificationToken

But when deployed to an IIS version 7.5 (Windows 2008 R2), then token name looks like:
__RequestVerificationToken_L2V6b3JkZXI1

Where is this getting changed? Is it because my application is not deployed to the "root folder" of the IIS? E.g. my application is deployed to
"http://myserver/myapp" instead of "http://myserver"

A: I found the answer after looking at the source code:
http://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.WebPages/Helpers/AntiForgeryConfig.cs

Yes, because my application was deployed to a path, the following code below appends the encoded equivalent of the path... Hope this finding will save you trouble.
        // If the app path is provided, we're generating a cookie name rather than a field name, and the cookie names should
    // be unique so that a development server cookie and an IIS cookie - both running on localhost - don't stomp on
    // each other.
    internal static string GetAntiForgeryCookieName(string appPath)
    {
        if (String.IsNullOrEmpty(appPath) || appPath == "/")
        {
            return AntiForgeryTokenFieldName;
        }
        else
        {
            return AntiForgeryTokenFieldName + "_" + HttpServerUtility.UrlTokenEncode(Encoding.UTF8.GetBytes(appPath));
        }
    }

A: Resolution to this problem is very easy by the use of AntiForgeryConfig class.See the reference below.
https://learn.microsoft.com/en-us/dotnet/api/system.web.helpers.antiforgeryconfig?view=aspnet-webpages-3.2
Namespace:System.Web.Helpers

You need to add below code under Application_Start() event of Global.asax file.
if (AntiForgeryConfig.CookieName.Contains("__RequestVerificationToken"))
            {
                AntiForgeryConfig.CookieName = "__RequestVerificationToken";
            }


text:
Q: Sample code or project for Facial Recognition using C#.net without using third party libraries? I want sample code for Facial Recognition using C#.net without using third party libraries.
I want to achieve this using microsoft libraries.
I gone through this link "http://www.codeproject.com/Articles/239849/Multiple-face-detection-and-recognition-in-real-ti" but in that link they have used "Emgu.CV.dll" and some other external OS libraries(DLLs).
I want to know whether these dlls are open source libraries??
How can i achieve this task using microsoft or open source dlls??
Any ideas??
Pls suggest me..

A: OpenCV Open Source Computer Vision Library is probably what your're looking for.


text:
Q: Login Validator Checker PHP MYSQL Below is my "Login Checker"
It works fine if I use the old traditional mysql connect.. but with PDO it doesnt seem to work.. mind if anyone give me a few tips or modifications to this code so that it will work?
It gives me this error:
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\clubresults\checklogin.php on line 23

where Line 23 is $count=mysql_num_rows($result);
Thanks!!
<?php
ob_start();
$tbl_name="admin_passwords"; // Table name

        $pdo = new PDO('mysql:host=localhost;dbname=clubresults', 'root', '12345678');
    #Set Error Mode to ERRMODE_EXCEPTION.
    $pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];

// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);

$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row

if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
$_SESSION["myusername"] = "$myusername";
$_SESSION["mypassword"] = "$mypassword";
header("location:login_success.php");
}
else {

echo "ACCESS DENIED.
 Incorrect username and/or Password

Please check your username and password.
 wait five seconds for redirection. ";
}
ob_flush();
?>

A: It doesn't look like you are fully leveraging the PDOs and using the parameterized statments.
If it were me I would have written your code as follows:
$tbl_name="admin_passwords"; // Table name

$pdo = new PDO('mysql:host=localhost;dbname=clubresults', 'root', '12345678');
#Set Error Mode to ERRMODE_EXCEPTION.
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$stmt = $pdo->prepare("SELECT * FROM $tbl_name WHERE username = :username AND password = :password");
$stmt->execute(array('username' => $_POST['myusername'], 'password' => $_POST['mypassword']));
if ($stmt->fetch() === false) {
    //access deined
    //....
}
else {
   //access granted
   //...
}

Also, for security purposes you should be hashing your passwords with sha1 at the least (I do sha512) in your database so that even if you data gets stolen the passwords can't be reverse engineered without quite a bit of effort.
EDIT: Looking again, it might also be good to use a user other than root to access the database, but that is more personal preference.

A: Try printing the result from this line:
$result=mysql_query($sql);

It looks like mysql_query might be failing because it is not being passed a link_identifier.

A: You need to make pdo-query not, mysql_query.
see here: http://php.net/manual/en/pdo.query.php


text:
Q: Use of the Student T distribution for the t-statistic The variable $T$ is given by the classic form of the one-sample t-test the population mean under a hypothesis such as $H_0: \mu = \mu_0$
$$T = \frac{\bar{X_n}-\mu_0}{S/\sqrt{n}}$$
where $\bar{X_n} = \sum_{i=1}^n X_i$ and $S = \sqrt{\frac{1}{n-1}\sum_{i=1}^n (X_i - \mu)}$ and where $X_i$ follows some distribution with population mean $\mu$ and variance $\sigma^2<\infty$. I am aware of the following two cases:
(1) If $X_i \sim^{i.i.d} N(\mu, \sigma^2)$ for $i=1,..,.n$ then $T$ is (exactly) Student T distributed with $n-1$ degrees of freedom
(2) If $X_i$ is drawn $i.i.d$ for all $i=1,...,n$ from a distribution with a finite second moment, then $T$ converges to a standard normal distribution as $n\rightarrow \infty$ (see a great derivation here).
Now, in practical, large-sample applications of the one-sample t-test, I understand that $T$ is only normally distributed in the limit. Thus, it is usually stated that one should use a Student T distribution for $T$ when determining critical-values, etc (for instance, see here, here, and here). I understand that a Student T distribution also converges to a Normal distribution as $n\rightarrow \infty$, but this is not sufficient justification to use the Student T distribution for the random variable $T$ for finite (even if large) $n$.
All answers to this question that I have seen argue that using the Student T distribution is more conservative: either this is just stated with intuitive appeal to the fact that we have to estimate $\sigma$ using $S$ (which is not nearly enough in my mind to justify the use of the Student T distribution) or appeals to simulation (again, not enough since these simulations can only ever test a finite number of distributions for $X_i$). For instance, this is approximately the answer given for this extremely well written question on the exact same topic here.
To this end, I am looking for some sort of mathematical (not intuitive and not based on simulation) justification that $T$ not only can but should be approximated as a Student T distribution in the case where $X_i$ are not normally distributed, $\sigma$ is unknown, and $n$ is finite (but large). A reference to a textbook or journal article would also be sufficient.


text:
Q: Cannot find local variable in Android Java Hello I am using Java to code an android app and I am getting a bug where the program doesn't think that the variable 'sc' exists.
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, getTrustingManager(), new java.security.SecureRandom());

    SSLSocketFactory socketFactory;
    socketFactory = new SSLSocketFactory(sc);
    Scheme sch = new Scheme("https", socketFactory, 443);
    client.getConnectionManager().getSchemeRegistry().register(sch);

I have a hunch that my issue is with creating a new object changes the scope so that 'sc' can't be seen.

A: Changing
SSLContext sc = SSLContext.getInstance("SSL");

to
final SSLContext sc = SSLContext.getInstance("SSL");

fixed the error. Thanks again NilayDani.


text:
Q: SSH Tunnel proxy - view HTTPS Page Really hope someone will answer to my question..
Basically got a ssh tunnel between MACHINE1 and MACHINE2, tunnel working as proxy, everything works well.
test12 = https server - 10.0.0.1 - same network as MACHINE1
MACHINE1 = windows 7 x64 - 192.168.6.20 (the one running ssh server)
MACHINE2 = windows 7 x64 - 192.168.2.8 (different network from MACHINE1)
So when i use putty on MACHINE2 to connect via ssh to MACHINE1, I Can browse https and https sites and see MACHINE1 public ip!
But when i navigate to test12, it can't display page!
PUTTY CONSOLE MACHINE2 - VIEW

As you can see using iexplore and setting proxy, the page can not be displayed! Also tried to edit C:\Windows\System32\drivers\etc\hosts to resolve test12 to 127.0.0.1 but have aniway error!
DNS CHANGE MACHINE2 - VIEW

A: Found the problem!
The IP of test12 was actually different, it was 192.168.6.120.
The problem was that socks proxy doesn't automatically resolves internal network dns names! so the solution was simply add to C:\Windows\System32\drivers\etc\hosts this line: 192.168.6.120 test12


text:
Q: Show that there is no polynomials $P,Q$ such that $\pi(n)=\frac{P(n)}{Q(n)}$. Show that there is no polynomials $P,Q$ such that $\pi(n)=\frac{P(n)}{Q(n)}$ for an infinity many $n$.
Attempts
Let $(n_k)$ a sequence s.t. $\pi(n_k)=\frac{P(n_k)}{Q(n_k)}$ and suppose by contradiction that $\#\{n_k\}=\infty $. Since $$\lim_{k\to \infty }\pi(n_k)=\infty ,$$
we have that $$\lim_{k\to \infty }\frac{P(n_k)}{Q(n_k)}=\infty,$$
and thus $\deg P>\deg Q$. Let $m=\deg P$ and $\ell=\deg Q$. We suppose WLOG that $P$ and $Q$ are monic. Since $P$ and $Q$ are polynomials,
$$\frac{P(n_k)}{Q(n_k)}\sim n_k^{m-\ell}.$$
By Tchebychev, $$\pi(n_k)\ll \frac{n_k}{\log(n_k)},$$
and thus $$n_k^{m-\ell}\ll \frac{n_k}{\log(n_k)}$$
and thus $m-\ell< 1$. That implies that $\ell\geq m$ what is a contradiction.
Is this proof fine ? Is there easier ?


text:
Q: validate controller only with images in rails 4 hi i have given my attachment model:
class Attachment < ActiveRecord::Base
  belongs_to :attachable, polymorphic: true
  has_attached_file :attach,
                    :storage => :s3,
                    :s3_credentials => "#{Rails.root}/config/s3.yml",
                    :url => ":s3_domain_url",
                    :path => "/contents/:id/:basename.:extension"
  validates_attachment_content_type :attach,
                                    :content_type => ['application/msword',
                                                       'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                                                       'application/pdf',
                                                       'image/jpeg', 'image/jpg', 'image/png']
end

i am using these content type some where in my application so that i can not change these content type. so i decide to set validation at controller site. i have given:
def create
 @designation = Designation.create(designation_params)
 if (@designation.attachment.attach_content_type.present? &&
 (@designation.attachment.attach_content_type.to_s =~ /image\/.*/)) || @designationerrorse.present?
 redirect_to designations_path, notice: I18n.t('designation_created')
 else
 render :action => :new
 end
end

code in designation model:
has_one :attachment, as: :attachable
  accepts_nested_attributes_for :attachment

but it does not functioning properly.if i submit form with file field blank then it give me this error:

undefined method `attach_content_type' for nil:NilClass

how to implement these validation so that designation accept only images and if it is blank? send me error message can't blank. please guide me. thanks in advance

A: validates_attachment :attach, :presence => true, :with => %r{\.(rar|tar|zip)$}i, :size => { :in => 0..10.kilobytes}, :if => Proc.new{|f| f.attachable_type == 'Designation' }
This validation will be called when attachment will be of Designation class

A: you can use its own validation method like this:
validates_attachment :attach, :presence => true, :with => %r{\.(rar|tar|zip)$}i, :size => { :in => 0..10.kilobytes}