text:
Q: get one record based upon catname I have this query, it joins two tables and give me results of all the data under one a condition CATID is

'videography'

SELECT
pm_categories_images.Image,
pm_categories_images.FileURL,
pm_categories.catname,
pm_categories.`status`,
pm_categories.sortorder,
pm_categories.parentID,
pm_categories_images.CatID
FROM
pm_categories
LEFT JOIN pm_categories_images ON pm_categories_images.CatID = pm_categories.catID
where pm_categories_images.CatID IN (select catid from pm_categories where
parentID = (select catID from pm_categories where catname = 'Videography'))

Now this videography has a results like this

http://prntscr.com/gpkuyl

now i want to get 1 record for every catname

A: Without a MCVE and actual requirements on which image you want from the images table and a better understanding of why you need a left join when your where clause makes it behave like an inner... and why the where clause is so complex... ...I'm really unsure what the question is after... Here's a shot... and a DEMO:http://rextester.com/CRBN50943
Sample data expected results always a plus: I made my own and several assumptions
I interperted the question as: I would like a list of the categories along with a image having the earliest alphabetic value for each category.
SELECT
CI.Image,
CI.FileURL,
C.catname,
C.`status`,
C.sortorder,
C.parentID,
CI.CatID
FROM pm_categories C
INNER JOIN pm_categories_images  CI
  ON CI.CatID = C.catID
INNER JOIN (SELECT Min(Image) MI, catID FROM pm_categories_images group by CATID) Z
 on CI.Image = Z.MI
 and CI.CatID = Z.CatId
##WHERE C.catname = 'Videography'
Order by sortOrder

Giving us
+----+------------+-----------------------------------------------+-------------+--------+-----------+----------+-------+
|    |   Image    |                    FileURL                    |   catname   | status | sortorder | parentID | CatID |
+----+------------+-----------------------------------------------+-------------+--------+-----------+----------+-------+
|  1 | guid1.jpg  | https://drive.google.com/BusinessID/Postings/ | Real Estate |      1 |         1 | NULL     |     1 |
|  2 | guid4.jpg  | https://drive.google.com/BusinessID/Postings/ | commercial  |      1 |         2 | NULL     |     2 |
|  3 | guid6.jpg  | https://drive.google.com/BusinessID/Postings/ | Videography |      1 |         3 | NULL     |     3 |
|  4 | guid10.jpg | https://drive.google.com/BusinessID/Postings/ | Other       |      1 |         4 | NULL     |     4 |
|  5 | guid11.jpg | https://drive.google.com/BusinessID/Postings/ | LackingMCVE |      1 |         5 | NULL     |     5 |
+----+------------+-----------------------------------------------+-------------+--------+-----------+----------+-------+


text:
Q: How to simply add album covers to an iTunes playlist? I would like to create a Playlist folder into which I could put album covers, without showing all the cuts within, since I play a classical recording as an individual entity. This would simplify finding an album without having to wade through all of the movements within a recording.

A: Create your playlist, then select View As > Albums.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get Lubuntu 22.04 to display startup or boot messages I recently installed Lubuntu 22.04 on my HP laptop and today I decided to remove the Plymouth splash screen permanently and view the "old school" boot messages instead. At first, I tried to do this by removing "quiet" and "splash" next to the "GRUB_CMDLINE_LINUX_DEFAULT" entry in GRUB. That didn't remove the splash screen, so I decided to remove Plymouth altogether using Synaptic and some instructions I found on a website. While that successfully removed the splash screen, the boot messages do not show at all when the system is starting up, nor does pressing the "Esc" key make them appear. I've tried three or four different solutions, including uncommenting "GFXMODE" and changing the parameter to "text," but to no avail. Does anyone know of a way I get the boot messages to appear reliably each time I start the OS? :-)
In case it helps, here is one of the pages where I sought information t resolve this problem...
How to enable boot messages to be printed on screen during boot up?
Thank you for your time and any help you can offer! :-)
Regards...

A: Let me preface this by saying you may need to completely uninstall "plymouth" and all plymouth related packages, including the configuration files located in the "/usr/share/plymouth" directory, for this to work. However, please be warned, even though I didn't experience any problems myself, this may have unintended consequences and create errors and other problems in your operating system, including a failure to boot, from what I've heard. Just try just editing the GRUB file in "etc" first and see if that works for you. :-)
Per guiverc's suggestion, I decided to post what I did to resolve the issue in case it helps anyone else. After reading sudodus's and guiverc's questions and suggestions, I did the following...

*

*I brought up the file manager "pcmanfm-qt" and went to the location "/etc/default/grub" to see if I could find the GRUB file I didn't see in my initial search. Praise God I did this time! :-)

*I brought up a terminal or command line window (QTerminal) and used the "gksudo pcmanfm-qt" command to bring up a file manager in root, where I was able to access and open the GRUB file (using gedit) in "/etc/default/grub" and modify the "GRUB_CMDLINE_LINUX_DEFAULT" line to look like this...
GRUB_CMDLINE_LINUX_DEFAULT=""
PLEASE NOTE: The "gksu" package has been deprecated and has not been offered in the repositories since 16.04, I believe. Therefore, unless you install the necessary packages manually, you will not be able to use the command I used above. Now, one way to open a file manager in root is to use the "pkexec" command, or specifically pkexec pcmanfm-qt (in the case of Lubuntu.) However, I ran into errors trying to use "pkexec" that I didn't know how to resolve, so I just installed "gksu," a program that I'm used to and like better. There are probably ways to accomplish the same task using the terminal but I'm not well versed enough with the CLI to offer suggestions using that method. Please see the following pages linked to below for more information...
https://itsfoss.com/gksu-replacement-ubuntu/
How to configure pkexec?

*I then saved the changes, closed all the windows I had opened and then opened up a new terminal window and ran the command sudo update-grub and waited for the program to complete its work. I then closed the window and rebooted the system.

*Voila! Problem solved, praise be to God! I now have lots and lots of boot messages! :-D
Thank you to everyone on Ask Ubuntu who has posted answers to help others resolve their Ubuntu (or Ubuntu flavor) related issues! Your help is very much a blessing! :-)
Regards...


text:
Q: How to perform element-wise matrix multiplication on cuda using opencv GpuMat? As title says i need to perform element-wise matrix multiplication on cuda using GpuMat. My desired outcome is one that
cv::Mat mul() function gives for non-gpu Mats. I can use build-in function as well as i can write kernell for that operation, but i need little help as i am new to cuda.
I allready tried to write kernells to perform that but with no success so far. Also i tried to use mulSpectrums which is available for GpuMats but that function requires matrix to be type CV_32FC2 but i need my matrix to be CV_32F. IF there is literally no way to perform that operation on matrix which is not CV_32FC2, then you can show me efficient way to change matrix type from CV_32F to CV_32FC2 and back to CV_32F.
If anyone has time and will, i would love additional explanation how to perform operations on GpuMat matrices inside CUDA's kernell.
I need that to speed up my SSIM algorithm to lowest possible value as 0.01 sec is way to much for me atm.
But any type of help to perform that mul operation on GpuMat CV_32F inside cuda will be great.

A: An element wise multiplication can be performed with cv::cuda::multiply.
https://docs.opencv.org/master/d8/d34/group__cudaarithm__elem.html
You can also study the NPP libraries:
https://docs.nvidia.com/cuda/npp/group__image__mul.html


text:
Q: Debugging Multi-Processing in Python I am implementing a multiprocessing code for my python script. The way I am utilizing the multiprocessing module is as follows: -
 with get_context("spawn").Pool() as p:
                print('#########Starting Multiprocessing#########')
                n_core = multiprocessing.cpu_count() if settings['ncore'] <= 0 else settings['ncore']
                print('This is number of cores: ', n_core)
                subteams = np.array_split(list(teams.values()), n_core)
                func = partial(Team.bucketing, settings['bucket_size'], indexes['s2i'], indexes['c2i'], indexes['l2i'])
                data = p.map(func, subteams)

I have tried running the job on different memory sizes - 85GB, 95GB, 120GB and 185GB. But everytime the job is getting stuck at one of the threads: -
Loading 29000/722593 instances by <SpawnProcess name='SpawnPoolWorker-4' parent=144941 started daemon>! 24144.20463013649
Loading 29500/722593 instances by <SpawnProcess name='SpawnPoolWorker-4' parent=144941 started daemon>! 24555.586552858353
Loading 30000/722593 instances by <SpawnProcess name='SpawnPoolWorker-4' parent=144941 started daemon>! 24960.114577770233
Loading 30500/722593 instances by <SpawnProcess name='SpawnPoolWorker-4' parent=144941 started daemon>! 25363.86053919792
Loading 31000/722593 instances by <SpawnProcess name='SpawnPoolWorker-4' parent=144941 started daemon>! 25775.94654607773
Loading 31500/722593 instances by <SpawnProcess name='SpawnPoolWorker-4' parent=144941 started daemon>! 26186.659839630127
Loading 32000/722593 instances by <SpawnProcess name='SpawnPoolWorker-4' parent=144941 started daemon>! 26599.891565561295
Loading 32500/722593 instances by <SpawnProcess name='SpawnPoolWorker-4' parent=144941 started daemon>! 27014.309255361557
Loading 33000/722593 instances by <SpawnProcess name='SpawnPoolWorker-4' parent=144941 started daemon>! 27420.721549749374

Could anyone please suggest how I should debug or figure out what is causing this issue? Should I just try with an even greater memory or is there any other way to resolve it?
Any help would be greatly appreciated. Please let me know if there is anymore information that I can provide which might help you understand the issue.
Thanks.


text:
Q: How to determine if array items are references to other arrays (multidimensional arrays) How can I determine whether an array item is a reference to another array or another typed item like Single for instance.
I'm looking into this because I would like to make a uniform code that will iterate through all items of a dynamic multidimensional arrays regardless of the number of dimensions that array have.
And I need this in order to determine if I need to recursively iterate through array that represents inner dimension or whether I'm already at innermost dimension.
I assume I might need to rely in RTTI but I must admit I have no experience with RTTI so far.

A: I have found solution for this but it is only available in later versions of Delphi (tested on Delphi 10 Seattle and Delphi 10.1 Berlin) and it relies on undocumented function GetTypeKind that I stumbled upon.
if GetTypeKind(SomeVariable) = tkArray then //Returns true if variable references to static array

if GetTypeKind(SomeVariable) = tkDynArray then //Returns true if variable references to dynamic array

It can be even used for checking the items type of inner arrays
var Dyn2DArray: Array of Array of Integer;

if GetTypeKind(Dyn2DArray[0]) = tkDynArray then //Returns true since item of outmost array is references to inner array

if GetTypeKind(Dyn2DArray[0,0]) = tkDynArray then //Returns false since inner array item is of integer type


text:
Q: How to parse the description part in a CSV file and read only from column headers in Python Hi I have a dataframe which is a csv file, the first few rows consists of description or meta data. How to parse the file from the data and not the description.
How can i read the file and parse it?

This is general description of studies
A        B              C      D
Pharma   Retail         IoT   Supply Chain
Medical  Manufacturing  CV    Health
Here between the description and the data starting, there are 3 rows gap. Likewise it might vary, dynamically how can i parse only the data

A: Use the skiprows argument to skip your metadata.


text:
Q: Will an old Pentium 4-based server run Windows Server 2008 R2? I have a Dell PowerEdge 400sc with 4GB DDR 400, Pentium 4 3.2GHz.
It's an old server I would like to re-purpose as a domain controller/web server/file server for home intranet - mostly as a learning tool.
Would it run Windows Server 2008 R2 (which is 64-bit only)?
Thanks!

