text:
Q: python ghostscript: RuntimeError: Can not find Ghostscript library (libgs) When trying to run hello-world example
import sys
import ghostscript

args = [
    "ps2pdf", # actual value doesn't matter
    "-dNOPAUSE", "-dBATCH", "-dSAFER",
    "-sDEVICE=pdfwrite",
    "-sOutputFile=" + sys.argv[1],
    "-c", ".setpdfwrite",
    "-f",  sys.argv[2]
    ]

ghostscript.Ghostscript(*args)

getting error:
 File "/Users/ddd/sss/ddd/eee.py", line 2, in <module>
    import ghostscript
  File "build/bdist.macosx-10.6-universal/egg/ghostscript/__init__.py", line 33, in <module>

  File "build/bdist.macosx-10.6-universal/egg/ghostscript/_gsprint.py", line 290, in <module>
RuntimeError: Can not find Ghostscript library (libgs)

what is this libgs library and how can I get it?
btw I'm on mac

A: For newer user who are using M1 mac, ghostscript might show a missing libgs file error and the file would be unavailable at usr/local/lib
The issue can be resolved by following these steps, in the same order:

*

*brew install ghostscript

*conda install ghostscript, which installs the arm_64 based library from conda-forge

*If conda throws a channel error try using conda install -c conda-forge ghostscript

*pip install ghostscript
Note:

*

*The libgs.dylib file can be found in the home brew installation of ghostscript

*Changing the address in _gsprint.py will throw an error as the brew installed version will be arm_64 based and the pip installed version will be OS_X86 based

*Python doesn't recognise ghostscript module from conda install unless pip install is run, so that is an essential step

A: For me it was simply that I had installed the python parts:
pip install ghostscript

But not the C parts:
brew install ghostscript

Perhaps these DMGs work also - but I didn't go this route:
http://pages.uoregon.edu/koch/

A: You should have a look at Ghostscript's official download site as well as at their documentation.
If this doesn't get you started you could also ask the GS developers directly in their online chat channel named #ghostscript on IRC server irc.freenode.net. They are a very friendly and helpful bunch of people.

A: To solve it, you need to modify ghostscript modules path in site-packages.
in _gsprint.py modify into something like this:
libgs = ctypes.util.find_library('/opt/local/lib/libgs')
which locates your libgs file.

A: Ok, if you're on mac M1 and using python 3.9 that trick from the mentioned Github issue won't work probably. I did a few times what @Prajual suggested but didn't work either. This helps.

*

*First,

brew install ghostscript

*Check out in brew lib what your version is. there should be a directory named like 9.56.1_1
ls /opt/homebrew/Cellar/ghostscript/

*Then copy that dylib file to where pip can access at /usr/local/lib/ -- needs sudo privilege. x.xx.xx would be your version from last command!
sudo cp /opt/homebrew/Cellar/ghostscript/x.xx.xx/lib/libgs.dylib /usr/local/lib/

You should now be able to import ghostscript with no problem.

A: For Mac user find the version of the libgs.x.xx.dylib in your /usr/local/lib/ directory.
Then run this command,
ln -s /usr/local/lib/libgs.x.xx.dylib /usr/local/lib/libgs.so

echo 'export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib/' >> ~/.zshrc

Replace .zshrc with your shell script type.
[replace x.xx with the version in your directory]

A: For other users on Mac that have tried @PrajualPillai's answer and it still didn't work, I'm posting @ArpanKushwaha's comment as an answer, because it was the only thing that worked for me.
For some reason, ctypes.util.find_library("gs") could not find my ghostscript install, so I had to replace it in
/opt/anaconda3/lib/python3.8/site-packages/ghostscript/_gsprint.py

At the top of the file, add
import distutils.spawn

and then replace
libgs = ctypes.util.find_library('gs')

with
libgs = distutils.spawn.find_executable("gs")

near the bottom of _gsprint.py.
If you also use camelot for pdf parsing you also need to replace library = find_library("gs") with library = distutils.spawn.find_executable("gs") in your /opt/anaconda3/lib/python3.8/site-packages/camelot/backends/ghostscript_backend.py  file.


text:
Q: CSS Hover - Fade in on hover, Disappear instantly off hover So, I have a hover transition that I would like to ease in on hover, but be instantaneous off hover.
Here's a sample snippet:

.invisible{
  opacity: 0;
  transition: 1s;
}

div{
  cursor: pointer;
}

div:hover .invisible{
  opacity: 100%;
}

Hover Here

Now you see me

What can I change in the CSS to keep the text fading in over the space of 1 second, but instantly vanish when the mouse is moved away?

A: You can give transition to hover state only, by default it was given to all states.
Once you'll use it for :hover, transition will occur only for mouseover, not for mouseout.

.invisible {
  opacity: 0;
}

div {
  cursor: pointer;
}

div:hover .invisible {
  opacity: 100%;
  transition: 1s; /* moved this */
}

Hover Here

Now you see me

A: You just need to specify a different transition-duration for the two states, resp. specify the duration not equal zero just for the hover state.
(transition: 0s; for the normal state - because you want it to be 0, when you return into this state, from the hover state. Can be implicit, if no transition-duration is already set for that state.)

.invisible{
  opacity: 0;
  /* transition: 0s; */
}

div{
  cursor: pointer;
}

div:hover .invisible{
  opacity: 100%;
  transition: 1s;
}

Hover Here

Now you see me

redpajama_set_name: RedPajamaStackExchange


text:
Q: Different bracket types python So I've been following a guide I got off reddit about understanding python's bracket requirements:
Is it a list? Then use brackets.
Is it a dict? Then use braces.
Otherwise, you probably want parentheses.
However, I've come across something that the above can't explain:
df.groupby('Age')['Salary'].mean()
In this case, both Age & Salary are lists (they are both columns from a df), so why do we use parentheses for Age and brackets for Salary?
Additionally, why is there a dot before mean, but not in-between ('Age') and ['Salary']?
I realise the questions I'm asking may be fairly basic. I'm working my way through Python Essential Reference (4th ed) Developer's Library. If anyone has any sources dealing with my kind of questions it would be great to see them.
Thanks

A: If you'll forgive me for answering the important question rather than the one you asked...
That's a very compact chain. Break it into separate lines and then use the Debugging view of an IDE to step through it the understand the datatypes involved.
query_method = df.groupby
query_string = 'Age'
query_return = query_method(query_string)
data = query_return['Salary']
data_mean = data.mean()

Step through in the PyCharm Debugger and you can see type for every variable.

A: There is a lot of context here that can be found in the pandas dataframe documentation.
To start off, df is an object of class pandas.DataFrame.
pandas.DataFrame has a function called groupby that takes some input. In your example, the input is 'Age'. When you pass arguments to a function it looks like this:
my_function(input)

when you have more than one input, the common way to pass them is as multiple variables, like this
my_function(input1, input2, etc, ...)

pandas.DataFrame.groupby(...) returns an object that is subscriptable or sliceable. Using slice notation is like accessing an element in an list or a dict, like this
my_list = [1,2,3]
print(my_list[0]) # --> 1

my_dict = {
    "a": "apple",
    "b": "banana",
    "c": "cucumber"
}

print(my_dict["b"]) # --> banana

coming back to your specific question:
df.groupby('Age')['Salary'].mean()
df                                 # df, the name of your DataFrame variable
  .groupby('Age')                  # call the function groupby to get the frame grouped by the column 'Age'
                 ['Salary']        # access the 'Salary' element from that groupby
                           .mean() # and apply the mean() function to the 'Salary' element

So it appears that you are getting a list of all the the mean salaries by age of the employee.
I hope this helps to explain

A:
both Age & Salary are lists (they are both columns from a df),

They're Ranges / Columns, not lists. The group by function of a Dataframe returns an indexed object. Calling methods requires parenthesis, like print(). You can use square brackets to access indexed data (ref. dict() objects).
The period and paranthesis afterwards is another function call

why is there a dot before mean, but not in-between ('Age') and ['Salary']

Short answer is that foo.['bar'] is not valid syntax
But df.groupBy("Age").some_func() certainly could be done, depending on the available functions on that object


text:
Q: Doctrine, ignore some fields to persist and null given a user:
id, name, password

so I want to modify him, and set a name to it. But then if I persists, his password will be rewritten (set to empty), even though I didnt set it. But here is the nullable=true annotation! Right now it seems to work - but this way its impossible to persist if I want to set it null itself. Then how?

A: in the password field in form add the argument mapped => false do the Doctrine will not be considered as an entity field in the moment of form validation.
->add('password', 'password', array(
   'mapped' => false
))


text:
Q: OAuth 1.0 "Could not authenticate you." Hı first of all this is a twitter auth. I can login, I can get the timeline etc etc. I can get those things because they dont want an extra paramaters. But now ı want to add "tweet_mode=extended" paramaters to that.
 public String extendedtweet(String token, String secret,String id) throws IOException{

    String url="https://api.twitter.com/1.1/statuses/lookup.json";
    headercreator hc=new headercreator(outhconsumerkey,consumersecret,token,secret);
    Map<String,String> requestparams = new HashMap<String, String>();
    Log.e("id",id);
    requestparams.put("id",id);
    String header=hc.generateHeader("GET",url,requestparams);
    Log.e("header",header);

    Response response =request(url,"","GET","Authorization",header);
    String jsonData=response.body().string();
    JsonObject js=new Gson().fromJson(jsonData, JsonObject.class);
    return js.get("full_text").getAsString();

}

When ı Delete the
        requestparams.put("id",id);

Line at there it says id paramaters is missing.That is Nice because that shows me the problem is at the Headercreator class which is here :
   package com.example.twittertestvol1;

import android.os.Build;
import android.util.Log;

import androidx.annotation.RequiresApi;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * Class to generate Oauth 1.0a header for Twitter
 *
 */
@RequiresApi(api = Build.VERSION_CODES.N)
public class headercreator {

    private String consumerKey;
    private String consumerSecret;
    private String signatureMethod;
    private String token;
    private String tokenSecret;
    private String version;

    public headercreator(String consumerKey, String consumerSecret, String token, String tokenSecret) {
        this.consumerKey = consumerKey;
        this.consumerSecret = consumerSecret;
        this.token = token;
        this.tokenSecret = tokenSecret;
        this.signatureMethod = "HMAC-SHA1";
        this.version = "1.0";
    }

    private static final String oauth_consumer_key = "oauth_consumer_key";
    private static final String oauth_token = "oauth_token";
    private static final String oauth_signature_method = "oauth_signature_method";
    private static final String oauth_timestamp = "oauth_timestamp";
    private static final String oauth_nonce = "oauth_nonce";
    private static final String oauth_version = "oauth_version";
    private static final String oauth_signature = "oauth_signature";
    private static final String HMAC_SHA1 = "HmacSHA1";