A: The 400SC came with 32 and 64 bit processors.  If you have a 64 bit processor, your machine is more that capable of running Server 2008 R2.  Check out Microsoft's requirements for server 2008.


text:
Q: Como renombrar un Label o un textbox dentro de un bucle? Como cambiar nombre de Label o TextBox en un blucle? Para alimentar datos de celdas consecutivas
Con mi código no reconoce Label Nom1.caption ni la celda B1
for i = 1 to 25

  "Nom"&i.caption = worksheets("hoja1").range("B&i").value

Next i


text:
Q: react-dropzone preview property missing Tried almost everything but, couldn't get it working? Can anyone point out what I'm missing? Also, I looked at other stack overflow post nothing seem to be working for me.
Don't know why the file.preview is missing but it seems to work well for others. Is it because of the component model is used? Should I go with functional component?
constructor() {
 super();
  this.onDrop = (files) => {
    console.log(files)
    this.setState({ files })
  };
  this.state = {
    files: []
  };
}

renderPreviewImg(files) {
  console.log(files)
  const img = {
    display: 'block',
    width: 'auto',
    height: '100%'
  };

  const thumb = {
    display: 'inline-flex',
    borderRadius: 2,
    border: '1px solid #eaeaea',
    marginBottom: 8,
    marginRight: 8,
    width: 100,
    height: 100,
    padding: 4,
    boxSizing: 'border-box'
  };

  const thumbInner = {
    display: 'flex',
    minWidth: 0,
    overflow: 'hidden'
  };

  const thumbs = files.map(file => (

  ));
  return thumbs;
}

<Dropzone
  onDrop={this.onDrop}
>
  {({ getRootProps, getInputProps }) => (

        <input {...getInputProps()} />

Drag 'n' drop some files here, or click to select files

        {this.renderPreviewImg(this.state.files)}

  )}
</Dropzone>

A: You can use this method

If you have more than one file then loop through files and return above statement for each file.
<Dropzone
  onDrop={this.onDrop}
>
  {({ getRootProps, getInputProps }) => (

        <input {...getInputProps()} />

Drag 'n' drop some files here, or click to select files

        {this.state.files.map(file=>{
        return
        })}

  )}
</Dropzone>


text:
Q: java.lang.CharSequence as a member of a Java class is not type-checked as expected The following code is rejected by the Kotlin compiler (rightfully so):
// main.kt
class KotlinFoo(val bar: java.lang.CharSequence)

fun test(foo: KotlinFoo) {
    println(foo.bar == "hi")
}

Error:
Operator '==' cannot be applied to 'CharSequence' and 'String'

The following, however, is accepted without complaints:
// JavaFoo.java
public class JavaFoo {
    public java.lang.CharSequence bar;
}

// main2.kt
fun test(foo: JavaFoo) {
    println(foo.bar == "hi")
}

I would have expected it to generate the same error.
Is this compiler behavior intended?

A: That's because kotlin.String "hi" is guaranteed to be not java.lang.CharSequence but kotlin.CharSequence. These classes have different subtyping hierarchies.
So, you should use kotlin.CharSequence in all cases, because on JVM it is mapped to java.lang.CharSequence by the ecompiler anyway.
However, there is a hack if you really want to use Java types in Kotlin—you can cast Kotlin's char sequences to Java ones:
    val s: java.lang.CharSequence = "42" as java.lang.CharSequence
    println(s == "42" as java.lang.CharSequence)


text:
Q: How to set the layout_width = screen_width ? And how to manage good size for image compared to the device? I already read a lot of threads on stackOverflow but I didn't find what I was searching for. I already read too the official documentation but I steel have some questions.
I'm trying to insert some image in my application and I'm trying to make the layout_width to the image equals to the width screen size (in portrait).
So I make many different size for the same image and I put them in
drawable-ldpi, drawable-hdpi ....
But when I'm trying my image on the emulator (hdpi) it works fine, but when I'm trying this on my tablet (hdpi too) the image don't get all the width screen.
I would like to know if I have to do multiple drawable about the screen size ?
and so then what about the drawable about the dpi ?
I know it's possible to put some vector image but I would like to know if I can choose the layout_width like this: android:layout_width = screen width.
and why is it so important to set the density ? A big tablet can be in mdpi et a phone on hdpi... what is so important in the density ?

A: Try using android:layout_width = "match_parent" in your layout.xml this will set the width of your main layout or parent layout to stretch from one side of screen to other side of screen. setting android:layout_height = "match_parent" and android:layout_width = "match_parent" will spread the layout over whole screen (top to bottom and left to right).
AND TO SAVE TIME AND EFFORT of creating different sizes of same image and icons,
you can use Android-drawable-importer plugin. With this plugin, import just 1 image and it will create different sizes (small,large,xlarge,xxlarge etc) automatically by it self.

A: Thank's for answer. I'll try to use this extension and see.
Edit:
It works fine but it make different image size only for the resolution (hdpi,mdpi ...) but it can't make different image size for the screen size ? Maybe I didn't see where I have to go ...
Do you know what I have to do ?
And I have a new questions: What is the vector image extension I must use in my projects ? I have .EPS and .AI but the plug in don't see theme in the search folder window. Do you know what is the step who can resolve it ?


text:
Q: Program will not compare the real answer to the players answer When I run the program, I will put in the correct answer but it will always mark it as wrong:

(10, '+', 2)
  12
  ...
  Wrong answer, the answer was 12 !

Here is the section of code which is wrong:
Player_answer = input()
print ("...")
time.sleep (0.5)

if operation==("+"): #check answer
    answer = num1+num2  #This works out the real answer

    if Player_answer == answer:  #This works out if the player is correct
        print("That's the correct answer")
        score = score + 1
    else:
        print("Wrong answer, the answer was",answer,"!")

if operation==("*"):
    answer = num1*num2

    if Player_answer == answer:
        print("That's the correct answer")
        score = score + 1
    else:
        print("Wrong answer, the answer was",answer,"!")

elif operation==("-"):
    answer = num1-num2

    if Player_answer == answer:
        print("That's the correct answer")
        score = score + 1
    else:
        print("Wrong answer, the answer was",answer,"!")

A: By default, input() returns a string. So, even if you type in 12, Player_input is "12" (a string). To make Player_input an integer, simply type Player_input = int(Player_input). The int() function takes any data value, and attempts to convert it to an integer. However, if it cannot convert, such as trying to convert "not num", it will raise a ValueError To prevent this, you can wrap it in a try/except statement.


text:
Q: Ajax loading of scripts (using jQuery) from CDN is't working In my Javascript heavy Web app, I have some scripts that are loaded in the source HTML with  tags, and others that I load as needed using jQuery's ajax method.
I am in the process of relocating most of my app's static assets to a CDN (I'm using AWS Cloudfront). My dynamic loads no longer work. The jQuery Ajax call:
$.ajax({
    url: url,
    dataType: 'script',
    async: true,
    success: function (content) {
        ....

triggers the success function, but the content is empty.
I'm wondering if this is because such a request violates the Browser's security model for cross-site scripting. If that's the case, is there to load scripts dynamically from a CDN?  Ahhh... I am NOT presently using a CNAME alias for the cloudfront host. Would doing so solve this problem?

A: You're right, it is the cross-site scripting security preventing this.
You're able to use the jQuery.getScript() method to load it from an external domain (or internal).


text:
Q: кнопки при клике на которые блок появляется Кнопки вакансий - при нажатии кнопки разворачивается блок с текстом вакансии, повторный клик сворачивает его обратно. На самой кнопке указано название вакансии. Как сделать? Помогите!!!

A: Для этой задачи подойдёт старый добрый спойлер.
Вот один из простых вариантов на jQuery

$(document).on('click', '.spoiler .button', function(){
  let parent = $(this).closest('.spoiler'),
      button = parent.find('.button'),
      content = parent.find('.content');
  if(content.css('display') === 'none') { // если контент скрыт
    content.fadeIn(); // покажем контент
    button.find('span').text('-'); // сменим "иконку" у кнопки
  } else { // если контент показан
    content.fadeOut(); // скроем контент
    button.find('span').text('+'); // сменим "иконку"
  }
});
.spoiler .button {
  cursor: pointer;
}

.spoiler .content {
  display: none;
}

Название вакансии +

    Описание вакансии


text:
Q: how to put an image to each button in use (for loop) in python I want to create a loop to create several buttons, and put a different image in each button.
but it shows that on the last button,
-noted: when I run in (debug) step by step, it works.
-it's been two days since I search on google
thank you in advance
    from tkinter import *

    win = Tk()
    win.geometry("800x600")
    win.title("hhh")

    ls = ['/home/decode/Images/ImageDB/tom.png', '/home/decode/Images  /ImageDB/aub.png','/home/decode/Images/ImageDB/res.png']
    z=0
    #g= ls[z]

    for i in range(3):
        g= ls[z]
        img = PhotoImage(file=g)
        btn = Button(win, image=img)
        btn.pack()
        z+=1

    win.*mainloop*()

enter image description here``
enter image description here

A: You want to use the PIL library and PhotoImage, for example:
from tkinter import *
from PIL import* Image,Tkimage

win = Tk()
win.geometry("800x600")
win.title("hhh")

photo_1=PhotoImage(file=r'D:/button.png')

photo_image=Button(win,image=photo_1)
photo_image.place(x=10,y=0,height=12,width=12)

win.mainloop()


text:
Q: Rank MySQL for multiple users I would need an help for a task I should implement.
I have a table, in which are included following fields:

*

*Username

*Score

*Competition

Each username can be present in the table several times, thus he can have several scores.
In any case, a username can be associated to only one country.
Here below an example of my table:
Username !! Country || Score
Bob       ! Italy   !   100
Bob       ! Italy   !   150
Christian ! Italy   !   500
Christian ! Italy   !   200
Fred      | Germany |  80
Carl      | Germany |  700
Charlie   | France  |   400
Charlie   | France  |  280
Jean      | France  |   90

What I would get is a MYSQL command to get the ranking of each user in his country, considering only his best score and discarding the others.
Therefore, my ideal output should look like:
Christian ranked #1 in Italy
Bob ranked #2 in Italy
Carl ranked #1 in Germany
Fred ranked #2 in Germany
Charlie ranked #1 in France
Jean ranked #2 in France
I can order the users and have their rank, but having all the entries.
What I would like to have is the ranking with just the best scores.
Any help is much appreciated,
Thanks a lot

A: You can do this with aggregation and window function rank(), if you are running MySQL 8.0
select
    username,
    country,
    max(score) top_score,
    rank() over(partition by country order by max(score) desc) country_rank
from mytable
group by username, country
order by country, country_rank

A: One way that this could be done is:
SELECT o1.Username, o1.Country, o1.maxScore,
    (SELECT COUNT(DISTINCT s2.Username)
     FROM `scores` s2
     WHERE o1.Country = s2.Country AND s2.Score > o1.maxScore) + 1 AS ranking
FROM (
     SELECT Username, Country, MAX(Score) AS maxScore
     FROM `scores` s1
     GROUP BY Username) o1

This works by:

*

*1st getting the max score for each Username seen at alias "o1" (MAX(Score) AS maxScore)

*2nd using the maxScore result found above and a subQuery "s2" to find the rank for each Username and Country

Since MAX(Score) AS maxScore is an aggregated result, we cannot use the subQuery directly in 1 query, but first we have to aggregate the results and use the resulted max scores.


text:
Q: How to clear cache (or force recompilation) in numba I have a fairly large codebase written in numba, and I have noticed that when the cache is enabled for a function calling another numba compiled function in another file, changes in the called function are not picked up when the called function is changed. The situation occurs when I have two files:
testfile2:
import numba

@numba.njit(cache=True)
def function1(x):
    return x * 10

testfile:
import numba
from tests import file1

@numba.njit(cache=True)
def function2(x, y):
    return y + file1.function1(x)

If in a jupyter notebook, I run the following:
# INSIDE JUPYTER NOTEBOOK
import sys
sys.path.insert(1, "path/to/files/")
from tests import testfile

testfile.function2(3, 4)
>>> 34   # good value

However, if I change then change testfile2 to the following:
import numba

@numba.njit(cache=True)
def function1(x):
    return x * 1

Then I restart the jupyter notebook kernel and rerun the notebook, I get the following
import sys
sys.path.insert(1, "path/to/files/")
from tests import testfile

testfile.function2(3, 4)
>>> 34   # bad value, should be 7

Importing both files into the notebook has no effect on the bad result. Also, setting cache=False only on function1 also has no effect. What does work is setting cache=False on all njit'ted functions, then restarting the kernel, then rerunning.
I believe that LLVM is probably inlining some of the called functions and then never checking them again.
I looked in the source and discovered there is a method that returns the cache object numba.caching.NullCache(), instantiated a cache object and ran the following:
cache = numba.caching.NullCache()
cache.flush()

Unfortunately that appears to have no effect.
Is there a numba environment setting, or another way I can manually clear all cached functions within a conda env? Or am I simply doing something wrong?
I am running numba 0.33 with Anaconda Python 3.6 on Mac OS X 10.12.3.

A: I "solved" this with a hack solution after seeing Josh's answer, by creating a utility in the project method to kill off the cache.
There is probably a better way, but this works. I'm leaving the question open in case someone has a less hacky way of doing this.
import os

def kill_files(folder):
    for the_file in os.listdir(folder):
        file_path = os.path.join(folder, the_file)
        try:
            if os.path.isfile(file_path):
                os.unlink(file_path)
        except Exception as e:
            print("failed on filepath: %s" % file_path)

def kill_numba_cache():

    root_folder = os.path.realpath(__file__ + "/../../")

    for root, dirnames, filenames in os.walk(root_folder):
        for dirname in dirnames:
            if dirname == "__pycache__":
                try:
                    kill_files(root + "/" + dirname)
                except Exception as e:
                    print("failed on %s", root)

A: This is a bit of a hack, but it's something I've used before. If you put this function in the top-level of where your numba functions are (for this example, in testfile), it should recompile everything:
import inspect
import sys

def recompile_nb_code():
    this_module = sys.modules[__name__]
    module_members = inspect.getmembers(this_module)

    for member_name, member in module_members:
        if hasattr(member, 'recompile') and hasattr(member, 'inspect_llvm'):
            member.recompile()

and then call it from your jupyter notebook when you want to force a recompile. The caveat is that it only works on files in the module where this function is located and their dependencies. There might be another way to generalize it.

A: The official document of Numba recommends to remove the cache directory for clearing the cache [link].
The Numba cache is saved in these four directories [link]:

*

*numba.config.CACHE_DIR

*__pycache__

*numba.misc.appdirs.user_cache_dir()

*IPython.paths.get_ipython_cache_dir()
It is possible to find the Numba cache by searching *.nbi files [link].

I personally use the following two codes. The former one is referenced from Python3 project remove __pycache__ folders and .pyc files.
import pathlib
import shutil

_ = [shutil.rmtree(p) for p in pathlib.Path('.').rglob('__pycache__')]

import IPython
import shutil

path_parent = IPython.paths.get_ipython_cache_dir()
path_child = os.path.join(path_parent, 'numba_cache')

if path_parent:
    if os.path.isdir(path_child):
        shutil.rmtree(path_child)


text:
Q: How to decode an NSString containing UTF8 symbol? I got an NSString, named aString, which contains UTF8 symbol:
NSLog(@"aString: %@", aString);

Console => aString: \U00e6\U00b8\U00ac\U00e8\U00a9\U00a6\U00e6\U00a8\U0099

How can I decode this NSString? I'v tried lots of method, but they didn't work.

A: Try [NSString stringWithUTF8String:yourstring]


text:
Q: i am not able to get 50 results records by google search api this is my code. which works fine for 10 records. but whe it will prompt error when i increase the number. please check it and let me know if you have any solutions.
    Thanks in advance,
    Ravi Sharma
    Softobiz Technologies
<?php

    # JSON SEARCH RESULT

    // This example request includes an optional API key which you will need to
    // remove or replace with your own key.
    // Read more about why it's useful to have an API key.
    // The request also includes the userip parameter which provides the end
    // user's IP address. Doing so will help distinguish this legitimate
    // server-side traffic from traffic which doesn't come from an end-user.

    $url = 'https://www.googleapis.com/customsearch/v1?key=AIzaSyC4o52-Q90FxNzMxY9FNryrONierFS3la8&cx=016278085151347603490%3Affuoqez1cew&q=ravi&num=20';
    // sendRequest
    // note how referer is set manually
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_REFERER, '202.164.43.51');
    $body = curl_exec($ch);
    curl_close($ch);

    // now, process the JSON string
    $array = json_decode($body);
    // now have some fun with the results...

    echo "<pre>";
    print_r($array);

    ?>

A: From http://code.google.com/apis/websearch/

Note: The Google Web Search API has been officially deprecated as of November 1, 2010. It will continue to work as per our deprecation policy, but the number of requests you may make per day will be limited. Therefore, we encourage you to move to the new Custom Search API.

From: http://code.google.com/apis/soapsearch/api_faq.html#tech8

8. Is there a limit on the number of results I can receive per query?
Yes. You can retrieve a maximum of 10 results per query, and you cannot access information beyond the 1000th result for any given query.

What you're encountering is the single request result limit.

A: Also from the docs:
Pagination
This API can return the first 100 search results, in chunks (pages) up to 10 search results long. You can specify the page of search results to return using the start and num query parameters.


text:
Q: How to fix my MBR? While installing random Ubuntu my MBR is not getting overwritten anymore I boot with liveUSB. But how do i fix now my MBR, so that i can re-install Ubuntu? (after installing ubuntu i get mostly this blinking cursor and black screen)
root@ubuntu:~# fdisk -l

Disk /dev/sda: 500.1 GB, 500107862016 bytes
255 heads, 63 sectors/track, 60801 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x000638ad

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1               1       59769   480092160   83  Linux
/dev/sda2           59769       60802     8291329    5  Extended
/dev/sda5           59769       60802     8291328   82  Linux swap / Solaris

Disk /dev/sdb: 2013 MB, 2013265920 bytes
58 heads, 58 sectors/track, 1168 cylinders
Units = cylinders of 3364 * 512 = 1722368 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x1965c912

   Device Boot      Start         End      Blocks   Id  System
/dev/sdb1   *           1        1169     1965056   83  Linux

root@ubuntu:~# fdisk /dev/sda

WARNING: DOS-compatible mode is deprecated. It's strongly recommended to
         switch off the mode (command 'c') and change display units to
         sectors (command 'u').

Command (m for help): p

Disk /dev/sda: 500.1 GB, 500107862016 bytes
255 heads, 63 sectors/track, 60801 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x000638ad

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1               1       59769   480092160   83  Linux
/dev/sda2           59769       60802     8291329    5  Extended
/dev/sda5           59769       60802     8291328   82  Linux swap / Solaris

Command (m for help):

A: For the simplest solution, try installing Ubuntu by letting installer configure partitions.
Set 1 partition to be boot able and install either "/" on it or "/boot" on it.

A: It looks like none of your partitions on /dev/sda have bootable flag set - compare the fdisk -l output with /dev/sdb - see the star in the Boot column next to /dev/sdb1? You need to set it on /dev/sda1
To set bootable flag, start fdisk with
fdisk /dev/sda

(from your LiveCD, as root). There, press "a" and then enter "1". then press "w" to write your changes to disk. Reboot. Enjoy.


text:
Q: Brainstorm: a pun on rainstorm? The Online Etymology Dictionary unsurprisingly says brainstorm is from the combination of brain and storm.
What I want to know is whether or not this neologism was an intentional pun on the word rainstorm and also whether or not, when people use brainstorm today, they think of it as a pun or an independent word from rainstorm.
I, for one, used brainstorm my entire life without thinking about rainstorm until last week when, as if in a thunderous mental flash, it suddenly occurred to me. Am I just late to make an obvious connection here? Or is this news to other people as well?

A: The answer appears to be that there is no evidence that brainstorm is a pun on rainstorm. As mentioned in the comments, it was originally used to denote 'a violent transient fit of insanity', and according to Webster, that remains its primary definition.
Elaborating on the transition to its present meaning, Ken Greenwald (Fort Collins, CO - U.S.A.) quotes from the book, America in So Many Words:

BRAINSTORM: Originally a brainstorm was a momentary malfunction of the
  mind, a 'cerebral disturbance,' in the words of an 1894 investigator.
  A bright idea was not yet 'a brainstorm' but a 'brain wave,' as far
  back as "Harper's" magazine of 1890: 'Lucilla, with what she was fond
  of terming a brain wave, comprehended the situation.' But by the 1920s
  'brain wave' was subsiding, while 'brainstorm' took over the meaning
  of 'a sudden surge of ingenuity.'
The first instance of this transferred sense, 'He had a brainstorm,'
  is recorded in the magazine 'College Humor' in early 1925. Many
  brainstorms took place after that, such as this one from 1941: 'Then I
  had the brainstorm of getting an English star like Howard to play the
  part,' and another from 1993: 'Then one of the guys working here had
  a brainstorm.'

As the OP has noted, Etymonline fails to provide any additional insight:

"brilliant idea, mental excitement, fit of mental application," 1849, from brain (n.) + figurative use of storm (n.). As a verb, recorded from 1920s.

It is, however, interesting to note a curious discrepancy in the OED in its native and American English definitions for brainstorming. The former defines it as:

*

*British informal a moment in which one is suddenly unable to think
  clearly or act sensibly: we can only assume that someone simply had a
  brainstorm and left the important bits out

*a spontaneous group discussion to produce ideas and ways of solving problems: the participants held a brainstorm

*

*[as modifier]: brainstorm exercises
North American informal a sudden clever idea: these three brainstorms
  may flop like other well-intentioned innovations

IOW, the primary and secondary definitions are more or less contradictory. The AE definition also lists both definitions, but in reverse order. Webster similarly lists these contradictory views:

2a : a sudden bright idea
2b : a harebrained idea

(with 1, of course, being about transient fits of insanity.)


text:
Q: Trajectory of a differential equation I am self-studying differential equations using MIT's public available materials, and came across this recitation question early on:
Suppose that a trajectory of $(3x^2 - y)dx + (3y^2- x)dy = 0$ contains the point $(1,1)$.  Show that it also contains the points $(1,-1)$, $(-1,1)$, $(0,1)$, and $(1,0)$.
I'm embarrassed to say that I do not see why this should be so.  Certainly we can write
\begin{align}
\frac{dy}{dx} & = \frac{y - 3x^2}{3y^2 - x}
\end{align}
to see that at $(1,1)$ we have $\frac{dy}{dx} = -1$, at $(1,-1)$ we have $\frac{dy}{dx} = -2$, at $(0,1)$ we have $\frac{dy}{dx} = \frac{1}{3}$, and at $(1,0)$ we have $\frac{dy}{dx} = 3$, but I do not understand how we can say anything about why these points must lie on the same trajectory.  (I also note that not only does it not make sense to write $y$ as a function of $x$ on any interval $x = 1$ (since $y(x)$ would have two distinct values at $x = 1$), but that it similarly does not make sense to write $x$ as a function of $y$ on any interval containing $y = 1$, for the same reason.  I'm not sure that this is relevant, however.)
I recognize that this is an elementary exercise, but I'm stuck nevertheless, and would appreciate a gentle push in the right direction.

A: As @Thomas points out, your differential equation can be written
$$
d\bigl(x^3+y^3-xy\bigr)=0.
$$
Thus, you are interested in the curves
$$
x^3+y^3-xy=C.
$$
Inserting the point $(x,y)=(1,1)$, we find that $C=1$. It is then easy to verify that the other points also satisfies $x^3+y^3-xy=1$. It remains to verify that the curve $x^3+y^3-xy=1$ is connected (so that we will arrive at all points). I attach a graph of the curve, together with the vector field and the interesting points marked.

A: By Poincar´e operators we mean the translation operator along the trajectories of the associated differential system and the first return (or section) map defined on the cross section of the torus by means of the flow generated by the vector field. The translation operator is sometimes also called as Poincar´e–Andronov or Levinson or, simply, T-operator.


text:
Q: Read a public static variable value from class file inside a war which is in shared folder I need a code that loads the .class file which is in a war(Archive) file located in a shared location and then get the static variable value in it.
Following is the code which I have tried which results in ClassNotFoundException when invoking the Class.ForName method.
String warPath = "jar:file://" + sharedDrivePath +"/AppUIWebApp.war!";
URL inputURL = new URL(warPath);
conn = (JarURLConnection) inputURL.openConnection();
URLClassLoader jarLevelClassLoader = new URLClassLoader(new URL[]{conn.getURL()});
Class.forName("Java.File.Name",Boolean.FALSE,
      jarLevelClassLoader).getDeclaredField("staticVariable").get(null));

Can anyone guide me on how to fix this issue. The same code worked for jar file which is also in shared drive.


text:
Q: Having trouble getting CSS files to work in CodeSandbox I'm having trouble getting CSS to work / be included in the codesandboxes I create. My aim is to simply create a sandbox that includes a few different CSS and JavaScript files, and have these files work with the HTML tags in the index.html file.
I found a sandbox online with working CSS, but the way it was including CSS seemed similar to what I was doing. I decided to slowly change my sandbox into their sandbox to see if I could spot the difference, but after completely changing my sandbox into their sandbox, I was left with one sandbox with working CSS and one with CSS that doesn't work - yet these sandboxes look identical to me.
CSS doesn't work: (except for the inline CSS)
https://codesandbox.io/s/happy-rubin-cytfo?file=/index.html
CSS does work:
https://codesandbox.io/s/01-3-ways-to-add-css-forked-9dwq5?file=/index.html
Can someone help me understand why CSS works in one and not the other?

A: I've figured it out. In the "Sandbox Info" section, the "Environment" is different between the two sandboxes. One is "parcel" and one is "create-react-app". create-react-app uses webpack, and bundles files differently than parcel, which is why the CSS works in one and not the other. In the create-react-app version, it doesn't know to bundle the CSS.


text:
Q: Training tensorflow network to check if two numbers are same doesn't work? I'm new to python and tensorflow (and machine learning) and this is my first program. Once trained, it should accept two numbers and return [1, 0] if they're unequal and [0, 1] if they're equal.
I've modified the beginner tensorflow tutorial at https://www.tensorflow.org/get_started/mnist/beginners (which looks for numbers in an image array) to this purpose. I train it on 1000000 pairs with both equal and unequal pairs with the numbers in [0, 100] range.
Problems - Training brings up the accuracy to 0.5 but no higher. Instead of returning [0, 1] or [1, 0], it returns [x, -x] (where x is a floating point number). I'm not sure if the problem lies in the python code or tensorflow usage but I suspect it is a silly beginner's mistake. What am I doing wrong?
Below is my code -
sess = tf.InteractiveSession()
x = tf.placeholder(tf.float32, shape=[None, 2])
y_ = tf.placeholder(tf.float32, shape=[None, 2])
W = tf.Variable(tf.zeros([2,2]))
b = tf.Variable(tf.zeros([2]))
sess.run(tf.global_variables_initializer())
y = tf.matmul(x,W) + b
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
train_step = tf.train.GradientDescentOptimizer(0.2).minimize(cross_entropy)(0.2).minimize(cross_entropy)#
xinput = [[1, 2], [4, 4]]
yinput = [[1, 0], [0, 1]]
for _ in range(0, 1000000): #Generates more random training data with a mix of equal and unequal pairs
        temp = random.randint(0, 2)
        if(temp == 0):
            t1 = random.randint(0, 100)
            xinput.append([t1, t1])
            yinput.append([0, 1])
        else:
            t1 = random.randint(0, 100)
            t2 = random.randint(0, 100)
            if(t1 != t2):
                xinput.append([t1, t2])
                yinput.append([1, 0])
train_step.run(feed_dict={x: xinput, y_: yinput})

Then I test it with some test data -
xeval = [[1, 1], [2, 3], [5, 5], [34, 6]]
yeval = [[0, 1], [1, 0], [0, 1], [1, 0]]
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(sess.run(accuracy, feed_dict={x: xeval, y_: yeval}))

Which always prints 0.5.
Here are the outputs of more variables -
print(y.eval(feed_dict={x: xeval, y_: yeval}))
Output - [[-0.0584463   0.0584463 ][-0.14445792  0.14445792][-0.289756    0.289756 ][-1.17759383  1.17759383]]

print(tf.argmax(y,1).eval(feed_dict={x: xeval, y_: yeval}))
Output - [1 1 1 1]

for var in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES):
    print('{0} - {1}'.format(var.name, sess.run(var)))
Output - Variable:0 - [[-0.02964323  0.02964323] [-0.0281842   0.0281842 ]]
Variable_1:0 - [-0.00061888  0.00061888]


text:
Q: Can we inherit a custom variable defined in a class in another class? I've been going through the basic CSS tutorials and I had a small confusion. I would appreciate any help with this. Below are two examples to demonstrate what is causing the confusion

Scenario 1: Inheriting a variable from :root

:root {
  --red-color: red;
}
.red-box {
  background: red;
  background: var(--red-color);
  height: 200px;
  width:200px;
}

Scenario 2: Inheriting a variable from another class. [I HAVE CONFUSION WITH THIS CASE]

.penguin {

  /* change code below */
  --penguin-skin: gray;
  --penguin-belly: white;
  --penguin-beak: orange;
  /* change code above */

  position: relative;
  margin: auto;
  display: block;
  margin-top: 5%;
  width: 300px;
  height: 300px;
}

.penguin-top {
  top: 10%;
  left: 25%;
  background: var(--penguin-skin, gray);
  width: 50%;
  height: 45%;
  border-radius: 70% 70% 60% 60%;
}

.penguin-bottom {
  top: 40%;
  left: 23.5%;
  background: var(--penguin-skin, gray);
  width: 53%;
  height: 45%;
  border-radius: 70% 70% 100% 100%;
}

.right-hand {
  top: 0%;
  left: -5%;
  background: var(--penguin-skin, gray);
  width: 30%;
  height: 60%;
  border-radius: 30% 30% 120% 30%;
  transform: rotate(45deg);
  z-index: -1;
}

.left-hand {
  top: 0%;
  left: 75%;
  background: var(--penguin-skin, gray);
  width: 30%;
  height: 60%;
  border-radius: 30% 30% 30% 120%;
  transform: rotate(-45deg);
  z-index: -1;
}

.right-cheek {
  top: 15%;
  left: 35%;
  background: var(--penguin-belly, white);
  width: 60%;
  height: 70%;
  border-radius: 70% 70% 60% 60%;
}

.left-cheek {
  top: 15%;
  left: 5%;
  background: var(--penguin-belly, white);
  width: 60%;
  height: 70%;
  border-radius: 70% 70% 60% 60%;
}

.belly {
  top: 60%;
  left: 2.5%;
  background: var(--penguin-belly, white);
  width: 95%;
  height: 100%;
  border-radius: 120% 120% 100% 100%;
}

.right-feet {
  top: 85%;
  left: 60%;
  background: var(--penguin-beak, orange);
  width: 15%;
  height: 30%;
  border-radius: 50% 50% 50% 50%;
  transform: rotate(-80deg);
  z-index: -2222;
}

.left-feet {
  top: 85%;
  left: 25%;
  background: var(--penguin-beak, orange);
  width: 15%;
  height: 30%;
  border-radius: 50% 50% 50% 50%;
  transform: rotate(80deg);
  z-index: -2222;
}

.right-eye {
  top: 45%;
  left: 60%;
  background: black;
  width: 15%;
  height: 17%;
  border-radius: 50%;
}

.left-eye {
  top: 45%;
  left: 25%;
  background: black;
  width: 15%;
  height: 17%;
  border-radius: 50%;
}

.sparkle {
  top: 25%;
  left: 15%;
  background: white;
  width: 35%;
  height: 35%;
  border-radius: 50%;
}

.blush-right {
  top: 65%;
  left: 15%;
  background: pink;
  width: 15%;
  height: 10%;
  border-radius: 50%;
}

.blush-left {
  top: 65%;
  left: 70%;
  background: pink;
  width: 15%;
  height: 10%;
  border-radius: 50%;
}

.beak-top {
  top: 60%;
  left: 40%;
  background: var(--penguin-beak, orange);
  width: 20%;
  height: 10%;
  border-radius: 50%;
}

.beak-bottom {
  top: 65%;
  left: 42%;
  background: var(--penguin-beak, orange);
  width: 16%;
  height: 10%;
  border-radius: 50%;
}

body {
  background:#c6faf1;
}

.penguin * {
  position: absolute;
}

My Question:
I have clearly seen the tutorials mentioning that we can make use of variables from :root in other classes, but as per the example in Scenario 2 I am not able to understand how is the variable inherited from one class to another? I am asking this since I have not seen this mentioned specifically and I just want to be sure about my knowledge.
Thanks for your help in advance :)