    /**
     * Generates oAuth 1.0a header which can be pass as Authorization header
     *
     * @param httpMethod
     * @param url
     * @param requestParams
     * @return
     */
    public String generateHeader(String httpMethod, String url, Map<String, String> requestParams) {
        StringBuilder base = new StringBuilder();
        String nonce = getNonce();
        String timestamp = getTimestamp();
        String baseSignatureString = generateSignatureBaseString(httpMethod, url, requestParams, nonce, timestamp);
        String signature = encryptUsingHmacSHA1(baseSignatureString);
        base.append("OAuth ");
        append(base, oauth_consumer_key, consumerKey);
        append(base, oauth_token, token);
        append(base, oauth_signature_method, signatureMethod);
        append(base, oauth_timestamp, timestamp);
        append(base, oauth_nonce, nonce);
        append(base, oauth_version, version);
        append(base, oauth_signature, signature);
        base.deleteCharAt(base.length() - 1);
        return base.toString();
    }

    /**
     * Generate base string to generate the oauth_signature
     *
     * @param httpMethod
     * @param url
     * @param requestParams
     * @return
     */
    private String generateSignatureBaseString(String httpMethod, String url, Map<String, String> requestParams, String nonce, String timestamp) {
        Map<String, String> params = new HashMap<>();
        if (requestParams!=null)
        {
            requestParams.entrySet().forEach(entry -> {
                put(params, entry.getKey(), entry.getValue());
            });

        }
        put(params, oauth_consumer_key, consumerKey);
        put(params, oauth_nonce, nonce);
        put(params, oauth_signature_method, signatureMethod);
        put(params, oauth_timestamp, timestamp);
        put(params, oauth_token, token);
        put(params, oauth_version, version);
        Map<String, String> sortedParams = params.entrySet().stream().sorted(Map.Entry.comparingByKey())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));
        StringBuilder base = new StringBuilder();
        sortedParams.entrySet().forEach(entry -> {
            base.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        });
        base.deleteCharAt(base.length() - 1);
        String baseString = httpMethod.toUpperCase() + "&" + encode(url) + "&" + encode(base.toString());
        return baseString;
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private String encryptUsingHmacSHA1(String input) {
        String secret = new StringBuilder().append(encode(consumerSecret)).append("&").append(encode(tokenSecret)).toString();
        byte[] keyBytes = secret.getBytes(StandardCharsets.UTF_8);
        SecretKey key = new SecretKeySpec(keyBytes, HMAC_SHA1);
        Mac mac;
        try {
            mac = Mac.getInstance(HMAC_SHA1);
            mac.init(key);
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            e.printStackTrace();
            return null;
        }
        byte[] signatureBytes = mac.doFinal(input.getBytes(StandardCharsets.UTF_8));
        return new String(Base64.getEncoder().encode(signatureBytes));
    }

    /**
     * Percentage encode String as per RFC 3986, Section 2.1
     *
     * @param value
     * @return
     */
    private String encode(String value) {
        String encoded = "";
        try {
            encoded = URLEncoder.encode(value, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String sb = "";
        char focus;
        for (int i = 0; i < encoded.length(); i++) {
            focus = encoded.charAt(i);
            if (focus == '*') {
                sb += "%2A";
            } else if (focus == '+') {
                sb += "%20";
            } else if (focus == '%' && i + 1 < encoded.length() && encoded.charAt(i + 1) == '7' && encoded.charAt(i + 2) == 'E') {
                sb += '~';
                i += 2;
            } else {
                sb += focus;
            }
        }
        return sb.toString();
    }

    private void put(Map<String, String> map, String key, String value) {
        map.put(encode(key), encode(value));
    }

    private void append(StringBuilder builder, String key, String value) {
        builder.append(encode(key)).append("=\"").append(encode(value)).append("\",");
    }

    private String getNonce() {
        int leftLimit = 48; // numeral '0'
        int rightLimit = 122; // letter 'z'
        int targetStringLength = 10;
        Random random = new Random();

        String generatedString = random.ints(leftLimit, rightLimit + 1).filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97)).limit(targetStringLength)
                .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString();
        return generatedString;

    }

    private String getTimestamp() {
        return Math.round((new Date()).getTime() / 1000.0) + "";
    }

}

Nowı wonder if someone shows me where is the problem why ı cant solve that. And that is the error code and error for that

{"errors":[{"code":32,"message":"Could not authenticate you."}]}

Here is thre request function
private Response request(String url, String bodys, String type, String Headername, String Header) throws IOException {

    OkHttpClient client = new OkHttpClient();
    MediaType mediaType = MediaType.parse("text/plain");
    RequestBody body = RequestBody.create(mediaType,bodys);
    Request request;
    if (!Headername.equals(""))
    {
        if (type.equals("GET"))
        {

            request = new Request.Builder()
                    .url(url)
                    .method(type,null)
                    .addHeader(Headername,Header)
                    .build();

        }
        else{
            request = new Request.Builder()
                    .url(url)
                    .method(type, body)
                    .addHeader(Headername,Header)
                    .build();
        }

    }
    else {
        request = new Request.Builder()
                .url(url)
                .method(type, body)
                .build();

    }

    return client.newCall(request).execute();
}

A: Issue is at Response response =request(url,"","GET","Authorization",header);.
You need to pass in the request params when calling the service but you are not passing the id or any other param when calling the request() method. For me following code works:
    public void getTweet() {
        Map<String, String> requestParams = new HashMap<>();
        String id = "1263213348000325633";
        // Pass all request params for header generation
        requestParams.put("id", id);
        requestParams.put("tweet_mode", "extended");
        String url = "https://api.twitter.com/1.1/statuses/lookup.json";
        String header = generator.generateHeader(HttpMethod.GET.name(), url, requestParams);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", header);
        HttpEntity<String> httpEntity = new HttpEntity<String>("body", headers);
        // Pass all request params in the request
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
                .queryParam("id", id)
                .queryParam("tweet_mode", "extended");
        ResponseEntity<String> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, httpEntity, String.class);
        String responseBody = response.getBody();
        assertNotNull(responseBody);
        System.out.println(responseBody);
    }

Working code available here as a junit.


text:
Q: Git subtree cannot detect new commits in sub folder I have a git repository like the following:
Top/
  .git
  sub1/
  sub2/
    Very big stuff

Sub1 is the only folder I want to push to Github. In the Top directory, I use the following command to push sub1:
git subtree push --prefix sub1/ origin master
But after I made new commits in sub1, the above command cannot find new commits and only tells me that every thing is up to date. In addition, the hash ID of the Top master is different from sub1 master. Also, the log history of Top is quite different from sub. Is this expected or the problem? How to fix it?
Thanks!

A: Finally I figured out why. I used symbol link to create this folder structure. The true above level of the Sub is not Top, but another folder. This folder contains a .git directory. So the masters of Top and sub are different.


text:
Q: Delete file listitem is linked to on the SD Card I've got a list showing a list of items in a directory I've specified. I've created an onLongClickListener that pops up a dialog box for confirmation. I need the actual file on the SD card to be deleted when the user presses the Ok button on the Dialog. I've viewed all the examples I could find on Stack Overflow and found none that worked for me.
public class ReadFilesFromPath extends Activity {
/** Called when the activity is first created. */
List<String> myList;
File file;
ListView listview;
ArrayAdapter<String> adapter;
String value;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recordinglist);
Intent intent = getIntent();
value = intent.getStringExtra("path"); //if it's a string you stored.
listview = (ListView) findViewById(R.id.recordlist);
myList = new ArrayList<String>();
onitemclick();
File directory = Environment.getExternalStorageDirectory();
file = new File( directory + "/" + "Recordify" );
File list[] = file.listFiles();

for( int i=0; i< list.length; i++)
{
        myList.add( list[i].getName() );
}
adapter = new ArrayAdapter<String>(this,
        android.R.layout.simple_list_item_1, android.R.id.text1, myList);
listview.setAdapter(adapter); //Set all the file in the list.
longclick();
}

public void longclick() {
    listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

        public boolean onItemLongClick(AdapterView<?> arg0, View v, //when long pressed
                int pos, long arg3) {
            AlertDialog.Builder adb=new AlertDialog.Builder(ReadFilesFromPath.this); //alert for each time an item is pressed
              adb.setTitle("Delete?");
              adb.setMessage("Are you sure you want to delete this recording?");
              final int positionToRemove = pos;
              adb.setNegativeButton("Cancel", null);
              adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {

                  public void onClick(DialogInterface dialog, int which) {
                      listview.animate().setDuration(500).alpha(0) //animates a smooth deletion animation
                        .withEndAction(new Runnable() {
                          @Override
                          public void run() {
                            file.delete();
                            myList.remove(positionToRemove); //removes the selected item from the list but not on SD card
//this is where I need my code to delete it on the SD card to go.
                            adapter.notifyDataSetChanged(); //tells the adapter to delete it
                            listview.setAlpha(1);
                          }
                        });
                  }});
              adb.show();
              return false;
              }
          });

        }

 }

A: have you tried:
new File(path).delete()

A: String file_name = file_list.get(position);
String MEDIA_PATH = new String(Environment.getExternalStorageDirectory() + "/AudioRecorder/" + file_name);
File file = new File(MEDIA_PATH);
file.delete();
file_list.remove(position);
notifyDataSetChanged();

Use this in on click event handler.


text:
Q: Unit testing Plugin in Magento 2 I got a problem in my Testunit in Magento I can't figure out the problem
This is the File
Mode.php
<?php
namespace Mxxxx\Category\Plugin\Model\Category\Attribute\Source;

use Mxxxx\Category\Model\Category\Category;

/**
 * Class Mode
 * @package Mxxxx\Category\Plugin\Model\Category\Attribute\Source
 */
class Mode
{
    /**
     * @param \Magento\Catalog\Model\Category\Attribute\Source\Mode $subject
     * @param $result
     * @return mixed
     */
    public function afterGetAllOptions(
        \Magento\Catalog\Model\Category\Attribute\Source\Mode $subject,
        $result
    ) {
        $result[] = ['value' => Category::DM_BUFFER_PAGE, 'label' => 'Buffer page'];
        return $result;
    }
}

This is the File of Unit Test
ModeTest.php
<?php
namespace Mxxxx\Category\Test\Unit\Plugin\Model\Category\Attribute\Source;

use Mxxxx\Category\Model\Category\Category;
use Mxxxx\Category\Plugin\Model\Category\Attribute\Source\Mode;
use Magento\Framework\TestFramework\Unit\Helper\ObjectManager;

class ModeTest extends \PHPUnit\Framework\TestCase
{
    private $model;

    public function testAfterGetAllOptions($subject, $validResult)
    {
        $validResult = ['value' => Category::DM_BUFFER_PAGE, 'label' => 'Buffer page'];
        $this->assertEquals(\Magento\Catalog\Model\Category\Attribute\Source\Mode );
    }

    protected function setUp()
    {
        $helper = new ObjectManager($this);
        $this->model = $helper->getObject(
            Mode::class
        );
    }
}

When I run the unit test using this command
./vendor/bin/phpunit -c dev/tests/unit/phpunit.xml.dist app/code/Mxxxx/Category/Test/Unit/Plugin/Model/Category/Attribute/Source/ModeTest