A: From the specification:

Custom properties are ordinary properties, so they can be declared on any element, are resolved with the normal inheritance and cascade rules, can be made conditional with @media and other conditional rules, can be used in HTML's style attribute, can be read or set using the CSSOM, etc.

And also:

Inherited: yes

So it's not about the inheritance from another class but the usual inheritance from a parent (or ancestor) element exactly like any inherited property.
In your case penguin-top is a child of penguin so it will inherit its custom properties.

Worth to note that :root is the html element which is the ancestor of all the elements that's why all them will logically inherit custom property defined inside :root


text:
Q: How to handle sql injection from asp.net What is the best way from asp.net to avoid sql injections but at the same time I want to set my user free to enter any special symbol.
Edit
I am not using any parametrised query, I am using enterprise library and stored procedure

A: Parameterized queries. Use them wherever you have a query at all, and your user can enter in any symbol they particularly feel like.
If you're using an ORM, this is pretty much handled for you, but if you aren't, then what you need to do is something like this:
comm.CommandText = "insert into MyTable (col1, col2) values (@col1, @col2)";
comm.Parameters.AddWithValue("@col1", 123);
comm.Parameters.AddWithValue("@col2", "; drop table whatever; --");
comm.ExecuteNonQuery();

That query is 100% safe to run ad nauseum. Let .NET just handle the parameters for you, and you'll be all set.
Also, make sure you're using nvarchar (Unicode) columns, rather than varchar, if your users are going to be inserting symbols outside of the ANSI character set.

A: Use the SqlCommand.Prepare Method as mentioned on bobby-tables.
private static void SqlCommandPrepareEx(string connectionString)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        SqlCommand command = new SqlCommand(null, connection);

        // Create and prepare an SQL statement.
        command.CommandText =
            "INSERT INTO Region (RegionID, RegionDescription) " +
            "VALUES (@id, @desc)";
        SqlParameter idParam = new SqlParameter("@id", SqlDbType.Int, 0);
        SqlParameter descParam =
            new SqlParameter("@desc", SqlDbType.Text, 100);
        idParam.Value = 20;
        descParam.Value = "First Region";
        command.Parameters.Add(idParam);
        command.Parameters.Add(descParam);

        // Call Prepare after setting the Commandtext and Parameters.
        command.Prepare();
        command.ExecuteNonQuery();

        // Change parameter values and call ExecuteNonQuery.
        command.Parameters[0].Value = 21;
        command.Parameters[1].Value = "Second Region";
        command.ExecuteNonQuery();
    }
}


text:
Q: SFML:Реализация перигелия и афелия Планета движется по закону:
x=Sun.x+radius.x*cos(time*speed);
y=Sun.y+radius.y*sin(time*speed);

Как реализовать ускорения при приближении до планеты и уменьшении скорости при отдалении?
Спасибо!

A: Решите численно уравнение Кеплера
2*Pi * t / T = E - e * sin(E)

где T - период, e - эксцентриситет
Т.е. в каждый период времени t нужно найти величину E (эксцентрическую аномалию), а из неё уже истинную аномалию v, что и даст положение планеты.
v = 2 * atan (tan(E/2) * Sqrt((1+e)/(1-e)))

Простая имитация разной скорости (с Солнцем в центре, а не в фокусе, как у автора) с использованием такого (Delphi) кода - приращение угла зависит от самого угла.
 cf := 1.0 / (2 + Cos(2 * an));
 an := an + speed * cf;
 x := cx + Round(rx * Cos(an));
 y := cy + Round(ry * Sin(an));
 Canvas.Brush.Color := clBlue;
 Canvas.Ellipse(x - 10, y - 10, x + 11, y + 11);


text:
Q: Can't get fractal image to work So I'm working on a homework assignment regarding using image objects in python. I'm using python 3.4.1 for this assignment. I feel like I have everything done, but it doesn't want to work correctly. Basically, I'm trying to get it to look like the picture that I've attached, but it only shows as 1 red line across, and 1 red line top to bottom on a white background.
Any help would be much appreciated.
The attached image:
http://imgur.com/TMho41w
import cImage as image

width = 500
height = 500

img = image.EmptyImage(width, height)
win = image.ImageWin("Exercise 3", width, height)
img.draw(win)

for row in range(height):
    for col in range(width):
        p = img.getPixel(col, row)

        if row == 0 or col == 0:
            p = image.Pixel(255, 0, 0)
        else:
            Sum = 0
            temppixel = img.getPixel(col-1, row)
            if temppixel.getRed() == 255:
                Sum = Sum + 1
            elif temppixel.getBlue() == 255:
                Sum = Sum + 2

            temppixel = img.getPixel(col-1, row-1)
            if temppixel.getRed() == 255:
                Sum = Sum + 1
            elif temppixel.getBlue() == 255:
                Sum = Sum + 2

            temppixel = img.getPixel(col, row-1)
            if temppixel.getRed() == 255:
                Sum = Sum + 1
            elif temppixel.getBlue() == 255:
                Sum = Sum + 2

            if Sum % 3 == 1:
                p = image.Pixel(255, 0, 0)
            elif Sum % 3 == 2:
                p = image.Pixel(0, 0, 255)
            else:
                p = image.Pixel(255, 255, 255)

        img.setPixel(col, row, p)

    img.draw(win)

img.draw(win)

# uncomment this to save the image as a file
#img.saveTk("gradient.gif")

win.exitonclick()

A: Unfortunately, your code does exactly what you have written it to do. Let's name the three first if ... elif condition1, 2 and 3 :

*

*The first pixel is set to red

*Then we progress through the first line, so row = 0 which means condition 2 and 3 are using invalid coordinates (because of row-1). So there's only condition at play here, and it will always increment by 1 sum which means it'll add a new red pixel.

*So you have now your first red line.

*For the first column, starting from the second line : conditions 1 & 2 are using invalid coordinates. Condition 3 will always return sum = 1 which means a new red pixel. And you have your red line from top to bottom

*And then from row = 1 and col = 1, all neighbors are red, which leads to a new white pixel. Unfortunately, white does contain some red, so it'll always be the sames conditions that are met, and you have your white background.

I haven't been able to find the complete algorithm for this method to build a Sierpinski carpet, so I can't really correct it. But you should be extra careful with these edges situations : what should be the three neighbors if you are on the first line or first row ?


text:
Q: Replace matching word with a digit/number in a string in PHP I want to replace some words in a string with a digit/number only if that word is followed or preceded by a digit [whitespace(s) allowed in between]. For example, here is an example string in which I wish to replace too with 2 and for with 4. I have tried with str_replace, but doesn't serve the full purpose as it replaces all for and too in the string
$str = 'Please wait for sometime too, the area code is for 18 and phone number is too 5897 for';
$str = str_ireplace(' for ', '4', $str);
$str = str_ireplace(' too ', '2', $str);
echo $str;

but it isn't giving me the desired output which should be
Please wait for sometime too, the area code is 418 and phone number is 258974

A: This may be a little too long, but you get the idea:
http://3v4l.org/JfXBN
<?php
$str="Please wait for sometime too, the area code is for 18 and phone number is too 5897 for";
$str=preg_replace('#(\d)\s*for#','${1}4',$str);
$str=preg_replace('#(\d)\s*too#','${1}2',$str);
$str=preg_replace('#for\s*(\d)#','4${1}',$str);
$str=preg_replace('#too\s*(\d)#','2${1}',$str);
echo $str;

Outputs:

Please wait for sometime too, the area code is 418 and phone number is 258974

Warning:
If your string looks like this: 8 too for,
this code snippet may or may not fail depending on whether you expect 824 or 82 for, since it does not do recursive replace (the current sequence returns 82 for).

A: You should be using preg_replace_callback() for this:
$str = preg_replace_callback('~\d\K\h*(?:too|for)|(?:too|for)\h*(?=\d)~i',
     function($m) {
        return strtr(strtolower(trim($m[0])), array('too'=>2,'for'=>4));
     }, $str);


text:
Q: Add a .dll source to use classes Im coding in c#. already written a portable console application that needs a dll to work with and it works perfect without any error.
I want to get rid of carrying that dll everywhere and copy its source or some of its classes. Im already using NetShrink software for making my exe and dll a package but its a kind of trick and not a original way.
MyQuestion: Is there any original way in visual studio or any plugins to bring a dll source into another project  ? i heard from an old programmer that there is a built-in tool that bring whole .dll source to project.
What i tried: except Netshrink i tried assembly-explorer in Resharper plugin and get output as .sln project from .dll but thing get hard with this.
the dll is Ionic.Zip.dll in DotNetZip used for compressing files.

A: Actually there is no way around it. You have several options to deal with your portable project.

*

*Add the library project to your solution and reference it.

*Add the library (.dll) to your solution and reference it.

*Add the library (.dll) to your solution and Load it from Resources

*Merge the (.dll) to your .exe with 3rd party tools (e.g., NetShrink)

*Upload your library (.dll) to a NuGet Server and just install it (You could setup your own NuGet Server or use the Microsoft one)

I personally use approach number 3. Copy the .dll to my solution somewhere, reference it, load it on demand and do not copy it to the output folder. If possible, stick to approach number 5. since its the most convenient one.

A: You are actually mixing up obfuscation and merging. Your goal is to hide referenced assemblies that are packed into your assembly.
For a reference look at this question: How can I protect my .NET assemblies from decompilation?
Regarding your original question you are already good to go. As I suggested you could use LibZ or ILMerge (or another tool, there are dozens of them).
You definitely should be more specific in your question as you want to protect your assemblies against piracy and not merge them together.


text:
Q: Flask request.data is slow We have a few clients in Asia and the USA and we're seeing this strange behavior when calling request.data when handling their POST requests:

*

*The Singapore client is super fast (> 10 ms)

*The USA clients are not as fast (50 - 100 ms)

*The Chinese client is the slowest (200+ ms)

We got the above data by using cProfile, so that should be accurate (I think?). The payload of each client varies between 50 - 700 bytes but does not seem to exhibit any patterns (the Singapore client has a medium sized POST payload and the Chinese one has a small sized one)
After looking in this question, I suspect we're facing something similar, where the request is processed immediately after the headers are received, so calling request.data blocks until the full POST payload is received. I am guessing that the Chinese clients are the slowest since the GFW slows down the transmission of the POST payload.
I have two questions:

*

*Does the analysis make sense?

*How can I fix this? The above behavior seems quite inefficient since my API instance is blocked for an additional amount of time and wastes CPU cycles. It seems like it would work better if the request was fully received before being sent to the API instance

FWIW, I inherited this code base and there may be some gaps in my understanding but our DCOS architecture is similar to the image below. I tried looking for configuration options in the external marathon LB to increase buffering or send only fully received requests but I didn't find such options.

A: Looks like I figured this one out!
Apparently Marathon LB is a wrapper around HAProxy and HAProxy has a mechanism to receive the full HTTP request payload before forwarding it on to the backend. Adding the http-buffer-request option to the Marathon-LB configuration seems to have done the trick!


text:
Q: Hadoop WritableComparable RawType, What is RawType Could you please explain what is RAW Type in Java, I could find anything more meaningful in the Internet.
For ex:
Hadoop WritableComparable<T> RawType, What is RawType ? When I try to implement this interface using implements keyword, I was forced to give parameter in the angle brackets.
Not sure, what is RAW type and <> angle brackets has to be used instead of () ?

A: Raw type is like using Object type everywhere. I'll use the example of List:
List list1 = new ArrayList(); //raw list
List<String> list2 = new ArrayList<String>(); //parametrized list

you can put whatever you want to list whether you can only put String objects to list2. Raw list might be convenient sometimes but it's likely to cause problems in future. Essentially raw type in Java means no type specified. If you ever feel like you need to use raw type imho probably there is something you can do to prevent it.
As for <> - angle brackets are used to specify type. You are mistaken by thinking you use them instead of (),
<> specify generic type, () mean a method (or contructor) call which you need to initialize the object.


text:
Q: Calculus of Binary Relations I was reading "Origins of the Calculus of Binary Relations" by Vaughan Pratt where he says "it consists of two components, a logical or static component and a relative or dynamic component" but it seems as if it should be possible to define the "static component" purely in terms of the "dynamic component". Is this the case?

A: *

*That was an historical paper, and the distinction in question was first drawn by De Morgan and then Peirce under the rubric of logical vs. relative as modifiers of sum and product.  In my own papers introducing dynamic logic as a binary version of unary static logic, starting in 1976 (based on class notes from 1974), I used those terms merely as the ones that occurred to me, as I was not familiar with the history and so did not know about "logic" vs. "relative."  Had I been aware of that precedent, "dynamic logic" might these days be called "relative logic," except that its modal character (see 2 below) mitigates against that.