I got this error
E                                                                   1 / 1 (100%)

Time: 14.26 seconds, Memory: 10.00MB

There was 1 error:

1) Mxxxx\Category\Test\Unit\Plugin\Model\Category\Attribute\Source\ModeTest::testAfterGetAllOptions
ArgumentCountError: Too few arguments to function Mxxxx\Category\Test\Unit\Plugin\Model\Category\Attribute\Source\ModeTest::testAfterGetAllOptions(), 0 passed and exactly 2 expected

/shared/httpd/Mxxxx/magento-v2/app/code/Mxxxx/Category/Test/Unit/Plugin/Model/Category/Attribute/Source/ModeTest.php:12

ERRORS!
Tests: 1, Assertions: 0, Errors: 1.

Thanks in advance


text:
Q: flat pack java for multiline records or multi line fixed width files I am using net.sf.flatpack and new to fixed length file parsing. Does flatpack support mutlilined files or files with different fixed length records?
for example:
myfile
AAA000 SOMETHING 0001 - record1
AAAA SOMETHINGELSE 0001 AAAA - sub-record of record 1
-repeat-
if flatpack does support it how is the pzmap xml defined?
if not supported is there another library i can use?
Thanks all


text:
Q: create a repeating pop-up window (tkinter) def popup():
  global Qscreen
  QA = random.randint(0,1)
  Qscreen = Toplevel(screen)
  Qscreen.attributes("-fullscreen", True)
  Qscreen.attributes("-topmost", True)
  Qscreen.title("QUESTION")
  Label(Qscreen, text = questions[QA]).pack()
  Button(Qscreen, text = "o", command = answer).pack()
  screen.after(10000, destroy)

def answer():
  Qscreen.destroy()

def destroy():
  global Qscreen
  Qscreen.destroy()
  popup()

def Maze():
  tkinter_window = Tkinter_window()
  tkinter_window.run()

def play():
  popup()
  Maze()

I need the popup function to open a window every 10 seconds and close after the user has clicked a certain button. However when testing this I wasnt able to click the button on the popup window.

A: Try changing your code like this.

def Maze():
    tkinter_window = Tkinter_window()
    tkinter_window.run()

def answer():
    Qscreen.destroy()
    Maze()

def destroy():
    Qscreen.destroy()
    popup()

def play():
    popup()

play() # popup()
screen.mainloop()

The Maze is now created after user presses button.

A: You should now be able to click the button in the pop-up window
def popup():
  global Qscreen

  Qscreen = Toplevel(screen)
  Qscreen.attributes("-fullscreen", True)
  Qscreen.attributes("-topmost", True)
  Qscreen.title("QUESTION")

  QA = random.randint(0,1)
  Label(Qscreen, text = questions[QA]).pack()
  Button(Qscreen, text = "o", command = answer).pack()

  screen.after(10000, destroy)

def answer():
    Qscreen.destroy()
    Maze()

def destroy():
    Qscreen.destroy()
    popup()

def Maze():
    tkinter_window = Tkinter_window()
    tkinter_window.run()

def play():
    popup()

play()


text:
Q: Upgrading but get unmet dependencies grub-common:i386 Try to upgrade and get this error:
The following packages have unmet dependencies:
 grub2-common:i386 : Depends: grub-common:i386 (= 2.02-2ubuntu8.23)
E: Unmet dependencies. Try 'apt --fix-broken install' with no packages (or specify a solution).

However if I do that I get:
E: /var/cache/apt/archives/grub2-common_2.04-1ubuntu45_i386.deb: trying to overwrite '/etc/kernel/postinst.d/zz-update-grub', which is also in package grub-efi-amd64 2.04-1ubuntu44.1.2

I have no clue how to solve this. Please help.
ls -d /sys/firmware/efi gives:
config_table efivars esrt fw_platform_size fw_vendor runtime runtime_map systab vars
echo UEFI gives UEFI
echo BIOS gives BIOS


text:
Q: The complement of $L_1(0,1)$ in $L_1(0,1)^{**}$ Let $\mu$ be a finite measure, like the Lebesgue measure in $(0,1)$. It is well-known that  $L_1(\mu)$ and its second dual $L_1(\mu)^{**}$ are Banach lattices, $L_1(\mu)$ is a projection band in $L_1(\mu)^{**}$, and we can write $L_1(\mu)^{**}=L_1(\mu)\oplus L_1(\mu)^d$, where $L_1(\mu)^d = \{x^{**}\in L_1(\mu)^{**} : |x^{**}|\wedge |x|=0 \textrm{ for each }x\in L_1(\mu)\}$.
In "Linear Operators, Part I" 1988 by Dunford and Schwarz (IV.8.16 on page 296), there is a description of $L_1(\mu)^{**}$ as the space of finitely additive bounded signed measures that are absolutely continuous with respect to $\mu$ (with the variation norm). Every such finitely additive measure that is countably additive corresponds to an element of $L_1(\mu)$ by the Radon-Nikodym theorem.
I am interested in a description of the finitely additive measures that correspond with  elements of $L_1(\mu)^d$.

A: If I understand your question correctly, you are interested in a convenient description of $L_1^d(\mu)$. The finite additive measures are very inconvenient to work with. But Gelfand's representation allows to avoid them. According to
Kôsaku Yosida and Edwin Hewitt, Finitely additive measures, Trans. Amer. Math. Soc. 72 (1952), 46-66 (see theorem 4.3)

there exists a compact Hausdorff topological space $X$ such that Banach spaces $L_\infty(\mu)$ and $C(X)$ are isomorphic, $L_\infty(\mu)\simeq C(X)$. Therefore, $L_\infty^*(\mu)\simeq C^*(X)$. The last one is the space of Radon measures (regular countable additive Borel measures) on $X$ by the Riesz-Markov-Kakutani representation theorem, $L_\infty^*(\mu)\simeq\mathrm{rca}(X)$.
https://en.wikipedia.org/wiki/Continuous_functions_on_a_compact_Hausdorff_space
So instead of nasty finite additive measures in $L_\infty^*(\mu)$ we have nice countable additive measures on a compact Hausdorff space $X$. So $L_1(\mu)$ is identified with measures on $X$ that are absolutely continuous w.r.t. $1\in C(X)$, and $L_1^d(\mu)$ are whose that are singular to $1\in C(X)$.
The space $X$ and isomorphism $L_\infty(\mu)\simeq C(X)$ can be described more or less explicitly. Namely, $X$ is the space of characters $\chi$ on $L_\infty(\mu)$, i.e. $\chi\in L_\infty^*(\mu)$ and $\chi(fg)=\chi(f)\chi(g)$ for any $f,g\in L_\infty(\mu)$. The topology on $X$ is the restriction of the weak$^*$ topology on $L_\infty^*(\mu)$. The isomorphism $L_\infty(\mu)\simeq C(X)$ is given by
$f\in L_\infty(\mu)\quad\mapsto\quad F\in C(X)$
where $F(\chi) = \chi(f)$.


text:
Q: React Progressbar not Visible? I have created a React progress bar with the help of third part library
import React from "react";
import { css } from "@emotion/core";
import ClipLoader from "react-spinners/ClipLoader";

// Can be a string as well. Need to ensure each key-value pair ends with ;
const override = css`
  display: block;
  margin: 0 auto;
  border-color: red;
`;

class AwesomeComponent extends React.Component {
  constructor(props) {

    super(props);
    this.state = {
      loading: true
    };
  }

  render() {
    return (

        <ClipLoader
          css={override}
          size={150}
          color={"#123abc"}
          loading={this.state.loading}
        />

    );
  }
}
export default AwesomeComponent;

and then import in index.js file
import AwesomeComponent from './awesomeComponent.js';

ReactDOM.render(
  <Provider store={store}>
    <BrowserRouter>
      <App />
      <AwesomeComponent />
    </BrowserRouter>
  </Provider>,
  document.getElementById("root")
);

In my application i want to show this progresbar when data loading from nodejs api or any button clicked ..But nothing visible in GUI related to progressbar.

A: If you are using class based component for react-promise-tracker then you need to use HOC promiseTrackerHoc :
import React from "react";
import { css } from "@emotion/core";
import ClipLoader from "react-spinners/ClipLoader";
import { promiseTrackerHoc } from "react-promise-tracker"; // <--------- HERE

// Can be a string as well. Need to ensure each key-value pair ends with ;
const override = css`
  display: block;
  margin: 0 auto;
  border-color: red;
`;

class AwesomeComponent extends React.Component {
  constructor(props) {

    super(props);
    this.state = {
      loading: true
    };
  }

  render() {
    return (
        this.props.promiseInProgress && // <--------- HERE

            <ClipLoader
            css={override}
            size={150}
            color={"#123abc"}
            loading={this.state.loading}
            />

    );
  }
}
export default promiseTrackerHoc(AwesomeComponent); // <--------- HERE

WORKING DEMO :

Note :
You can checkout DOC, as they have explained everything, I
think you can help you to find out whatever the scenario you want to
implement

A: In this example, you can see how you can change the visibility of your spinner just changed the local state by clicking on button
https://codesandbox.io/s/modern-monad-4tipc?file=/src/AwesomeComponent.js


text:
Q: Sql Server Ignore update errors I have inherited a very old database that needs some data to be updated. Each row ha a column with a UniqueID that looks like C0042-45-39612. The last 3 numbers of the code are the category Id (in this case 612).
I need to do an update that targets only certain categories and I'm using this SQL statement
UPDATE WebbikesProducts SET Price = Price * 1.05 WHERE Convert( Integer, SubString( UniqueID, 3, 3 )) = 125

The obvious problem here is what if the unique code doesn't have 3 numbers at the end? Well that's exactly the problem I have as not all the items are categorized or have unique numbers like C0049-307-1CHROME.
I don't have access to the DB (I'm calling this from an asp page) so I'd prefer not to have to create a stored procedure. The DB is SQL 2000.
Is there any way to ignore the rows with errors and carry on updating the other rows?

A: I'm not sure why you are bothering converting to an int. Why not just do a string compare for the last three digits. Also, you are doing - substring(id, 3, 3).
I assume you have simplified the above snippet to make it easier to read and that you are already extracting the 39612 first?
I would suggest the following:
where UniqueID like '%612'

A: Try this:
UPDATE WebbikesProducts
SET Price = Price * 1.05
WHERE ISNUMERIC(SubString( UniqueID, 3, 3 )) = 1
AND Convert( Integer, SubString( UniqueID, 3, 3 )) = 125

or even more simple:
UPDATE WebbikesProducts
SET Price = Price * 1.05
WHERE SubString( UniqueID, 3, 3 ) = '125'

-Edo


text:
Q: How to run Streamlit and Telegram Bot (python-telegram-bot) simultaneously? I'm trying to run a Streamlit webpage and a python-telegram-bot instance together, because I need to call Telegram Bot functions from the Webpage.
Below is my code:
import streamlit as st
from telegram import Update
from telegram.ext import Updater, CallbackContext, MessageHandler, Filters