*My "Origins" paper was for the annual evening LICS talk, for LICS'92.  (It nearly didn't happen as I'd just had a quintuple bypass six weeks earlier.  Fortunately I'd recovered by then, and was able two weeks later to visit St. Petersburg, Moscow, Tver to give a conference talk, and Paris.)  An earlier paper,
Pratt, V.R., ``Dynamic algebras as a well-behaved fragment of relation
algebras'', Proc. Algebra and Computer Science, ed.  Bergman, Maddux,
and Pigozzi, LNCS 425, 77-110, Springer-Verlag, 1990.  Also Report No.
STAN-CS-90-1309, CS Dept., Stanford, 1990,
which was originally given as a talk at the workshop "Algebraic Logic and Universal Algebra in Theoretical Computer Science" held in Ames, Iowa in 1988, made the point that the complexity of various logical problems is lower for modules (understood as two-object gadgets) than for monoids as one-object structures.  The underlying intuition was that by limiting the operations in the "dynamic" object (where the monoid lived) and moving the Boolean stuff to the "static object" (a sort of cul-de-sac from which there was no return), the complexity was greatly reduced over that of relation algebra where all the operations can interact, creating much harder problems.  Even without star, Tarski's RA is undecidable, whereas dynamic algebra is decidable even with star, in fact I was even able to show its equational theory was decidable in deterministic exponential time.

*Nevertheless the monoid situation greatly interested me, and in 1990, in response to a request by Johan van Benthem to speak at JELIA'90, I came up with Action Logic for my talk there.  You can read about this under "Action Algebra" on Wikipedia, whose lead redes as follows:
In algebraic logic, an action algebra is an algebraic structure which is both a residuated semilattice and a Kleene algebra. It adds the star or reflexive transitive closure operation of the latter to the former, while adding the left and right residuation or implication operations of the former to the latter. Unlike dynamic logic and other modal logics of programs, for which programs and propositions form two distinct sorts, action algebra combines the two into a single sort. It can be thought of as a variant of intuitionistic logic with star and with a noncommutative conjunction whose identity need not be the top element. Unlike Kleene algebras, action algebras form a variety, which furthermore is finitely axiomatizable, the crucial axiom being a•(a → a)* ≤ a. Unlike models of the equational theory of Kleene algebras (the regular expression equations), the star operation of action algebras is reflexive transitive closure in every model of the equations.
What the lead doesn't say is that it remains an open question after 22 years as to whether Action Logic as an equational theory is decidable.  (The word problem of course would be undecidable, the monoid alone should be enough to kill decidablity.)  Some people who've solved long-standing open problems, in particular Istvan Nemeti and his colleagues, have been unable to crack this one even after all this time.  So if you like this area and have been looking for something easier than the Riemann Hypothesis to hone your problem-solving skills on, just remember that every famously solved problem had its first solver.  People thought Andrew Wiles was just another person beating his head against a brick wall until he proved Fermat's Last Theorem.  This one seems very unlikely to be anywhere near that hard, it should fall simply to a good insight taking 5-10 pages to explain.

A: As I understand it, and in more modern-day terms, the question asks whether it is possible to define the operations $0, 1, \cap, \cup, \neg$ on $P(X^2)$ (operations belonging to the "static component") in terms of "dynamic" operations $\delta', \delta, \circ, \circ', (-)^{op})$ where $\circ$ is relational composition (as an operator on $P(X^2)$):
$$(R \circ S)(x, z) := \exists_y R(x, y) \wedge S(y, z);$$
$\circ'$ is De Morgan dual to $\circ$:
$$(R \circ' S)(x, z) := \forall_y R(x, y) \vee S(y, z);$$
$\delta \in P(X^2)$ is the diagonal subset (the identity for $\circ$), $\delta'$ is its complement (the identity for $\circ'$), and $(-)^{op}$ is the relational converse:
$$R^{op}(x, y) = R(y, x).$$
The answer is no. For example, take $X$ to be $\mathbb{R}$, and consider the relation $n$ where $n(x, y) \Leftrightarrow (x = -y)$. Let $n'$ be the complement of $n$. I claim that the set $A = \{0, 1, \delta, \delta', n, n'\}$ is closed under the dynamic operations. It's clear that each of these elements is a fixed point under relational converse. It's also easy to check that $n \circ n = \delta$, and that
$$n' \circ n = \delta' = n \circ n',$$
$$\delta' \circ n = n' = n \circ \delta',$$
$$n' \circ n' = 1 = n' \circ \delta' = \delta' \circ n' = \delta' \circ \delta',$$
$$1 \circ x = 1 = x \circ 1  \qquad x \in A, x \neq 0$$
$$0 \circ x = 0 = x \circ 0 \qquad x \in A$$
Since $A$ is closed under complementation and under $\circ$, it is also closed under $\circ'$. Thus $A$ is closed under all the dynamic operations. However, it is clearly not closed under intersection, since $n \cap \delta$ is the singleton $\{(0, 0)\}$.


text:
Q: Optimising SQL query - cleans up old logs in database Ok, so we have a rather large database on a Wordpress website, we run a query every month or so that removes old logs from the database and I've been using the query below to accomplish it.
I essentially look at the total rows that need removing and keep running this query until the logs are all gone.
However, with a LIMIT of 1000 the query takes around 30 seconds to complete. The posts table contains around 400,000 entries and on this occasion, around 60,000 of these need removing.
Any help is much much appreciated! I'm a novice when it comes to SQL so this query will probably hurt some peoples eyes, but please be gentle, I'm learning! :)
CREATE TEMPORARY TABLE LOGSTOCLEAN
SELECT
  ID
FROM
  wp_posts WTCUP
  LEFT JOIN wp_term_relationships WTCUTR ON WTCUP.ID = WTCUTR.object_id
  LEFT JOIN wp_term_taxonomy WTCUTT ON WTCUTR.term_taxonomy_id = WTCUTT.term_taxonomy_id
WHERE
  WTCUTT.term_id IN (10)
  AND WTCUP.post_date < DATE_SUB(NOW(), INTERVAL 45 DAY)
GROUP BY
  WTCUP.ID
  LIMIT 1000;

    DELETE FROM wp_posts
    WHERE wp_posts.ID IN(SELECT ID FROM LOGSTOCLEAN)
    LIMIT 1000;

A: Rather than a rows limit, a time would allow the oldest rows to be removed, which we might hope are co-located by clustering or partitioning, or at least quickly locatable by index.  Select min date-time + some interval and delete all < that.
 Partitioning by day means you can just clean/drop one partition at a time.  Your RDBMS may vary!  Dropping a day (partition?) every day at midnight seems sensible!