def echo(update: Update, context: CallbackContext) -> None:
    update.effective_chat.send_message(text="Hi")

def run_website():
    st.set_page_config(page_title="My Webpage", page_icon=":tada:", layout="wide")

def run_bot() -> None:
    updater = Updater('5222690292:AAHpTsw3ynWX0WA-2WonGErslqmoFjLHkvA')
    dispatcher = updater.dispatcher

    # Add handlers
    echo_handler = MessageHandler(Filters.all, echo)
    dispatcher.add_handler(echo_handler)

    # Start Bot
    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    run_website()
    run_bot()

When starting the script with streamlit run test.py, I run into the following error:
ValueError: signal only works in main thread of the main interpreter

I then tried removing updater.idle(), but got the following error:
telegram.error.Conflict: Conflict: terminated by other getUpdates request; make sure that only one bot instance is running

I also tried adding @st.cache to my run_bot() function to no avail (same error as above).


text:
Q: python 3.5: How to change the format of dictionary to be accepted by rest api I am trying to build an input parameter which is a dictionary, but it's format is different in compare with normal dictionary,
what i already have is this
{"sort": {"-p1.m_visits_all"}}

and I am trying to change the format of the dictionary which is valid one in my rest query, the final format should be like this
{"sort": "{-p1.m_visits_all}"}

but I don't know how to do it. Any suggestions?

A: First, you can convert each dict value to a string with str(...).
Now your example would look like this:
{"sort": "{'-p1.m_visits_all'}"}

Next, you remove all single quotes (') in the values
. Now you have:
{"sort": '{-p1.m_visits_all}'}

Finally, you may convert it to JSON with json.dumps(), and you and up with:
'{"sort": "{-p1.m_visits_all}"}'

Here is a function that formats a dict and then returns a JSON string:
def format_for_api(params):
  formatted = {}
  for k, v in params.items():
    params[k] = str(v).replace("'", "")

  return json.dumps(formatted)

Or, using compressions:
def format_for_api(params):
  return json.dumps({k: str(v).replace("'", "") for k, v in params.items()})

Happy coding :)


text:
Q: How to Replace Outliers with Median in Pandas dataframe? Here's my dataframe:
cars_num_df.head(10)

    mpg cylinders   displacement    horsepower  weight  acceleration    age
0   18.0    8          307.0          130.0     3504.0     12.0         13
1   15.0    8          350.0          165.0     3693.0     11.5         13
2   18.0    8          318.0          150.0     3436.0     11.0         13
3   16.0    8          304.0          150.0     3433.0     12.0         13
4   17.0    8          302.0          140.0     3449.0     10.5         13
5   15.0    8          429.0          198.0     4341.0     10.0         13
6   14.0    8          454.0          220.0     4354.0      9.0         13
7   14.0    8          440.0          215.0     4312.0      8.5         13
8   14.0    8          455.0          225.0     4425.0     10.0         13
9   15.0    8          390.0          190.0     3850.0      8.5         13

Later on, I have standardized the data using Zscore and then I want to REPLACE the outliers (not remove) with the median value of each column.
I tried doing this:
median = cars_numz_df.median()
std = cars_numz_df.std()
value = cars_numz_df

outliers = (value - median).abs() > 2*std

cars_numz_df[outliers] = cars_numz_df[outliers].abs()

cars_numz_df[outliers]

    mpg cylinders   displacement    horsepower  weight  acceleration    age
0   NaN 1.498191    NaN             NaN         NaN     NaN             NaN
1   NaN 1.498191    NaN             NaN         NaN     NaN             NaN
2   NaN 1.498191    NaN             NaN         NaN     NaN             NaN
3   NaN 1.498191    NaN             NaN         NaN     NaN             NaN
4   NaN 1.498191    NaN             NaN         NaN     NaN             NaN
5   NaN 1.498191    2.262118        2.454408    NaN     NaN             NaN
6   NaN 1.498191    2.502182        3.030708    NaN     2.384735        NaN
7   NaN 1.498191    2.367746        2.899730    NaN     2.566274        NaN
8   NaN 1.498191    2.511784        3.161685    NaN     NaN             NaN
9   NaN 1.498191    1.887617        2.244844    NaN     2.566274        NaN

Now, I'm trying to replace the outliers with the median by doing this:
cars_numz_df[outliers] = median

but I get this error:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-394-d48a51500f28> in <module>
      9 cars_numz_df[outliers] = cars_numz_df[outliers].abs()
     10
---> 11 cars_numz_df[outliers] = median
     12

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\frame.py
in __setitem__(self, key, value)
   3112
   3113         if isinstance(key, DataFrame) or getattr(key, 'ndim', None)
== 2:
-> 3114             self._setitem_frame(key, value)
   3115         elif isinstance(key, (Series, np.ndarray, list, Index)):
   3116             self._setitem_array(key, value)

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\frame.py
in _setitem_frame(self, key, value)
   3161         self._check_inplace_setting(value)
   3162         self._check_setitem_copy()
-> 3163         self._where(-key, value, inplace=True)
   3164
   3165     def _ensure_valid_index(self, value):

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\generic.py
in _where(self, cond, other, inplace, axis, level, errors, try_cast)
   7543
   7544                 _, other = self.align(other, join='left', axis=axis,
-> 7545                                       level=level,
fill_value=np.nan)
   7546
   7547                 # if we are NOT aligned, raise as we cannot where
index

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\frame.py
in align(self, other, join, axis, level, copy, fill_value, method, limit,
fill_axis, broadcast_axis)
   3548                                             method=method,
limit=limit,
   3549                                             fill_axis=fill_axis,
-> 3550
broadcast_axis=broadcast_axis)
   3551
   3552     @Appender(_shared_docs['reindex'] % _shared_doc_kwargs)

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\generic.py
in align(self, other, join, axis, level, copy, fill_value, method, limit,
fill_axis, broadcast_axis)
   7370                                       copy=copy,
fill_value=fill_value,
   7371                                       method=method, limit=limit,
-> 7372                                       fill_axis=fill_axis)
   7373         else:  # pragma: no cover
   7374             raise TypeError('unsupported type: %s' % type(other))

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\generic.py
in _align_series(self, other, join, axis, level, copy, fill_value, method,
limit, fill_axis)
   7469                     fdata = fdata.reindex_indexer(join_index, lidx,
axis=0)
   7470             else:
-> 7471                 raise ValueError('Must specify axis=0 or 1')
   7472
   7473             if copy and fdata is self._data:

ValueError: Must specify axis=0 or 1

Please advise, how can I replace the outliers with column median.

A: I don't have access to the dataset proposed in the question and therefore construct a randomized set of data.
import pandas as pd
import random as r
import numpy as np

d = [r.random()*1000 for i in range(0,100)]
df = pd.DataFrame({'Values': d})

median = df['Values'].median()
std = df['Values'].std()
outliers = (df['Values'] - median).abs() > std
df[outliers] = np.nan
df['Values'].fillna(median, inplace=True)

FWIW, clipping and winsorization should also be considered when trying to scoot outliers to somewhere useful.

A: In your example outliers returns a boolean DataFrame which can be used as a mask:
cars_numz_df.mask(outliers, other=median, axis=1, inplace=True)

Shown with another example:
import numpy as np
import pandas as pd

np.random.seed(0) # seed random
df = pd.DataFrame(np.random.rand(10,2)) # 2col dataframe

median = df.median() # 55.84, 68.05
std = df.std()
value = df

outliers = (value-median).abs() > 2*std

df.mask(outliers, other=median, axis=1, inplace=True)
df

A: The answer of @Rich Andrews is missing a z_thresh to say inside of how many sigmas you want to keep, here is the expanded version inside of a function:
def replace_numerical_outliers(df, column_name, z_thresh=3):
    median = df[column_name].median()
    std = df[column_name].std()
    outliers = ((df[column_name] - median).abs()) > z_thresh*std
    df[outliers] = np.nan
    df[column_name].fillna(median, inplace=True)


text:
Q: Failed to register MzCOM.exe in Racket 6.6, what's the reason? I tried to use MzCOM but it was not successfully registered on my system.Tried to run "C:\\Program Files\\Racket\\lib\\MzCOM.exe" /RegServer /v(I installed Racket in that directory) but got a error message box "registration failed", which says the access is denied. Then run it as administrator but I didn't get any output and the MzCOM is still not registered.
P.S. Using Windows10 with Visual Studio 2015


text:
Q: Drupal hook_user_update is not working I want the last updated time of the user profile details. So i have created a table user_changes with fields ( id, uid, changed ). When i use this hook_user_update hook , then data is not inserted into the table. I'm using this function in my theme's template.php
function garland_user_update(&$edit, $account, $category) {
    db_insert('user_changes')->fields(array(
    'uid' => $account->uid,
    'changed' => time(),
    ))->execute();
    exit;
}

Let me know if you want any details. Thanks in advance.

A: Hooks must be implemented in modules, not in themes. For that, choose a name (e.g. example), create a directory by that name in sites/all/modules, create the example.info file with content
name = Example
description = Does some fancy stuff in certain situations
core = 7.x

in that directory and put your function in sites/all/modules/example/example.module. You also have to rename your function to example_user_update.
Further reading:

*

*Writing module .info files (Drupal 7.x)

*Understanding the hook system for Drupal modules

*module_invoke_all, the function that is used to invoke hook implementations.


text:
Q: Gimp: why can't I register this? I'm writing an add-on for Blender to sync it with Gimp and this script should be able to start from within Gimp, but I can't register it... Why?
blender_gimp_sync.py:
# -*- coding: utf-8 -*-

#!/usr/bin/env python

from gimpfu import *

def blender_gimp_sync():
    image_dir = "/home/antoni4040/Έγγραφα/Layout.png"
    image = gimp.pdb.gimp_file_load(image_dir, image_dir)
    gimp.Display(image)

register(
    "python_fu_bgsync",
    "Blender-Gimp Sync",
    "Syncronize Gimp with Blender for texturing",
    "Antonis Karvelas",
    "Antonis Karvelas",
    "2012",
    "<Image>/Image/Blender-Gimp Sync",
    "*",
    [],
    [],
    blender_gimp_sync
)

main()

It's really strange...

A: You didn't say which error you are getting - but since you posted your source file I think I can guess it:
GIMP expect's it's plug-ins to be exectuable by the system - and what tell's Posix (linux included) systems that a file should be executed with a particular interpreter or shell is the  shebang line - the line that goes #!/usr/bin/env python in your example.
This line, however, has to be the first line in your file - the #! characters in it should be the first two characters in the file. The line denoting the character encoding - # -*- coding: utf-8 -*- should come after it - it has to be the second line in the file, no blank lines between them).
And finally, be sure to set the script as executable, by running "chmod a+x " on the Python file.
related to it, but not being what is causing the problem, putting the menu path along with the script menu name is deprecated in GIMP - the correct way to do it is, after the "date" parameter, pass just the name that should show in the menu -- "Sync" - and pass the menu path as a named parameter, at the end of the call, like: menu="<Image>/Image/Blender-Gimp"


text:
Q: StackOverFlow Exception in Outlook Addin I am a newcomer to world of programming and trying to refactor a Outlook Addin in which all code was written in ThisAddIn.cs i.e. automatically generated file. I have separated contents of ThisAddIn to several class but when I am debugging my application StackOverflow Exception is thrown. What could be the cause for such problem?

A: Generally speaking an StackOverflowException means that some code has entered an endless loop. Consider the example below, which will never terminate. Imagine that Main is the entry-point into your application (i.e. Outlook addin), then method A and Main will keep calling each other until an StackOverflowException occurs.
public void Main()
{
    A();
}

public void A()
{
    Main();
}

If you can run the application in debug-mode in Visual Studio, it will generally tell you the stack trace from where the StackOverflowException occurred. Using that information it should be possible to track down the error.
It is often caused by recursive functions (e.g. due to misuse or with a "bad" stopping condition) or events that keep raising each other.

A: The most common cause is a recursive function: a function that calls itself.
See this for troubleshooting tips: How do I prevent and/or handle a StackOverflowException?
When you're debugging you want to pause/halt code execution when the call stack grows extremely large and then the problem will be visible. Here is an example, if you called this function with large numbers you'd get a Stackoverflow Exception:
private long Multiply(int x, int y)
{
  x+=y;
  y--;
  if (y==0) return x;
  return Multiply(x,y);
}


text:
Q: Breaks for scale_x_date in ggplot2 and R I am plotting value~date in ggplot2 (in R). I have the following code. As you see ggplot2 adds more breaks on the x-axis that I have in my data. I just want to have the x-label everytime I have a data point in my data frame. How can I force ggplot2 to just show the breaks only at the values of my.dates? It seems there is no "breaks" argument for scale_x_date
require(ggplot2)
my.dates = as.Date(c("2011-07-22","2011-07-23",
                     "2011-07-24","2011-07-28","2011-07-29"))
my.vals  = c(5,6,8,7,3)
my.data <- data.frame(date =my.dates, vals = my.vals)
plot(my.dates, my.vals)
p <- ggplot(data = my.data, aes(date,vals))+ geom_line(size = 1.5)
p <- p + scale_x_date(format="%m/%d", ' ')
p

A: One approach would be to treat the x-axis as numeric and set the breaks and labels aesthetics with scale_x_continuous().
ggplot(my.data, aes(as.numeric(date), vals)) +
  geom_line(size = 1.5) +
  scale_x_continuous(breaks = as.numeric(my.data$date)
                     , labels = format(my.data$date, format = "%m/%d"))

though the break between 7/24 through 7/28 looks a bit strange in my opinion. However, I think that's what you want? Let me know if I've misinterpreted.
EDIT
As noted above, I wasn't thrilled with the way the breaks looked above, specifically with the gray grid in the background. Here's one way to maintain the rectangular grid and to only label the points where we have data. You could do this all within the ggplot call, but I think it's easier to do the processing outside of ggplot. First, create a vector that contains the sequence of numbers corresponding to the dates. Then we'll update the appropriate labels and replace the NA entries with " " to prevent anything from being plotted on the x-axis for those entries:
xscale <- data.frame(breaks = seq(min(as.numeric(my.data$date)), max(as.numeric(my.data$date)))
                      , labels = NA)

xscale$labels[xscale$breaks %in% as.numeric(my.data$date)] <- format(my.data$date, format = "%m/%d")
xscale$labels[is.na(xscale$labels)] <- " "

This gives us something that looks like:
  breaks labels
1  15177  07/22
2  15178  07/23
3  15179  07/24
4  15180
5  15181
6  15182
7  15183  07/28
8  15184  07/29

which can then be passed to the scale like this:
scale_x_continuous(breaks = xscale$breaks, labels = xscale$labels)


text:
Q: How to Remove No Data from a NetCDF Raster Layers? Question: How to remove no data from a NetCDF Raster Layer?
I am trying to use the Zonal Statistics as Table tool in ArcGIS to calculate the mean. The problem  is I am not getting the correct mean, because I have no data information inside the Raster Layer. I am able to not view the no data and change the value in symbology in properties, but still I get the incorrect mean.  I have also tried going into ArcCatalog and changing the no data, but it does not work for NetCDF Raster Layers, just Raster.


text:
Q: dask 100GB dataframe sorting / set_index on new column out of memory issues I have a dask dataframe of around 100GB and 4 columns that does not fit into memory. My machine is an 8 CORE Xeon with 64GB of Ram with a local Dask Cluster.
I converted the dataframe to 150 partiitions (700MB each). However
My simple set_index() operation fails with error "95% memory reached"
    g=dd.read_parquet(geodata,columns=['lng','indexCol'])
    g.set_index('lng').to_parquet('output/geodata_vec_lng.parq',write_index=True  )

I tried:

*

*1 worker 4 threads. 55 GB assigned RAM

*1 worker 2 threads. 55 GB assigned RAM

*1 worker 1 thread.  55 GB assigned RAM

If I make the partitions smaller I get exponentially more shuffling. 100GB is not large. What am I doing wrong?


text:
Q: Access raw date values in Officejs add-in selection I am trying to access values in Excel plugin via Officejs.
Office.context.document.getSelectedDataAsync(
    Office.CoercionType.Matrix,
    function(asyncResult => ...)

What I am looking for is an automatic way to access date values in their raw format without deduction if it is a date (initially, they are in Excel-like format, represented by a number of days after 01/01/1900).
Text of callback, but I can't find any interface to use so far.
Office.context.document.getSelectedDataAsync(zone, options, callback) returns numbers in all the cases.

A: You may try to get the value by using range.values API, then use setNumberFormat("dd/MM/yyyy") to set it into time format.


text:
Q: Can implicit value be also a lazy value when used as implicit method parameter value? I have a test suite which uses Slick for DB access. Some tests in this suite access the DB and some not.
My suite has
implicit val db = DB.getDB
which effectively initializes DataBaseDef at the beginning of the suite execution. This value then is used as implicit parameter value for some methods.
Also it has the afterAll() which closes the db at the end of suite execution:
override def afterAll():Unit={
    db.close()
    super.afterAll()
  }

Now if I changed to:
implicit lazy val db = DB.getDB
then what exactly will happen?
If I run only a test which does not use the DB then the connection will not be initialized and in the afterAll() it will still try to close the connection and I have a problem in this case, right? I tried to run but no error happened and no exception was thrown...
My knowledge of implicits is not enough to help me understand it in combination with lazy.

A:
then what exactly will happen?

The value won't be initialized until the first access to it.

it will still try to close the connection and I have a problem in this
  case, right?

When you access db.close(), it will first initialize the value, which means it will call DB.getDb prior to closing the connection. This means, although you didn't intend to, the connection would be still initialized and then immediately closed, hence why you don't see an exception.

A: To add to the accepted answer, I'd like to point out that implicit are resolved at compile time, while val lazy val and def have implications at runtime only.
If you define an identifier as implicit, it will tell the compiler that you have access to an implicit value of the given type, so any method that need such an implicit parameter will use it; conversely, if you don't declare an implicit identifier of a given type, any call to a method needing a value of that type will throw a compiler error. However, once the code is compiled, there is no need for implicits anymore (they have been replaced by explicit references to the relevant identifier, depending on scope).
Now, at runtime, when an implicit identifier is called, it will be instantiated with the standard rules, so it can be either instantiated and memoized at definition if it's a val, instantiated and memoized at usage if it's a lazy val or instantiated at each usage if it's a def. The fact that it used to be an implicit parameter has no influence on the instantiation rules.


text:
Q: pom.xml giving same error everytimr i create new spring project? I have used https://start.spring.io/ to create a new spring-boot project, choosing maven and spring-web as my dependency.
But as soon as I import this to my Eclipse as Existing maven project, I am getting some error in my pom.xml file, and I am getting it every time I make new spring-boot project.
Error Message:
Failure to transfer net.bytebuddy:byte-buddy-agent:jar:1.10.14 from https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced. Original error: Could not transfer artifact net.bytebuddy:byte-buddy-agent:jar:1.10.14 from/to central (https://repo.maven.apache.org/maven2): The operation was cancelled.

org.eclipse.aether.transfer.ArtifactTransferException: Failure to transfer net.bytebuddy:byte-buddy-agent:jar:1.10.14 from https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced. Original error: Could not transfer artifact net.bytebuddy:byte-buddy-agent:jar:1.10.14 from/to central (https://repo.maven.apache.org/maven2): The operation was cancelled.
    at org.eclipse.aether.internal.impl.DefaultUpdateCheckManager.newException(DefaultUpdateCheckManager.java:225)
    at org.eclipse.aether.internal.impl.DefaultUpdateCheckManager.checkArtifact(DefaultUpdateCheckManager.java:193)
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.gatherDownloads(DefaultArtifactResolver.java:559)
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.performDownloads(DefaultArtifactResolver.java:483)
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:401)
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolveArtifacts(DefaultArtifactResolver.java:229)
    at org.eclipse.aether.internal.impl.DefaultRepositorySystem.resolveDependencies(DefaultRepositorySystem.java:340)
    at org.apache.maven.project.DefaultProjectDependenciesResolver.resolve(DefaultProjectDependenciesResolver.java:202)
    at org.apache.maven.project.DefaultProjectBuilder.resolveDependencies(DefaultProjectBuilder.java:227)
    at org.apache.maven.project.DefaultProjectBuilder.build(DefaultProjectBuilder.java:200)
    at org.apache.maven.project.DefaultProjectBuilder.build(DefaultProjectBuilder.java:124)
    at org.eclipse.m2e.core.internal.embedder.MavenImpl.readMavenProject(MavenImpl.java:629)

Below is the code of my pom.xml file: The error is coming at the 3rd line below
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.serviceonepavilion.customerapi</groupId>
    <artifactId>customer-api</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>SpringBootH2IntegrationNew</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Thanks in advance for any help or guidance..

A: Try to run maven project update with

force update snapshots

option selected.
A specific jar was not downloaded properly. Retrying would solve in most cases.


text:
Q: Is it possible to do Vectored Strctured exception handling in c#? As far as i know, when a first chance exception occurs, the debugger is notified(if any) and then if still unhandled, the system searches for the nearest frame based exception handler in the stack if any.
I was reading this link when I came to know about vectored exception handling.
Question1) I was wondering if there is any way we can do that in managed code?
Question2) I think that any try{}catch{} is a frame based handler but what happens when we register a handle at certain events like
AppDomain.CurrentDomain.UnhandledException += (x, y) =>
{
    Console.WriteLine("Unhandled exception");
};

what are these?