A: PARTITIONing is out of the question since you are purging only rows with term_id=10, and that test is not in wp_posts.
It sound like there are more than 1000 rows to remove on a typical day?  Then consider removing only, say, 300.  But do it every hour instead of every month.  A "cron" job or a MySQL "Event" could take care of running that automatically.  (If there is more than 300 in an hour, don't worry, the next invocation will take care of more.)
You have not really asked a Question.  Is what you are doing too slow?  Interferes with other activities?  Too 'manual'?  Or something else?
If it is a performance question, then please provide SHOW CREATE TABLE for each table.


text:
Q: Merge Multiple Google Spreadsheets into One Sheet I have a couple of Google Spreadsheets.
This Spreadsheets have the same columns number and columns names, but diffrent data.
I want to merge all of this Spreadsheets into one Sheet.
The closest thing i found is this: http://ctrlq.org/code/19980-merge-google-spreadsheets
, but it make new Spreadsheet with diffrent Sheet for every Sheets on Spreadsheets.
I want just one Sheet with all data.
Do you guys have idea how to do that?

A: Short answer
Use embedded arrays. The simplest form for spreadsheets with regional settings that use dot as decimal separator are

*

*={A1:A2;B1:B2} for vertical merging and

*={A1:A2,B1:B2} for horizontal merging.

Explanation
To merge vertically two ranges,

*

*for spreadsheets using dot as a decimal separator and comma as function parameter separator
={Sheet1!A1:B5;Sheet2!A1:B5}

*for spreadsheets using comma as a decimal and semicolon as function parameter separator
={Sheet1!A1:B5\Sheet2!A1:B5}
Reference

*

*Using arrays in Google Sheets- Google Docs editors Help

A: You can use Google Apps Scripts for this.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var All = ss.insertSheet("All-Values");

function TotalsSheet() {
  var totaldata = [];
  var sheets = ss.getSheets();
  var totalSheets = 2;

  for (var i=0; i < totalSheets; i++) {
    var sheet = sheets[i];
    var range = sheet.getDataRange();
    var values = range.getValues();

    for (var row in values) {
      totaldata.push(values[row]);
    }
  }
  return totaldata;
}

function Start() {
  var totaldata = TotalsSheet();
  for (var i =0; i < totaldata.length; i++) {
    All.appendRow(totaldata[i]);
  }
}


text:
Q: C++ Multiple variadic template not binded to function arguments I was trying to use some variadic template parameters but I was quickly stopped by an error I didn't managed to understand.
#include <tuple>

template <typename T>
struct Foo
{
  typedef T type;
};

// return a tuple of pair of args and Foo templated on Types
template <typename Head, typename ...Args, typename Type, typename ...Types>
auto func(Head arg, Args... args)
{
  return std::tuple_cat(std::make_tuple(std::make_pair(arg, Foo<Type>())),
                       func<Args..., Types...>(args...));
}

template <typename Head, typename Type>
auto func(Head arg)
{
  return std::make_tuple(std::make_pair(arg, Foo<Type>()));
}

int main()
{
  func<int, bool, char>(1, 2, 3);
}

Here func try to unpack template parameters and make a tuple of pair of a func argument and a Foo struct templated on the second variadic template but I am having:
test.cc:25:3: error: no matching function for call to 'func'
 func<int, bool, char>(1, 2, 3);
 ^~~~~~~~~~~~~~~~~~~~~
test.cc:11:6: note: candidate template ignored: couldn't infer template argument 'Type'
 auto func(Head arg, Args... args)
 ^
test.cc:18:6: note: candidate function template not viable: requires single argument 'arg', but 3
  arguments were provided
 auto func(Head arg)
 ^
 1 error generated.

Why Type cannot be inferred ? (gcc told me the same)
I am sure that multiple variadic template is possible after seing std::tuple_cat implementation (https://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-api-4.5/a01066_source.html) and I think this is a simple example and someone should knows better that me if there is a solution or if the standard doesn't accept this.
Thanks for your help,

A: Put deduced arguments last.
... template arguments are greedy -- they will consume passed in arguments and wont "save" any for later template arguments.
Once that is done, deduction occurs from non-template function arguments.
Swap like this:
template <typename Type, typename ...Types, typename Head, typename ...Args>
auto func(Head arg, Args... args)

Also, get rid of the other overload, so func<int,int>(3) is not ambiguous.
This makes the recursion break, but that is easy to fix:
template <class... Types, class... Args>
auto func(Args... args)
{
  return std::make_tuple(std::make_pair(args, Foo<Types>())...);
}

Which has the bonus of being nice and short.

A: A key data point here is that a variadic parameter will be matched by an empty list. This has several consequences.
The first consequence is that given the following template declaration:
template <typename Head, typename ...Args, typename Type, typename ...Types>

and the following instantiation:
<int, bool, char>

There are several ways the instantiation can match the template:
1.
Head           int
...Args        bool
Type           char
... Types      (empty list)

2.
Head           int
...Args        (empty list)
Type           bool
... Types      char

So, that's one source of ambiguity. The reference in main() can match either template definition.  Although there are various arcane rules that in some instances can resolve this kind of ambiguity, it's always better not to rely on arcane template disambiguation rules, or at least go no further than use several standard, basic SFINAE approaches.
But, back on topic, right off the bat the compiler is going to be behind an eight-ball here, not having a clear candidate to resolve the template reference in main(). But it gets worse. Given
auto func(Head arg, Args... args)

and
auto func(Head arg)

Because, once again, a variatic parameter, in this case it's Args..., can match an empty list, then, for example:
func(4)

Can match either function signature.
Combine all of these factors together, and the compiler can't really make heads or tails here.


text:
Q: Include section number in list number As a follow-up to this question, I'd like to know if it is possible to automatically include the current section number, including all nesting levels, in the list number. How do I accomplish this?
Example of what I want:
\section{This is section 1}
  \pointedenum\begin{enumerate}
    \item This item has number 1.1.
    \item This item has number 1.2.
    \pointedenum\begin{enumerate}
      \item This item has number 1.2.1.
    \end{enumerate}
  \end{enumerate}

  \subsection{This is section 1.1}
    \pointedenum\begin{enumerate}
      \item This item has number 1.1.1.
      \item This item has number 1.1.2.
    \end{enumerate}
% etcetera...

A: The variables governing the labels for the items in an enumerated list are \labelenumi (for the top level), \labelenumii (next-to-top level),... You can use \renewcommand to redefine them to anything you want.
I would expect this to work, but I have not tried it:
\renewcommand{\labelenumi}{\thesection.\arabic{enumi}}
\renewcommand{\labelenumii}{\thesection.\arabic{enumi}.\arabic{enumii}}

A: You could redefine \theenumi using \thesection:
\renewcommand*{\theenumi}{\thesection.\arabic{enumi}}
\renewcommand*{\theenumii}{\theenumi.\arabic{enumii}}

In that case omit \pointedenum, it would destroy that redefinition.
That may also be done using \thesubsection.
Alternatively, here's code using the enumitem package:
\usepackage{enumitem}
\setenumerate[1]{label=\thesection.\arabic*.}
\setenumerate[2]{label*=\arabic*.}

Using enumitem you're able to continue numbering by \begin{enumerate}[resume] if you like.

A: I usually resolve this with the enumerate package. I always use this package anyway to control how items are enumerated by allowing you to specify e.g. \begin{enumerate}[(1)] to have parentheses the numbers etc..
In preamble use
\usepackage{enumerate}

Then:
\section{This is section 1}
\begin{enumerate}[\thesection .1]
\item This is item 1.1
\item This is item 1.2
\end{enumerate}

\subsection{This is section 1.1}
\begin{enumerate}[\thesubsection .1]
\item This is item 1.1.1
\item This is item 1.1.2
\end{enumerate}

This solution allows you to use section numbering in enumerate only where you specify it. However if you want to do this globally I would use Stefan Kottwitz' solution above.


text:
Q: boost::filesystem::path and std::string I have a String class which has a member std::string. One of the constructor is
String (std::string s)
{
    // member: std::string _mString;
    _mString = s;  // error on path assignment
}

I now have functions that take String as parameter, e.g. Load(String path);
but it turns out that boost::filesystem::path::string() is incompatible with that String constructor, yet, normally assigning is ok
boost::filesystem::path somepath("some directory")
std::string filename = somepath.extension(); // OK!

What is happening? How can I make my constructor work? Thanks.
EDIT: Issue solved by making it const ref, but still curious why the error because it seems ok to pass a copy since it can be assigned directly.
Error in file xstring
void __CLR_OR_THIS_CALL _Tidy(bool _Built = false,
        size_type _Newsize = 0)
        {   // initialize buffer, deallocating any storage
        if (!_Built)
            ;
        else if (_BUF_SIZE <= _Myres)
            {   // copy any leftovers to small buffer and deallocate
            _Elem *_Ptr = _Bx._Ptr;
            if (0 < _Newsize)
                _Traits_helper::copy_s<_Traits>(_Bx._Buf, _BUF_SIZE, _Ptr, _Newsize);
            _Mybase::_Alval.deallocate(_Ptr, _Myres + 1);
            }
        _Myres = _BUF_SIZE - 1; // **** ERROR ***
        _Eos(_Newsize);
        }

A: in your constructor: String (std::string s) should be String (const std::string& s)


text:
Q: Is it possible to access a private vimeo video with your API? I have an app and I want to integrate vimeo videos, so instead of using access domain release I would have to use the token, I read all your documentation and even then it was not clear how this request would be, I'm testing with insomnia, and it always returns an error.

A: You can access private videos, but you must use an access token authenticated to your user and it must have the private scope.
You can view documentation for this here: https://developer.vimeo.com/api/guides/start#generate-access-token
To view all of your user's videos, you use GET https://api.vimeo.com/me/videos with a header Authorization: bearer <token>, to view a specific video, you use GET https://api.vimeo.com/videos/{video_id} with the same header.


text:
Q: Svelte reactivity: todos.forEach(todo => todo.completed = completed) vs. todos.forEach((todo, i) => todos[i].completed = completed) I'm working on the MDN svelte tutorial and in this section on the checkAllTodos function:
https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_reactivity_lifecycle_accessibility#reactivity_gotchas_updating_objects_and_arrays
it states that,
todos.forEach(todo => todo.completed = completed)does not trigger reactivity but todos.forEach((todo, i) => todos[i].completed = completed) does, because

assignments to properties of arrays and objects work the same way as assignments to the values themselves

I understand why todos.forEach(todo => todo.completed = completed)does not do the trick, but don't see why todos.forEach((todo, i) => todos[i].completed = completed) does. Why do assignments to properties of arrays and objects work the same way as assignments to the values themselves?
For me, both should fail to trigger reactivity as they do not change the reference of todos.
What did I miss here?

A: This is called "conservative reactivity": The compiler will invalidate a variable when it or any of its properties (or more deeply nested properties) are assigned. Otherwise it would be hard to impossible to track all changes correctly, especially through component props.


text:
Q: Python: is there a way to sort a list from higher to lower I have the following piece of code in python:
results = {}
....
results = sorted([(v, k) for (k, v) in results.items()])
....
return results[:limit]

results contains distances that are sorted in such a way the smaller distances are in the top of the list
Is there a way to sort this list in such a way the higher distances are in the top of results?
 Or, if we don't reverse the items is there a way to get the last items of results instead of the top results using return results[:limit]

A: Use the optional reverse parameter in the sorted function:
results= sorted([(v, k) for (k, v) in results.items()], reverse=True)

A: To answer the second question you ask, since @Ruzihm already answered the first, you can get the last items of results with:
return results[-limit:]


text:
Q: I want to install a bruteforcer that uses pip in python, help me with it! The directory '/home/anuj/.cache/pip/http' or its parent directory is not
owned by the current user and the cache has been disabled.
Please check the permissions and owner of that directory.
If executing pip with sudo, you may want sudo's -H flag.

I get this error while running following python script:
import os
os.system("sudo apt-get install python-pip python-dev build-essential -y")
os.system("sudo apt-get install build-essential libssl-dev libffi-dev python-dev python-setuptools -y")
os.system("pip install -U selenium && sudo apt-get install firefoxdriver -y")
os.system("pip install mechanize && pip install paramiko && pip install requests && pip install xmpppy==0.5.0rc1")
os.system("pip install stem && pip install pyvirtualdisplay && apt-get install xvfb")

Now I need to install, please help me!

A: Take back ownership of pip's cache folder in your home directory using this command:
sudo chown -R anuj: /home/anuj/.cache/pip/

After that, pip should stop complaining.
For the future, do never run sudo pip. If you really need to use pip to install Python packages globally for all users, use sudo -H pip instead, so that it will use the root user's home directory as cache.


text:
Q: iText7 for .NET is 4-9 times slower than iTextSharp 5.5.9 while merging files I've tried using iText7 for .NET for merging documents into single one, after getting some errors I've created second application but using iTextSharp 5.5.9.
I was amazed that same functionality works 4 times faster than in newer version.
Below is my code for version 5:
private bool Merge5(IEnumerable<string> fileNames, string targetPdf)
{
    bool merged = true;
    using (FileStream stream = new FileStream(targetPdf, FileMode.Create))
    {
        Document document = new Document();
        PdfCopy pdf = new PdfCopy(document, stream);
        PdfReader reader = null;
        try
        {
            document.Open();
            foreach (string file in fileNames)
            {
                reader = new PdfReader(file);
                //not needed I guess
                reader.ConsolidateNamedDestinations();
                pdf.AddDocument(reader);
                reader.Close();
            }
        }
        catch (Exception)
        {
            merged = false;
            if (reader != null)
            {
                reader.Close();
            }
        }
        finally
        {
            if (pdf != null)
            {
                pdf.Close();
            }
            if (document != null)
            {
                document.Close();
            }
        }
    }
    return merged;
}

and code for version 7:
private void Merge7(List<string> src, string dest)
{
    PdfDocument pdfDocument1;

    try
    {
        pdfDocument1 = new PdfDocument(new PdfReader(src[0]), new PdfWriter(dest));
    }
    catch (Exception e)
    {
        Debug.WriteLine(e);
        throw;
    }

    var path = string.Empty;

    for (int i = 1, max = src.Count; i < max; i++)
    {
        path = src[i];
        try
        {
            PdfDocument pdfDocument2 = new PdfDocument(new PdfReader(path));
            var pagesCount = pdfDocument2.GetNumberOfPages();
            pdfDocument2.CopyPagesTo(1, pagesCount, pdfDocument1);
            pdfDocument2.Close();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
    }
    try
    {
        pdfDocument1.Close();
    }
    catch (Exception e)
    {
        Debug.WriteLine("Dest: " + dest);
        Debug.WriteLine("Src: " + path);
        Console.WriteLine(e);
    }
}

My call looks like this:
string dest = @"E:\TEST\final.pdf";
var files = Directory.GetFiles(@"E:\TEST\PDFS", "*.pdf").OrderBy(x => x).Take(1000).ToList();

Stopwatch sw = new Stopwatch();
sw.Start();

Merge5(files, dest);

sw.Stop();
Debug.WriteLine(sw.Elapsed);

First test:
For 1000 PDF files (same file, but copied 1000 times, size 370 KB) I get this results:
                 |           1 pass |           2 pass |           3 pass |
---------------------------------------------------------------------------
iText7 for .NET  | 00:00:13.4088770 | 00:00:13.5490370 | 00:00:14.2491171
iTextSharp 5.5.9 | 00:00:03.5330538 | 00:00:03.2058272 | 00:00:03.2854776

Second test:
For 1000 PDF files (same file, but copied 1000 times, size 606 KB) I get this results:
                 |           1 pass |           2 pass |           3 pass |
---------------------------------------------------------------------------
iText7 for .NET  | 00:00:25.5538607 | 00:00:24.6525861 | 00:00:26.7326629
iTextSharp 5.5.9 | 00:00:06.0918370 | 00:00:05.5687955 | 00:00:06.0283861

What might be the reason why I get so large difference in performance?
Can I optimize my merging function so that it will be faster (fast as in version 5)?
I'd like to use version 7, but because of performance I'll probably use older version.


text:
Q: How do i hide the auto-generated custom field that's created when update_post_meta() is called? I've added a custom textarea for the create/edit post admin page. I did so using the add_meta_box() function. The problem is that the add_meta_box() callback function (which saves the data input into the textarea) calls the update_post_meta(). update_post_meta() then adds a custom field within the custom field section. So you essential end up with two textareas for the same field! The one you've created and the auto generated one!
Is there a way to remove the auto generated custom field?
Thanks,
Jon

A: If the meta field starts with an underscore, it will be hidden in the interface by adding the class hidden to the <tr> element. You could also apply this class by yourself using Javascript, the <tr> element has an id of meta-{$custom_field_id}.


text:
Q: Unable to prevent keypresses from unsuspending laptop It appears that due to the poor build of my laptop, keys sometimes get pressed in my backpack, even though the lid is closed. This causes it to silently resume from sleep, then overheat and drain the battery.
I've been trying to turn keypress wakeups off, but unsuccessfully so.
Before closing the lid, I've disabled all device wakeups:
$ cat /proc/acpi/wakeup
Device  S-state   Status   Sysfs node
P0P1      S4    *disabled
EHC1      S4    *disabled  pci:0000:00:1d.0
XHC       S3    *disabled  pci:0000:00:14.0
HDEF      S4    *disabled  pci:0000:00:1b.0
RP03      S4    *disabled  pci:0000:00:1c.0
PXSX      S4    *disabled  pci:0000:01:00.0
RP04      S4    *disabled  pci:0000:00:1c.3
PXSX      S4    *disabled  pci:0000:02:00.0
RP05      S4    *disabled  pci:0000:00:1c.4
PEGP      S4    *disabled  pci:0000:03:00.0
PEG0      S4    *disabled
PEGP      S4    *disabled
PEG1      S4    *disabled
PEG2      S4    *disabled
LID0      S3    *disabled
PWRB      S4    *disabled

After waking it up by pressing some key (doing so by slightly opening the lid, just enough to reach a key), it seems PXSX has somehow enabled itself for wakeup:
stefan@stefan-PC ~> cat /proc/acpi/wakeup
Device  S-state   Status   Sysfs node
P0P1      S4    *disabled
EHC1      S4    *disabled  pci:0000:00:1d.0
XHC       S3    *disabled  pci:0000:00:14.0
HDEF      S4    *disabled  pci:0000:00:1b.0
RP03      S4    *disabled  pci:0000:00:1c.0
PXSX      S4    *enabled   pci:0000:01:00.0
RP04      S4    *disabled  pci:0000:00:1c.3
PXSX      S4    *disabled  pci:0000:02:00.0
RP05      S4    *disabled  pci:0000:00:1c.4
PEGP      S4    *disabled  pci:0000:03:00.0
PEG0      S4    *disabled
PEGP      S4    *disabled
PEG1      S4    *disabled
PEG2      S4    *disabled
LID0      S3    *disabled
PWRB      S4    *disabled

Not sure what causes this or how to stop it. /var/log/dmesg, /var/log/pm-suspend.log, /var/log/syslog show absolutely no information about the wakeup reason or about PXSX (I assume PXSX is the keyboard, not sure though).
Looking at /usr/lib/pm-utils and /etc/pm/sleep.d, there seem to be no hooks which would enable PXSX.
Could you suggest a way of debugging and fixing this issue? Thanks!
$ uname -a
Linux x 3.13.0-49-generic #83-Ubuntu SMP Fri Apr 10 20:11:33 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux


text:
Q: Prove that $\int_0^1 \frac{1}{1+\ln^2 x}\,dx = \int_1^\infty \frac{\sin(x-1)}{x}\,dx $ I've found the following identity.

$$\int_0^1 \frac{1}{1+\ln^2 x}\,dx = \int_1^\infty \frac{\sin(x-1)}{x}\,dx $$

I could verify it by using CAS, and calculate the integrals in term of exponential and trigonometric integrals, then using identities between them. However, I think there is a more elegent way to prove it.

How could we prove this identity?

Also would be nice to see some references.

A: Hint. One may observe that

$$
\frac1{1+\ln^2 x}=-\Im \frac1{i-\ln x}=-\Im \int_0^{\infty}e^{-(i-\ln x)t}dt,\quad x \in (0,1),
$$

gives

$$
\begin{align}
\int_0^1 \frac{1}{1+\ln^2 x}\,dx&=-\Im \int_0^1\!\!\int_0^{\infty}e^{-(i-\ln x)t}dt\:dx\\\\
&=-\Im \int_0^{\infty}\!\!\left(\int_0^1x^t dx\right)e^{-it}dt\\\\
&=-\Im \int_0^{\infty}\!\!\frac1{t+1} e^{-it}dt\\\\
&=\int_0^{\infty}\!\! \frac{\sin t}{t+1}  dt\\\\
&= \int_1^\infty \frac{\sin(x-1)}{x}\,dx
\end{align}
$$

as announced.

A: A variant:
$$
\int_1^{\infty}\frac{\sin(x-1)}{x}dx=\Im\int_1^{\infty}\frac{e^{i(x-1)}}{x}dx= \quad (1)\\ \Im\int_1^{\infty}\int_0^{\infty}e^{i(x-1)-xt}dtdx=\Im\int_0^{\infty}\int_1^{\infty}e^{i(x-1)-xt}dxdt=\quad (2) \\
\Im\int_0^{\infty}\frac{e^{-t}}{t-i}dt=-\int_0^{\infty}\frac{e^{-t}}{1+t^2}dt=\quad (3) \\
\int_0^1\frac{1}{1+\log^2(x)}dx\quad (4)
$$
Explanation
(1)   $\quad\Im (e^{i x})=\sin(x)$
(2) $\quad$ $\frac{1}{x}=\int_{0}^{\infty} e^{-xt}dt$ for $x>0$
(3) $\quad$ straightforward integration and $\Im\left(\frac{1}{z}\right)=\frac{\Im(\bar{z})}{|z|^2}$
(4) $\quad    e^{-t}=x,dt=\frac{-1}{x}$

A: Define $I(a)=\int_0^{\infty} e^{-(x+1)a}\frac{\sin(x)}{x+1}dx$.
Then $\displaystyle I'(a)=-\int_0^{\infty} e^{-(x+1)a}\sin(x)dx=-\frac{e^{-a}}{a^2+1}$, and since $\lim_{a\to \infty}  I(a)=0$, we have  $\ \displaystyle I(0)=\int_0^{\infty} \frac{\sin(x)}{x+1}=\int_0^{\infty}\frac{e^{-a}}{a^2+1}da=\int_0^1\frac{dx}{1+\ln^2 x}.$


text:
Q: Moved CPanel account and now can't access database I've just migrated a site across to a new account on CPanel and I just can't access the databases at all. The error I'm receiving is:
SQLSTATE[28000] [1045] Access denied for user

I've changed the usernames and passwords in the config and connection files, and altered paths, but it's left me stumped.

A: OK, panic over. The server people just responded with a "You should able to access the database now. Please let me know if you need any further assistance."
Frustrating, but happily sorted!


text:
Q: How to read files depending on their file type I want to write a code that can get file from user and then read files depending on their filetype i.e. if it is a json file then it must read it as json file and if it is a pickle file then read it as pickle file. My code is as follows:
import os
filename = input("Enter File Name ")
fileName,fileExtension = os.path.splitext(filename)
if fileExtension==".json" :
  print 'This file is flac file %s' %files
 elif  fileExtension==".mp3":
   print 'This file is mp3 file %s' %files
 else:
   print 'Format is not valid'

I understand this concept but for this i have to write seperate elif for each file type. Is their any way that file is handled at once based on the file type entered by the user instead of writing code for each file type?

A: You will need to write code for different files as each file must be read differently. so there is no option for that.
tip:- you can make functions to a specific file type and pass them that file. will help clean up your code


text:
Q: Multiple Custom Fonts for application without specific TargetType I'm trying to import two custom fonts into my application. For now, I have added the fonts in respectively the .Droid/Assets and .iOS/Resources directories and for iOS loaded it in my Info.plist.
In my App.xaml I do the following to load the fonts in my PCL:
<Application.Resources>
    <ResourceDictionary>
        <Style x:Name="BoldFont" TargetType="Label">
            <Setter Property="Label.FontFamily">
                <Setter.Value>
                    <OnPlatform x:TypeArguments="x:String">
                        <OnPlatform.Android>PT_Sans-Narrow-Web-Regular.ttf#PT Sans Narrow</OnPlatform.Android>
                        <OnPlatform.iOS>PT Sans Narrow</OnPlatform.iOS>
                    </OnPlatform>
                </Setter.Value>
            </Setter>
        </Style>
    </ResourceDictionary>
</Application.Resources>

However, i wish to be able to use multiple fonts in my Labels, being the reason why i added the following code into my <ResourceDictionary>:
<Style x:Name="RegularFont" TargetType="Label">
    <Setter Property="Label.FontFamily">
        <Setter.Value>
            <OnPlatform x:TypeArguments="x:String">
                <OnPlatform.Android>RobotoCondensed-Regular.ttf#Roboto Condensed</OnPlatform.Android>
                <OnPlatform.iOS>Roboto Condensed</OnPlatform.iOS>
            </OnPlatform>
        </Setter.Value>
    </Setter>
</Style>

Unfortunately, I'm getting the error:

A resource with the key 'Xamarin.Forms.Label' is already present in the ResourceDictionary

Furthermore, do I really have to make my TargetType specific to the Label, if say, I want to use the fonts globally regardless if it's a Label or an Entry?

A: First, with Style, use x:Key instead of x:Name.  That will avoid the error message you're seeing.
<Style x:Key="RegularFont" TargetType="Label">
    <Setter Property="Label.FontFamily">
        <Setter.Value>
            <OnPlatform x:TypeArguments="x:String">
                <OnPlatform.Android>RobotoCondensed-Regular.ttf#Roboto Condensed</OnPlatform.Android>
                <OnPlatform.iOS>Roboto Condensed</OnPlatform.iOS>
            </OnPlatform>
        </Setter.Value>
    </Setter>
</Style>

Sometimes you can share Style definitions between types. The best way to do that is to use a TargetType that is a common base class that defines the properties you want to set. Unfortunately, there is no such common base class between Label and Entry.  They each independently define FontFamily.


text:
Q: Have users upload and watch videos on my website? I'd like to enable users to upload and watch videos on my website.  This is very much like what a site like youtube currently does.  I'm not trying to create another youtube.  The video functionality is complimentary to other, already existing functionality the site has.  I don't mind having the users upload via youtube or another video sharing site.  The videos don't have to be private, but I do need to control the upload process.  Meaning, I'd like the video upload to be one step in a multi-step process.  So for example, let's say that if I was building a job search site (I am not), a user might do the following steps.

*

*Register and supply some info about yourself

*Create a resume with employment history

*Upload a video about yourself for employers to see

*Review and activate resume

So, in step #3 the user needs to upload a video.
Do I have any way to integrate with an existing video sharing site, but still retain control over the entire process?  Or do I need to create the uploading, converting to FLV, and playing from scratch myself?
I would like to avoid telling the user to independently go on youtube, post a video, and then tell the site what the URL is.
Thanks

A: Maybe this helps:

*

*Oct 12, 2009: Direct Uploads Server Migration

*Developer's Guide: Data API Protocol – Browser-based Uploading