A: The debugger is only notified of an exception if it is attached.  For example, if you are debugging in Visal Studio, then it would be called first, and if it passed on the exception, the exception handlers would be called.  To have the debugger stop on all exceptions, from Visual Studio select the Debug menu and select Exceptions and then choose the exceptions you want the debugger to halt at.  If none of those handlers (or there are no handlers) then the debugger would be called a 2nd time to stop execution and display a general message that an exception had occurred.  If on the other hand, the debugger is not attached, then the debugger won't be notified - which is the case for 99%+ of all managed production code.
Vectored exception handling is a low level api intended to be used from unmanaged code - i.e. C++.  Your very first choice from managed code (C#) should be to use structured exception handling with try/catch/finally blocks.  Most (99%+) managed code developers using a language like C#, including myself, have found structured exception handling to be quite adequate.
If you still think you need to use this api, you will have to call AddVectoredExceptionHandler by using P/Invoke, which is one way unmanaged code can be called from managed code.  There are a couple of caveats.  See this link for a general overview.  Mike Stall's blog suggests avoiding vectored exceptions in managed code.  In this thread, Mike Stall says that unmanaged vector exception handlers should never call back into managed code.  He also suggests that managed exceptions are an undocumented feature in vectored exception handling and that MS could eliminate that support in a future release of the CLR, so use at your own peril.
The AppDomain.UnhandledException event is only called when no other handler is found.  It could be used in situations where it is desired to log some information about an unhandled exception, but there is little time to put in proper structured exception handling to a large base of existing code, or perhaps you don't have access to the code that is throwing the exception.  Otherwise, try/catch/finally blocks should be used instead.
You might also try taking a look at the AppDomain.FirstChanceException event, which occurs before the first exception handler is called.  This one might be useful if all you want to do is log some information for certain exceptions thrown in someone else's code that you don't have access to that are handled.  It is only a notification though, and not an exception handler.  I have never used it before, so don't know how much it might affect performance.  My concern here is that Microsoft developers sometimes throw exceptions in the CLR for various things other than true errors.  To see this in action, try setting the debugger to break on every exception, including the CLR Runtime exceptions.  This can be done in Visual Studio from the Debug menu and choosing Exceptions.  So, I don't know how much of an impact it would have on performance since all the CLR exceptions will probably raise this event as well.  To be fair, the last time I did this was with VS 2008.  This might not be true or as true with later versions of the CLR.  I don't see a way to limit the exceptions this event will fire either.  So, you would need to filter out the exceptions you are not interested in and experiment to guage its impact on performance.


text:
Q: Why does Flutter app getting slow in live version After update the flutter sdk, the app getting slow after some 6-7 days. We are storing data offline, cache image and audio download option for offline use, but now it is hanging the full app. Right now we are using a function that check 7 days duration, and delete caches, but still the app running slow and sometime hanged.

A: It's hard to answer this question without seeing your code. This can have many reasons:

*

*It takes too long to load data from memory

*It takes too long to write data to memory

*There may be a delay in parsing

*There can be a delay in searching and finding the data

You will most likely need to improve one or more of these to make the app stop slowing down.


text:
Q: Unable to connect to mongo-express in Kubernetes cluster depending on the version tag I setup mongo-express in my local cluster and when connecting to it from localhost:8081 after successful authentication I see the message Turn on admin in config.js to view server statson the page. Searching for the issue I saw that it was related to the mongo-express:latest image I was using, and that mongo-express:0.54.0 should be used instead from SO question Turn on admin in config.js to view server stats, but with it it doesn't connect to it at all.
I also tried mongo-express:0.54 image but still not connecting, mongo-express:1.0.0-alpha.4 authorise fince but still shows the Turn on ... message.
mongo-express:latest logs
Welcome to mongo-express
------------------------

(node:7) [MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
Mongo Express server listening at http://0.0.0.0:8081
Server is open to allow connections from anyone (0.0.0.0)

mongo-express:0.54.0 logs
Waiting for mongo:27017...
/docker-entrypoint.sh: line 14: mongo: Name does not resolve
/docker-entrypoint.sh: line 14: /dev/tcp/mongo/27017: Invalid argument
Sun Jan 15 17:37:59 UTC 2023 retrying to connect to mongo:27017 (2/5)
/docker-entrypoint.sh: line 14: mongo: Name does not resolve
/docker-entrypoint.sh: line 14: /dev/tcp/mongo/27017: Invalid argument
Sun Jan 15 17:38:00 UTC 2023 retrying to connect to mongo:27017 (3/5)
/docker-entrypoint.sh: line 14: mongo: Name does not resolve
/docker-entrypoint.sh: line 14: /dev/tcp/mongo/27017: Invalid argument
Sun Jan 15 17:38:01 UTC 2023 retrying to connect to mongo:27017 (4/5)
/docker-entrypoint.sh: line 14: mongo: Name does not resolve
/docker-entrypoint.sh: line 14: /dev/tcp/mongo/27017: Invalid argument
Sun Jan 15 17:38:02 UTC 2023 retrying to connect to mongo:27017 (5/5)
/docker-entrypoint.sh: line 14: mongo: Name does not resolve
/docker-entrypoint.sh: line 14: /dev/tcp/mongo/27017: Invalid argument

I set ME_CONFIG_MONGODB_URL, ME_CONFIG_BASICAUTH_USERNAME and ME_CONFIG_BASICAUTH_PASSWORD mongo-express values getting them from the mongo-rs-fixit-admin-user secret that the operator creates by default which are correct as  use them for connecting the node.js app to mongo. ME_CONFIG_MONGODB_ENABLE_ADMIN is set to true.
I deploy mongo db replica set with the community operator and by not specifying a service it will use the one that the operator creates by default.
The operator also creates a secret containing the connection strings for mongo.
Is there something I'm doing wrong?
Many thanks for your time and help.
Cheers
mongo service created by the operator
vincenzocalia@vincenzos-MacBook-Air kubernetes_yaml_files % kubectl describe svc mongo-rs-svc
Name:              mongo-rs-svc
Namespace:         default
Labels:            app=mongo-rs-svc
Annotations:       <none>
Selector:          app=mongo-rs-svc
Type:              ClusterIP
IP Family Policy:  SingleStack
IP Families:       IPv4
IP:                None
IPs:               None
Port:              mongodb  27017/TCP
TargetPort:        27017/TCP
Endpoints:         10.1.0.79:27017,10.1.0.80:27017
Session Affinity:  None
Events:            <none>

mongo secret created by the operator
Name:         mongo-rs-fixit-admin-user
Namespace:    default
Labels:       <none>
Annotations:  <none>

Type:  Opaque

Data
====
connectionString.standardSrv:  108 bytes
password:                      8 bytes
username:                      10 bytes
connectionString.standard:     177 bytes

mongo deployment
apiVersion: mongodbcommunity.mongodb.com/v1
kind: MongoDBCommunity
metadata:
  name: mongo-rs
  namespace: default
spec:
  members: 2
  type: ReplicaSet
  # mongo version
  version: '5.0.5'
  security:
    authentication:
      modes:
        - SCRAM
  users:
    - name: admin-user

      db: fixit
      passwordSecretRef:
        name: mongo-secret
      roles:
        - name: clusterAdmin
          db: fixit
        - name: userAdminAnyDatabase
          db: fixit
      scramCredentialsSecretName: my-scram-mg-fixit
  additionalMongodConfig:
    storage.wiredTiger.engineConfig.journalCompressor: zlib
  statefulSet:
    spec:
      # You can specify a name for the service object created by the operator
      # if specified no connection strings are generated !!??
      # serviceName: mongo-rs-svc
      # get them with kubectl -n default get secret mongo-rs-fixit-admin-user -o json  and then decode them with echo "value" | base64 -d

      template:
        spec:
          affinity:
            podAntiAffinity:
              requiredDuringSchedulingIgnoredDuringExecution:
                - labelSelector:
                    matchExpressions:
                      - key: app
                        operator: In
                        values:
                          - mongo-replicaset
                  topologyKey: 'kubernetes.io/hostname'

      volumeClaimTemplates:
        - metadata:
            name: data-volume
          spec:
            accessModes:
              - ReadWriteOnce
              # - ReadWriteMany
            storageClassName: mongo-sc-data
            resources:
              requests:
                storage: 10Gi
        - metadata:
            name: logs-volume
          spec:
            accessModes:
              - ReadWriteOnce
              # - ReadWriteMany
            storageClassName: mongo-sc-logs
            resources:
              requests:
                storage: 2Gi

mongo-express deployment
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: mongo-express
  name: mongo-express
  namespace: default
spec:
  selector:
    matchLabels:
      app: mongo-express
  template:
    metadata:
      labels:
        app: mongo-express
    spec:
      containers:
        - name: mongo-express
          # image: mongo-express # connects but Turn on admin in config.js to view server stats!
          # image: mongo-express:latest # connects but  Turn on admin in config.js to view server stats!
          image: mongo-express:0.54.0
          # image: mongo-express:0.54
          imagePullPolicy: 'Always'
          ports:
            - containerPort: 8081
              protocol: TCP

          resources:
            limits:
              memory: '1Gi'
              cpu: '100m'
          env:
            # - name: ME_CONFIG_MONGODB_SERVER
            # value: mongo-rs-0.mongo-rs-svc.default.svc.cluster.local
            - name: ME_CONFIG_MONGODB_URL
              valueFrom:
                secretKeyRef:
                  name: mongo-rs-fixit-admin-user
                  key: connectionString.standard
            - name: ME_CONFIG_MONGODB_ENABLE_ADMIN
              value: 'true'
            - name: ME_CONFIG_BASICAUTH_USERNAME
              valueFrom:
                secretKeyRef:
                  name: mongo-rs-fixit-admin-user
                  key: username
            - name: ME_CONFIG_BASICAUTH_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: mongo-rs-fixit-admin-user
                  key: password
      restartPolicy: 'Always'

mongo-express service
apiVersion: v1
kind: Service
metadata:
  labels:
    app: mongo-express
  name: mongo-express
  namespace: default
spec:
  ports:
    - name: http
      port: 8081
      targetPort: 8081
      protocol: TCP
  selector:
    app: mongo-express
  type: LoadBalancer
``


text:
Q: Is any PHP Script available which is able to Ping an IP Address I want to ask is any php script available which is able to ping an IP Address if is it so let me know how we can do that ...?

A: $ip =   "127.0.0.1";
exec("ping -n 3 $ip", $output, $status);
print_r($output);

Output will be an Array. Something like this:
Array
(
    [0] =>
    [1] => Pinging 127.0.0.1 with 32 bytes of data:
    [2] => Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
    [3] => Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
    [4] => Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
    [5] =>
    [6] => Ping statistics for 127.0.0.1:
    [7] =>     Packets: Sent = 3, Received = 3, Lost = 0 (0% loss),
    [8] => Approximate round trip times in milli-seconds:
    [9] =>     Minimum = 0ms, Maximum = 0ms, Average = 0ms
)

A: On linux, you the use the following :
<?php
    function ping($ip) {
        $result = exec("/bin/ping -n 3 $ip", $outcome, $status);
        if (0 == $status) {
            $status = "alive";
        } else {
            $status = "dead";
        }
        echo $status;
    }

    ping("80.80.80.80");

?>


text:
Q: Merge partial rows while keeping the rest I would like to merge some rows while keeping the rest of the rows and the order of columns.
df1 <- data.frame(by1=c(1,3,5,7,9),
                 by2=c(6:10),
                 x=c("a",NA_character_,NA_character_,NA_character_,"e"),
                 y=c("q","w","e","r","t"),stringsAsFactors = F)
df1
  by1 by2    x y
1   1   6    a q
2   3   7 <NA> w
3   5   8 <NA> e
4   7   9 <NA> r
5   9  10    e t

df2 <- data.frame(by1=c(3,5),x=c("b","c"),stringsAsFactors = F)
df2
  by1 x
1   3 b
2   5 c

Expected output:
expected <- data.frame(by1=c(1,3,5,7,9),
                       by2=c(6:10),
                       x=c("a","b","c",NA_character_,"e"),
                       y=c("q","w","e","r","t"),stringsAsFactors = F )
expected
  by1 by2    x y
1   1   6    a q
2   3   7    b w
3   5   8    c e
4   7   9 <NA> r
5   9  10    e t

I can get the expected output by using the following code. However, it is not clean:
df1%>%
  merge(df2%>%rename(x2=x),by="by1",all.x=T)%>%
  mutate(x=coalesce(x,x2))%>%
  select(-x2)

A: Use rows_update
library(dplyr)
rows_update(df1, df2)

-output
  by1 by2    x y
1   1   6    a q
2   3   7    b w
3   5   8    c e
4   7   9 <NA> r
5   9  10    e t


text:
Q: UItableview section selected - swift ''Hello World'' :)
 I have a UItableview with 4 different sections. I'm trying to  fill each sections with some rows depending on the section selected. I am struggling -__- to detect which section is selected in order to fill them accordingly. In my program I have  created 4 uibuttons (outside of the tableview and they represents each user; when a button is selected I use them to name the section header). Now I would like to link the button selected with the section.
 How one should proceed to know which section is selected. If button A is selected it would mean that  section 0 is selected then do operation x in section 0 (like inserting a new row for example);
 if button B is selected (i.e section 1 is selected) then Do operation y and so on...
Thanks in advance for helping a desperate soul

A: Set tags for buttons.
button1.tag = 0
button2.tag = 1
button3.tag = 2
button4.tag = 3

then add targets
button1.addTarget(self, action: #selector(didTouchButton(_:)), for: .touchUpInside)
button2.addTarget(self, action: #selector(didTouchButton(_:)), for: .touchUpInside)
button3.addTarget(self, action: #selector(didTouchButton(_:)), for: .touchUpInside)
button4.addTarget(self, action: #selector(didTouchButton(_:)), for: .touchUpInside)

then when button will select check sender tag and do operation on section
func didTouchButton(_ sender: UIButton) {
    let section = sender.tag

    //do operations in section
}

Here are examples of inserting and deleting rows in section based on section index. In Swift3 you should base on this methods:
func insertRows(at: [IndexPath], with: UITableViewRowAnimation)
func deleteRows(at: [IndexPath], with: UITableViewRowAnimation)


text:
Q: Machine data not displaying output every 15 Seconds The following script is meant to output "vmstat" for example every 15 seconds, but for some reason it only does this if there's activity or when I kill the script, in other cases it just sits there.
#!/bin/bash
#!/bin/sh

ps -ef | grep -v grep | grep "vmstat 15" | awk '{ print $2 }' | xargs kill

ps -ef | grep -v grep | grep "iostat 15" | awk '{ print $2 }' | xargs kill

ps -ef | grep -v grep | grep "mpstat 15" | awk '{ print $2 }' | xargs kill

today=`date +%Y-%m-%d.%H:%M:%S`

find /var/log/ -name data_collection -type d -exec mv /var/log/data_collection /home/Beer/"data_collection_${today}" \;

mkdir -p /var/log/data_collection

vmstat 15 | /home/Beer/./addtimestamp.pl > /var/log/data_collection/vm_stat &
iostat 15 | /home/Beer/./addtimestamp.pl > /var/log/data_collection/ios_stat &
mpstat 15 | /home/Beer/./addtimestamp.pl > /var/log/data_collection/mp_stat &

Im guessing the '&' symbol at the end has something to do with this, I only did this so I can execute each command at once.

A: Since feature requests to mark a comment as an answer remain declined, I copy the above solution here.
What is in addtimestamp.pl? It could be that it's buffering input, and not flushing every time it reads something. – Diego Basch
@DiegoBasch that's exactly correct, I just added a '$|=1;' to the Perl script now and it started to work, basically setting the it to line buffer. Ill add the answer. – I AM L


text:
Q: Radiative corrections to $V-A$ and $V+A$ currents In Appendix A of the following reference, p.128,
Masaru Doi, Tsuneyuki Kotani, Eiichi Takasugi, Double Beta Decay and Majorana Neutrino, Progress of Theoretical Physics Supplement, Volume 83, March 1985, Pages 1–175, https://doi.org/10.1143/PTPS.83.1
The radiative correction to arbitrary order of perturbation to the effective tree level $V\pm A$ quark current is given as,
\begin{align}
\overline{u}\gamma^\mu(1\mp\gamma^5)d = \overline{u}(p_1)\Gamma^{\rho\nu ... ..\lambda}\gamma^\mu(1\mp\gamma^5)\Gamma'_{\rho\nu ... ..\lambda}d(p_2), \tag{1}\label{eqn1}
\end{align}
where $u$ and $d$ are up and down quarks. $\Gamma^{\rho\nu ... ..\lambda}$ consists of $\gamma^\mu$, $\gamma^\nu$, ...... $\gamma^\lambda$, $\gamma^\mu p_{1\mu}$, $\gamma^\mu p_{2\mu}$, masses of quarks and coupling constants. How do we get the r.h.s of \eqref{eqn1} from l.h.s by applying radiative correction?


text:
Q: Solidity - Invalid BigNumber string (argument="value" value="" code=INVALID_ARGUMENT version=bignumber/5.4.2) solidity newbie here. when I try to read the value of the people array. I'm getting an error:

call to SimpleStorage.people errored: Error encoding arguments: Error:
invalid BigNumber string (argument="value" value=""
code=INVALID_ARGUMENT version=bignumber/5.4.2)

my compiler version is 0.6.6. not sure what's wrong? any suggestions?
// SPD-License_Identifier: MIT

pragma solidity ^0.6.0;

contract SimpleStorage {
    uint256 favNum;

    struct People {
        uint256 favNum;
        string name;
    }

    People[] public people;

    function store(uint256 _favNum) public {
        favNum = _favNum;
    }

    function retrieve() public view returns(uint256) {
        return favNum;
    }

    function addPerson(string memory _name, uint256 _favNum) public {
        people.push(People(_favNum, _name));
    }
}

A: The error happens when you're trying to call the people() function (from Remix IDE) without passing any value.
Since the People[] public people is a public property, it autogenerates a getter function during compilation. But because it's an array, the getter function requires an uint256 param specifying the index of the array that you want to retrieve.
When you pass an empty string, Remix tries to encode it to the BigNumber instance, but this fails. Only when you pass an (existing) index of the array, it works correctly:

If you want to get the whole array in one call, you need to create a separate getter function:
function getAllPeople() public view returns (People[] memory) {
    return people;
}

A: You must click on the small arrow to the right of the deploy button, then the fields will be displayed so that you can complete the data that the contract must receive.


text:
Q: Spring Boot gradle build - invalid source release: 11 I am trying to build my spring boot project with this command:
./gradlew build

But it continuously throws this error:
'Execution failed for task ':compileJava'. invalid source release: 11'.

My project is using Java version 11, and the IntelliJ Java version is set to 11 as well.
This is the Java version settings on my IntelliJ that I have done so far:

*

*Settings - Build, Execution, Deployment - Build Tools - Gradle
-> set to 11.

*Settings - Build, Execution, Deployment - Compiler - Java Compiler - Project bytecode version
-> set to 11.

*java -version command on IntelliJ Terminal
-> set to 11.0.12

*Project Structure - Project Settings - Project - Project SDK:
-> set to 11.

*Project Structure - Project Settings - Modules - Module SDK:
-> set to 11.

*Project Structure - Platform Settings - SDKs - JDK home path:
-> set to 11.

*System Environment path - JAVA_HOME
-> set to 11.

*build.gradle - sourceCompatibility, targetCompatibility
-> set to 11.

After all of this when I run
./gradlew build

result

I think I've done everything possible. Is there any other settings that I can try ??

A: There are 2 solutions. The problem is likely happening because Gradle Wrapper tried to find JDK 11 in Java_home and failed to find it there. I don't think it's because you are using some old deprecated dependencies that don't support jdk11.
Solution1
Explicitly mention the JDK you want to use on terminal.
For example, instead of
./gradlew build

Use
./gradlew build -Dorg.gradle.java.home=yourjdk11homepath

Your path might be something like:
C:\\Program Files\\OpenJDK\\jdk-11.0.3

Solution 2
If you don't want to apply solution1 whenever you build project using gradle wrapper, you set the option in gradle.properties file.
On the same directory level as build.gradle and gradlew files, make
gradle.properties

file and write following:
org.gradle.java.home=yourjdk11homepath

Again, your path might be something like:
C:\\Program Files\\OpenJDK\\jdk-11.0.3

A: Please check Gradle JVM config
Click to see how to confg

A: In my case it's my sdkman which no longer supports adoptopenjdk 11 and the project got renamed to Temurin.
Reference: https://sdkman.io/jdks
So my gradle build was trying to resolve the missing adoptopenjdk 11 and it couldn't.
I reinstalled the jdk 11 from Temurin
sdk install java 11.0.14-tem

And voila it solved the build issue and my gradle build is successful.

A: Set project jdk to 1.8 instants 11


text:
Q: Are subtitles included in Apple's App Store Search algorithm? In iOS 11 Apple included a new metadata field in the App Store, "Subtitle". What I am wondering is if the subtitle is included in Apple's App Store Search algorithm, and is there anyway to know how it is weighted?
Apple explains their search algorithm contains a few new fields, but does not explicitly mention that subtitles are included, only that they are visible to the user in the results page.

Search results now include developers, in-app purchases, categories,
  editorial stories, tips and tricks, and collections. Apps appear in
  search results with subtitles and a single rating prominently
  displayed.

Source: https://developer.apple.com/app-store/search/
However, to contradict this I tested in an iOS 11 beta device, and I was able to get the correct app in the search results by entering an app's subtitle.
Is anyone aware of specific documentation that helps clarify the roles subtitles play in Apple's App Store Search functionality?

A: The answer is yes. Apple's App Store search algorithm includes the subtitle. Verified by searching for apps with unique subtitles that were not present in the description of the app.


text:
Q: Get child process id
Possible Duplicate:
Best way to kill all child processes

I am running a script, which runs a java program in the background using the eval command.
eval <java java_program & >

While running the above command, I found that it creates a new child process. Now when I want to stop the process, in the script I tried with the command '$!', which always gives me only parent process id. So kill -9 $! kills the parent process and leaves the child process still running in background.
Is there a way to find all the child processes associated with a process id and kill all the processes? Or what's the efficient way of killing all the process?

A: You may try to use pstree using the parent pid
and for killing it may worth a visit for this:
Best way to kill all child processes


text:
Q: List of all folders and files for x depth I want to have list of all folders and files for x depth.
If x is 2 than I will have information about all folders and files from first folder, and all folders and files from folders in first folder.
How to do this?

A: This code will do what other answers are doing, but also return the folder names (as that appears to be part of what you are asking). This will require .Net 4.0. If you wish to keep track of which are folders and which are files you could return a tuple containing a list of files and a list of folders.
List<string> GetFilesAndFolders(string root, int depth)
{
    var list = new List<string>();
    foreach(var directory in Directory.EnumerateDirectories(root))
    {
        list.Add(directory);
        if (depth > 0)
        {
            list.AddRange(GetFilesAndFolders(directory, depth-1));
        }
    }

    list.AddRange(Directory.EnumerateFiles(root));

    return list;
}

EDIT: Code that keeps the folders and files separate
Tuple<List<string>,List<string>> GetFilesAndFolders(string root, int depth)
{
    var folders = new List<string>();
    var files = new List<string>();
    foreach(var directory in Directory.EnumerateDirectories(root))
    {
        folders.Add(directory);
        if (depth > 0)
        {
                var result = GetFilesAndFolders(directory, depth-1);
                folders.AddRange(result.Item1);
                files.AddRange(result.Item2);
        }
    }

    files.AddRange(Directory.EnumerateFiles(root));

    return new Tuple<List<string>,List<string>>(folders, files);
}

A: I feel as though this has been solved before.  Basically what you want to do is ask the current File if it is a directory, if true and x has not maxed out yet grab that File's SubDirectories. Also, you need to check if there are files present in that directory and retrieve them as well.

A: if you just want the filenames you can do that with a recursive method. something like that:
(no garantee for total correctness, i write without compiler)
    public static List<String> GetSubfoldersAndFiles(DirectoryInfo di, int deep)
    {
       List<string> myContent = new List<string>();
       foreach(FileInfo fi in di.GetFiles())
       {
          myContent.Add(fi.FullName);
       }

       if(deep > 0)
       {
          foreach(DirectoryInfo subDi in di.GetDirectories())
          {
              myContent.AddRange(GetSubfoldersAndFiles(subDi, deep - 1).ToArray());
          }
       }

       return myContent;
    }

and the call would be like that:
List<string> content = GetSubfoldersAndFiles(new DirectoryInfo(@"c:\", 3));

A: All subfolders
public List<string> listDir(string pPath)
        {
            List<string> dirList = new List<string>();
            listDir(pPath, dirList);
            return dirList;
        }
private void listDir(string pPath, List<string> pList)
        {
                string[] loDirs = System.IO.Directory.GetDirectories(pPath);
                foreach (string loDir in loDirs)
                {
                    pList.Add(loDir);
                    listDir(loDir, pList);
                }
        }

A: Extending @pstrjds answer
private static IReadOnlyList<string> SearchFiles(string root, string pattern = "*", int depth = 1, params string[] exceptFolders)
{
    var files = Directory
        .EnumerateDirectories(root)
        .Where(it => !exceptFolders.Contains(Path.GetRelativePath(root, it)) && depth > 0)
        .SelectMany(it => SearchFiles(it, pattern, depth - 1, exceptFolders))
        .ToList();

    files.AddRange(Directory.EnumerateFiles(root, pattern));

    return files;
}


text:
Q: Why do I get UnauthorizedAccessException with some application pool identities if I'd like to use SPSiteCollection.Add in Sharepoint 2010? The background of this question is that my current task is to develope an application page which enables users to create site collections. The properties of the site collection are read from a list item. My solution works in most cases. However, there is one configuration of application pool identities where it throws an access denied and I'd like to understand why this is happening.
A (very) stripped-down version of my code looks like this:
SPSecurity.RunWithElevatedPrivileges(delegate { try
{
  SPWebApplication webApp = this.Web.Site.WebApplication;
  SPSiteCollection siteColl = webApp.Sites;

  SPSite newSite = siteColl.Add(mngPath + siteUrl, siteName, siteDesc, LocaleId,
                                null, primarySiteAdmin, String.Empty,
                                String.Empty));
});

The UnauthorizedAccessException is thrown when the Identities are set as following:

SharePoint Central Administration v4 --> localdomain\adminaccount
SharePoint - 80 --> NetworkService

All other combinations of NetworkService and domain\adminaccount do work. Dose someone have an explenation for that?
UPDATE
I guess that you have to run your sharepoint app pool using the same user as the central administration app pool in order to have sufficient rights on the DB. But that still does not explain why it works under the following configuration:

SharePoint Central Administration v4 --> NetworkService
SharePoint - 80 --> localdomain\adminaccount

BTW, another question on SA provides a solution (and some more details of the problem). See Permission to provision new site collection through workflow.

A: code under RunWithElevatedPrivileges is executed by using the credentials of th apppool account of the web application under which your code is being executed. best practice is to always use service domain accounts for application-pool. In your case one of account must be missing entry into some of the groups created by the sharepoint on your server or may not be having the proper rights on the database

A: Ok the problem were the DB access rights for the user running my application page's host web applications app pool. The Farm account (obviously) has db_owner rights on the AdminContent and _Config databases. Thats why it works when both application pools are run using the same user.
The reason why it also worked using the following configuration...

SharePoint Central Administration v4 --> NetworkService
SharePoint - 80 --> localdomain\adminaccount

... is that my local admin account also had db_owner rights. I have no idea why it has those rights, I never fiddled with DB access rights on my own. I only set it once to be the Farm account but I changed that soon after.

A: I'd look into the following
1) privileges for the elevated user to the target contedb
2) grant the elevated user (the application page's host web applications app pool account) rights as dbcreator if the script creates databases.


text:
Q: Expressing volume of bounded solid as iterated integral(s) I want to express $\iiint_E f(x,y,z) \ dV$ as an iterated integral.
The solid is bounded by the surfaces $y^2+z^2=9$, $x=-2$, $x=2$.
Looking at the projection on the plane x=0, the trace is a circle with radius 3 and center $(y,z)=(0,0)$. So $[(y,z)|-3\leq y\leq 3, -\sqrt{9-y^2} \leq z \leq \sqrt{9-y^2}]$
This would give the iterated integral:
$$\int_{-3}^{3}\int_{-\sqrt{9-y^2}}^{\sqrt{9-y^2}}\int_{-2}^{2} \ dx\ dz\ dy$$
In a similar way, I came up with the following variations of the integral:
$$\int_{-3}^{3}\int_{-\sqrt{9-z^2}}^{\sqrt{9-z^2}}\int_{-2}^{2} \ dx\ dy\ dz$$
$$\int_{-3}^{3}\int_{-2}^{2}\int_{-\sqrt{9-z^2}}^{\sqrt{9-z^2}} \ dy\ dx\ dz$$
$$\int_{-2}^{2}\int_{-3}^{3}\int_{-\sqrt{9-z^2}}^{\sqrt{9-z^2}} \ dy\ dz\ dx$$
$$\int_{-3}^{3}\int_{-2}^{2}\int_{-\sqrt{9-y^2}}^{\sqrt{9-y^2}} \ dz\ dx\ dy$$
$$\int_{-2}^{2}\int_{-3}^{3}\int_{-\sqrt{9-y^2}}^{\sqrt{9-y^2}} \ dz\ dy\ dx$$
Have I created the bounds on the integrals correctly, and are these all the ways to form the iterated integral?


text:
Q: SolutionDir no T4 Template Estou tentando carregar um assembly no template T4, porém ao tentar usar o $(SolutionDir) o meu assembly não carrega, só funciona se eu colocar o caminho completo.
Assim funciona
<#@ assembly name="d:\Projetos\Meus.Scaffold\bin\Debug\Meus.Scaffold.dll" #>

Assim não funciona
<#@ assembly name="$(SolutionDir)\bin\Debug\Meus.Scaffold.dll" #>

Sem que das duas formas o VS não acusa que não foi possível carregar o assembly, porém ao rodar o comando
Scaffold Triggers Teste Teste -force

Tenho o erro
Add-ProjectItemViaTemplate : d:\Projetos\Projeto.Web\CodeTemplates\Scaffolders\Trigger\ConexaoTriggerDelete.cs.t4(3,11) : error CS0246: Compiling
transformation: The type or namespace name 'Meus' could not be found (are you missing a using directive or an assembly reference?)
At d:\Projetos\Projeto.Web\CodeTemplates\Scaffolders\Trigger\Trigger.ps1:15 char:1
+ Add-ProjectItemViaTemplate $outputPath -Template $Template `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Add-ProjectItemViaTemplate], Exception
    + FullyQualifiedErrorId : T4Scaffolding.Cmdlets.AddProjectItemViaTemplateCmdlet


text:
Q: Threadpool size to number of cores available Will changing the thread pool size to the number of CPU cores available automatically make NodeJS multithreaded processes (crypto, fs, etc) run faster? If yes, how do I make it do so automatically?
 process.env.UV_THREADPOOL_SIZE=require('os').cpus().length;

Will this work on any kind of server?
I don't see why thread pool size is not already automatically set to the number of cores?


text:
Q: Vertical (mouse) scroll on  with overflow-x: scroll I've created a simple post container that allows to scroll trough several card components. However, as the majority of the users are not able to scroll horizontal (with a regular mouse), i need to change the scroll behavior from left -> right to top -> bottom, while the regular overflow-x: scroll is executed. Is there a simple way to implement this without usage of jquery?
My code:
  .main {
  ...
  height: 100vh;
  max-width: 100vw;
  overflow-x: hidden;

  &__feed {
    position: relative;
    height: 70vh;
    width: 100%;
    overflow-x: hidden;
    overflow-y: hidden;

    &__view {
      display: block;
      position: relative;
      height: 100%;
      overflow-x: scroll;

      &__items {
        position: absolute;
        display: flex;
        align-items: flex-start;
        left: 0;
        width: auto;
        height: 100%;

        // CHILD ELEMENTS (CARDS)
        & > * {
          width: 18vw;
          margin-right: $spacing-xs;

          @include media(tab-port) {
            word-break: break-all;
            width: 21rem;
          }
        }
      }
    }
  }
}

JSX :

                    {posts && filter === undefined
                      ? posts.map((post) => (
                          <Card
                            title={post.title.rendered}
                            content={post.content.rendered}
                            category={post.categories[0]}
                          />
                        ))
                      : posts
                          .filter((post) => post.categories[0] === filter)
                          .map((post) => (
                            <Card
                              title={post.title.rendered}
                              content={post.content.rendered}
                              category={post.categories[0]}
                            />
                          ))}