text:
Q: Python : How to search a large array in effiecient way? Problem :
Iam working on a data analysis project which require me to compare the substrings of an unknown word against a corpus of good and bad words.
I initially generated 4 lists and stored them in pickle format in disk.
-rw-rw-r-- 1 malware_corpus malware_corpus 189M May  4 13:11 clean_a.pkl
-rw-rw-r-- 1 malware_corpus malware_corpus 183M May  4 13:12 clean_b.pkl
-rw-rw-r-- 1 malware_corpus malware_corpus 1.7M Apr 30 11:12 data_backup.csv
-rw-rw-r-- 1 malware_corpus malware_corpus 2.9M May  4 13:13 data.csv
-rw-rw-r-- 1 malware_corpus malware_corpus 231M May  4 13:12 mal_a.pkl
-rw-rw-r-- 1 malware_corpus malware_corpus 232M May  4 13:13 mal_b.pkl

So in my code whenever a new string arises i will take these 4 lists and compare the sub-strings into these 4 lists and calculate the score.Due to all these 4 lists stored in memory,program is slow
Also each list has millions of words and if i want to do a search iam taking much longer time as it is taking O(n) time.
Solution Required:

*

*Any effiecient way to store the 4 lists so that they wont bulk up my memory.

*Any better way to search the string in the 4 lists.

*How to access large lists in python.

Code Part:
    def create_corpus(self):
    """corpus

    :param domain: Doamin passed will be split and words are stored in
    corpus.
    """
    with open(os.path.join(os.path.dirname(os.path.realpath(__file__)),'utils/x.txt'),'r') as f:
        for line in f:
            line = line.rstrip()

            self.line_x = self.calculate_xs(line)
            for i in self.line_x:
                self.clean_xs.append(i)
            self.line_y = self.calculate_ys(line)
            for i in self.line_y:
                self.clean_ys.append(i)
    with open(os.path.join(os.path.dirname(os.path.realpath(__file__)),'utils/y.txt'),'r') as f:
        for line in f:
            line = line.rstrip()
            self.line_x = self.calculate_x(line)
            for i in self.line_x:
                self.mal_xs.append(i)
            self.line_y = self.calculate_y(line)
            for i in self.line_y:
                self.mal_ys.append(i)

    # Store the Datasets in pickle Formats
    with open(os.path.join(os.path.dirname(os.path.realpath(__file__)),\
                           'utils/clean_x.pkl'),'wb') as f:
        pickle.dump(self.clean_xs , f)

    with open(os.path.join(os.path.dirname(os.path.realpath(__file__)),\
                           'utils/clean_ys.pkl'),'wb') as f:
        pickle.dump(self.clean_ys , f)
    with open(os.path.join(os.path.dirname(os.path.realpath(__file__)),\
                           'utils/mal_xs.pkl'),'wb') as f:
        pickle.dump(self.mal_xs , f)
    with open(os.path.join(os.path.dirname(os.path.realpath(__file__)),\
                           'utils/mal_ys.pkl'),'wb') as f:
        pickle.dump(self.mal_ys, f)
    return 1

def compare_score_function(self,domain):
    self.domain = domain
    self.g_freq = {}
    self.b_score = 0.0
    from collections import Counter
    for x in self.substrings_of_domain:
        self.g_freq[x] = {}
        self.g_freq[x]['occur'] = self.clean_x.count(x)
        self.g_freq[x]['freq']  = self.clean_x.count(x)/len(self.clean_x)
    for key,value in self.g_freq.iteritems():
        self.b_score += value['freq']
    return self.b_score

def calculate_x(self,domain):
    self.domain = self.clean_url(domain)
    self.bgrm = list(ngrams(self.domain,2))
    self.bgrm = [''.join(a) for a in self.bgrm ]
    return self.bgrm

def calculate_y(self,domain):
    self.domain = self.clean_url(domain)
    self.tgrm = list(ngrams(self.domain,3))
    self.tgrm = [''.join(a) for a in self.tgrm]
    return self.tgrm

Example Explaination

*

*clean_x_list = ['ap','pp','pl','le','bo','xl','ap']

*clean_y_list = ['apa','ppa','fpl','lef','bfo','xdl','mpd']

*bad_x_list = ['ti','qw','zx','qa','qa','qa','uy']

*bad_y_list =  ['zzx','zxx','qww','qww','qww','uyx','uyx']

Here suppose these are my 4 Lists:
My new string came -- suppose apple
 - Now i will calculate x words for apple => ['ap','pp','pl','le']
 - Now i will calculate y words for apple => ['app','ppl','ple','lea']

*

*Now i will search each x-word of apple i.e ['ap','pp','pl','le'] in both clean_x_list and bad_x_list

*then i will calculate frequency and occurency count

*occurence of ap in clean_x_list = 2

*frequence of ap in clean_x_list = 2 /7

*occurence of ap in bad_x_list   = 0

*occurence of ap in bad_x_list   = 0 /7

similarly i compute the other words occurence and frequency and finally sum it

A: Consider sorting your lists, and using bisect for searching your lists. Worst case lookup time is O(log n) in this case.

A: There are basically three options: A linear scan of the list in O(n), ...
>>> lst = random.sample(range(1, 1000000), 100000)
>>> x = lst[50000]
>>> %timeit x in lst
100 loops, best of 3: 2.12 ms per loop

... a binary search in the sorted list in O(logn), using the bisect module, ...
>>> srt = sorted(lst)
>>> srt[bisect.bisect_left(srt, x)] == x
True
>>> %timeit srt[bisect.bisect_left(srt, x)] == x
1000000 loops, best of 3: 444 ns per loop

... and a lookup in a hash set in O(1):
>>> st = set(lst)
>>> %timeit x in st
10000000 loops, best of 3: 38.3 ns per loop

Obviously, the set is by far the fastest, but it also takes up a bit more memory than the list based approaches. The bisect approach might be a good compromise, being already 5000 times faster then the linear scan in this example and only requiring to sort the list.
>>> sys.getsizeof(lst)
800064
>>> sys.getsizeof(srt)
900112
>>> sys.getsizeof(st)
4194528

However, unless your computer is very limited on memory, this should not be a problem. In particular, it will not make the code slower. Either it all fits into memory, and all is well, or it does not, and your program comes to a grinding halt.

If your good/bad word lists can contain duplicates, then set is not an option, and bisect will not work well, either. In this case, create a Counter for each of those lists. Then you can get the occurrence count and frequencies for each of the substrings in your text. Being a kind of hash map / dictionary, lookup in the Counter will also be O(1).
>>> clean_x_list = ['ap','pp','pl','le','bo','xl','ap']
>>> w = "apple"
>>> wx = [w[i:i+2] for i in range(len(w)-1)]
>>> ccx = collections.Counter(clean_x_list)

>>> occ_wx = {x: ccx[x] for x in wx}
>>> occ_wx
{'ap': 2, 'pp': 1, 'pl': 1, 'le': 1}

>>> freq_wx = {x: ccx[x] / len(clean_x_list) for x in wx}
>>> freq_wx
{'ap': 0.2857142857142857,
 'pp': 0.14285714285714285,
 'pl': 0.14285714285714285,
 'le': 0.14285714285714285}

And analogously for clean_y_list, bad_x_list, and so on.

A: One option to save space is to store the word files in a compressed way, but also not read the entire word file into memory.  For this an easy option is gzip.GzipFile which allows you to operate on a gzip archive like a regular file:
import gzip

with gzip.open('input.gz','rt') as text_f:
    for line in text_f:
        line = line.strip()
        print(line)

This way you can treat each line in the file as an item in a list, and process them accordingly.
Note the rt (or wt) open method, which causes it to be processed as text, not binary - this will depend on if you're just storing plain text/json, or using a binary format for your data (like pickle).


text:
Q: Get related entity number for each record in twig (or controller) I have a People class and a Group class. I know what group each man is part of through its 'group' field, but I don't know what people are in a group. To do that I have to find all people in the group by querying the People table.
Here are just the relevant parts of my classes:
class People
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(name="id",type="integer")
     */
    protected $id;

    /**
     * @ORM\ManyToOne(targetEntity="Bundle\Entity\Groups")
     * @ORM\JoinColumn(referencedColumnName="id")
     */
    protected $group;

.....

And here is part of my Group class.
class Group
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;
...

What I'm trying to do is count how many people are in each group and pass it in a twig template like so:
  {% for group in allGroups %}

name: {{group.name}}

date:{{ group.createdAt|date('d-m-Y H:i:s') }}

Number of people: {{ group.peopleNo}}

   {% endfor %}

The problem is that I can't seem to find out how to calculate and pass the number of people in each group. All the other data is easy by calling the doctrine and getting the repository and passing the group object to the view, but how to pass additional data for my records?
The group.peopleNo is not a property of my Group class. The only way for me to get it is go through the People class and count for each group how many people are in the group. But how do I pass it through the controller to the view?
Using the answer below I get this structure:
array(2) {
  [0]=>
  array(2) {
    [0]=>
    string(8) "Array(4)"
    ["total_peoples"]=>
    string(1) "3"
  }
  [1]=>
  array(2) {
    [0]=>
    string(8) "Array(4)"
    ["total_peoples"]=>
    string(1) "1"
  }
}

I'm not sure how can I loop through it in twig to display each group's number because it's indexed in order starting with 0, rather than indexed by my group id's. I think it's fine if a group has no people, then I'll just say it has 0 people if it can't find a record with it. The information is correct, I have two groups, one with 1 and other with 3 people, but their id's are 1 and 2, not 0 and 1.
Here's how my twig would look like, foreach in foreach seems like bad practice:
   {% for group in groups %}

 {{ group .name|e }}

{{ group .createdAt|date('d-m-Y H:i:s') }}

                {% for key, ppno in peopleno %}
                    {% if ppno [key] is defined %}
                        {% if ppno [key]['id']==ticket.id %}
                            people: {{ peopleno [key]['total_peoples'] }}
                        {% endif %}
                    {% else %}
                        people:0
                    {% endif %}

                {% endfor %}

        {% endfor %}

A: Create a One-To-Many, Bidirectional association between your entities and then in twig you can access peoples for each group
use Doctrine\Common\Collections\ArrayCollection;
class Group
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;
...
    /**
     * @ORM\OneToMany(targetEntity="People", mappedBy="group")
     **/
    private $peoples;
    // ...

    public function __construct() {
        $this->peoples = new ArrayCollection();
    }

}

And in twig you can use length function to get the count of peoples for each group
{% for group in allGroups %}

name: {{group.name}}

date:{{ group.createdAt|date('d-m-Y H:i:s') }}

Number of people: {{ group.peoples|length }}

{% endfor %}

If you don't want to update your entities you can write a join query
$DM = $this->getDoctrine()->getManager();
$peopleRepo = $DM->getRepository('People entity');
$qb = $peopleRepo->createQueryBuilder('p')
    ->select('g.name,g.createdAt,COUNT(p.id) AS total_peoples')
    ->innerJoin('p.group', 'g')
    ->groupBy('g.id')
    ->getQuery()
    ->getArrayResult();

In twig you can loop through your results and display count using total_peoples index

Note this will not return groups that don't have any associated users
  means group with 0 count will not be returned because its an inner
  join , what you need is right join to group entity by unfortunately its not
  possible to have a right join in dql Doctrine DQL RIGHT JOIN?

To achieve your right join thing and sticking to doctrine association you have to implement One-To-Many, Bidirectional

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the fastest and most efficient way of doing bulk updates with the C# MySQL Connector? I need to update around five hundred rows using the C# MySQL Connector/NET after a user posts a form. I'm reusing the same connection, but I'm executing multiple ExecuteNonQuery, and this is giving me a performance problem.
What is the best way / best practices to solve this problem?

*

*Should I create an extremely long SQL string? If so, how do I handle having specific parameter values and variables for each row?

*Is there a streaming interface?

*Is there an optimal bulk interface?

Note that for security reasons, I am preferring to use parameter variables instead of plain-text. E.g. "INSERT INTO xxx (a, b, c) VALUES (@a, @b, @c)", but if this is an impossible constraint let me know.

A: If its only 500 or so rows, i'd be inclined to just build the long SQL string and execute the once
Insert into MyTable (a, b, c) values (1,2,3), (2, 3, 4)

Where you are building the "(1, 2, 3),(2 ,3, 4)" part.

A: You can batch the updates into batches of, say, 50. Build a SQL query for 50 updates with numbered parameter names: INSERT INTO xxx (a, b, c) VALUES (@a_1, @b_1, @c_1). Then you create the parameters with the same names dynamically.
You are saying you need to update but your code shows inserts. If you are really doing inserts, you should probably insert multiple rows with one insert statement (I think MySQL supports that).


text:
Q: Menu Item disappears in VS2008 when I add a width, but appears when I build I'm very confused about this - as I mentioned in the title everything is okay when I build, but when I'm developing the code the fact that what is appearing in Visual Studio is different to what I get when I build is unsettling. Maybe someone can see what is going on?
Basically, I am unable to define widths for menu items or the header text disappears. It works fine when building though. I've included some screenshots and my code to make this easier to understand.
Thanks
With no width defined, the alignment is strange:

If I define a width, the text disappears!

Yet if I do define a width, while the text doesn't appear in Visual Studio when I run the application it does perfectly!

If anyone has any ideas that would be greatly appreciated.


text:
Q: Remove taskbar with registry in windows 7 I'm trying to permanently hide my taskbar. I'd rather not use a different shell or use software to do this for me, so editing the registry seemed a natural choice. Searching the web a bit, I found some guidelines designed for Windows XP.
These guidelines told me to do the following:
[-HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\StuckRects2]

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer]
"NoSetTaskbar"=dword:00000001
"NoTrayItemsDisplay"=dword:00000001
"HideClock"=dword:00000001
"NoToolbarsOnTaskbar"=dword:00000001
"NoTrayContextMenu"=dword:00000001
"NoSaveSettings"=dword:00000000

All of these things seemed to apply to Windows 7 too, so I tried them out. The bottom six settings work fine and removed or disabled what they were meant to remove/disable, but the StuckRects2 key seems to reappear, together with what remains of the taskbar (start button, opened programs, and a button to show desktop).
So are there any more keys that I have to specify to completely remove the taskbar, or is another easy solution (without software/shells) ?
Thanks.

A: Sorry for misunderstanding your query,
The only way to do this would be to completely and entirely stop using Windows Explorer, and use a custom shell to "replace Explorer completely." This means you would no longer have the usual start menu, Explorer windows, etc, and would have to rely entirely on some other piece of software for browsing your file system (I understand that it is not what you prefer, however regedit would not be a total solution to this). Some people do this, and there are replacements available, so if you really want to completely eliminate the Windows taskbar, find and use one of these of your choice.
In order to completely replace Explorer, and have your replacement be the default shell which opens up when you log in, create a REG_SZ value called Shell in [HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Winlogon] using the registry editor. This will "completely replace explorer" for your account, making it unnecessary to use any taskbar hiding/killing techniques.
There is already a SuperUser question discussing the various options.


text:
Q: Android - Masking a View I have a FrameLayout that has a background, and contains a ViewPager that I can slide through Views. I also have a PNG image that I want to use as a mask on the ViewPager, so that I can retain my background, but only show a portion of the ViewPager element. In essence, I want to create a custom masking effect as shown here but instead of applying that to an image, I want to apply that to a View. How can I do this?
I started out with:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:padding="4dip"
        android:gravity="center_horizontal"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <android.support.v4.view.ViewPager
                android:id="@+id/pager"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>

        <ImageView
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:scaleType="fitXY"
            android:src="@drawable/mask"/>

</FrameLayout>

The image I'm using basically has a cutout in the PNG file so there's a transparent portion. The problem with using this technique is there's a portion of the image that has a gradient. By doing a proper mask, I was hoping that characters would "fade" in but instead, it's now just starkly appearing as in you can see the edge of where it appears, so it's not pretty. If anyone has better ideas how to mask it cleanly, I'm open to them...


text:
Q: Error: option 'name' clashes with existing property 'name' on Command Some context: I've recently been trying to update a react native project that uses expo, since I have not worked on the project for about four months. I believe I finally was able to successfully upgrade the project as expo is starting. The issue is that I am now having some trouble with some of the newer modules I just installed with npm. This error seems to be coming from me not knowing how to use the commander module. Additionally, I do not believe that I have a thorough understanding of modulues in react native/expo. I am using ubuntu 20.04 via windows terminal.
Error:

I did go to the website mentioned in the error. I believe that this link - https://github.com/tj/commander.js#avoiding-option-name-clashes - is what will solve my problem. However, I am confused as to where I should put the example file and how to use it.
I am not very well versed in modules for react native/expo and it is quite possible that I do not need to use this module (I thought that installing it would make my react native program run, but that does not seem to be the case).
Thus, I am looking for advice on either how to use this module, or on whether or not I should be using these modules (after updating node and then expo, the following modules could not be found every time I ran npm start, so I decided to install them using sudo npm install module_name -g since some other stackoverflow/github pages recommended that):

*

*fs-extra

*terminal-link

*chalk

*getenv

*commander

*@expo/xdl

Any help would be appreciated, and I would be happy to provide any more information that would be relevant.

A: I was not able to figure out a way to make the project work with the above modules. So, I followed the advice of a post I made on the expo forums (I posted similar context there and also the answer that I wrote below).
If you do not want to click the link, here are the steps below:
Basically, I uninstalled expo using the following command: npm -g uninstall expo-cli --save && yarn global remove expo-cli. Then I proceeded to remove the .expo folder from my home directory. More details on these two steps can be found here.
After that, I reinstalled expo using npm install --global expo-cli, from the expo documentation, in the install section.
Then I closed my terminal, reopened it, and ran expo whoami. The command returned recommending an update, so I followed the provided update command (which I believe was just npm install --global expo-cli again).
I closed the terminal, reopened it, and ran expo whoami again. This time I was just met with "you are not logged into expo" (or something along those lines). So, everything seemed up to date.
I then went to project and ran npm start and it worked fine.
Note: You may need to use sudo for any uninstall and install commands above (your terminal will likely tell you if you do).
Note Clearing cache for npm and yarn may take some time. Additionally, the first time you run npm start may also take some time. I'd say all in all this took about two to three hours, but my computer is also not the best.


text:
Q: Convert all xls files available in a folder into "Google Doc Spreadsheets"? The basic way to do that is turn conversion on when uploading files into Google Drive.
Another way is to select the xls file in the folder and convert it one by one by hand.
But if one has already many xls files uploaded in a folder, it may be faster to convert them with Google Apps Script than re-uploading again the files.
In my case:

*

*once converted, I need to delete the xls files

*all xls files are below the limits : "Uploaded spreadsheet files that are converted to the Google spreadsheets format can't be larger than 100 MB, and need to be under 400,000 cells and 256 columns per sheet."
https://support.google.com/drive/answer/37603?hl=en
Thanks in advance;)

A: you should use the Advanced Drive Service, file update
This service must be enabled before use but the doc is pretty clear.

EDIT (following your comments)
(sorry for the long delay, I forgot this post)
This code will convert every XLS files in your drive to Google spreadsheet format (as long as their names have an .xls extension)
You must authorize the Drive extended ressource + API console (follow the instructions from the ressource/advanced services menu, see illustration below)
function importXLS(){
  var files = DriveApp.searchFiles('title contains ".xls"');// you can also use a folder as starting point and get the files in that folder... use only DriveApp method here.
  while(files.hasNext()){
    var xFile = files.next();
    var name = xFile.getName();
    if (name.indexOf('.xls')>-1){ // this check is not necessaey here because I get the files with a search but I left it in case you get the files differently...
      var ID = xFile.getId();
      var xBlob = xFile.getBlob();
      var newFile = { title : name+'_converted',
                     key : ID
                    }
      file = Drive.Files.insert(newFile, xBlob, {
        convert: true
      });
    }
  }
}


text:
Q: iPhone 6 as Bluetooth A2DP Source in 15.10 I've tried connecting my iPhone 6 as a bluetooth A2DP source (i.e. stream music from it) to my Ubuntu 15.10 laptop (a Dell Latitude E6440), but I can't get it to show up under "Choose a device for sound input" under "Input" in "Sound Settings".
I tried with my Android phone (Sony Xperia Z3 Compact) and it showed up without any problem.
I tried Googling around for a solution to this, but so far I can't find a reason why the iPhone would not show up, nor a workaround to fix it.
Any suggestions?

A: It seems this problem solved itself over time, without me doing anything (other than installing the normal updates). My iPhone now appears as an Input device in sound settings.


text:
Q: SQL: IF NULL THEN '-' ,ELSE condition mo_orders table:
mo_name   admin_id
abcd        2
xyz        NULL

login_details table:
id     username
1       Mark
2       John
3       Bob

I wrote a SQL Statement similar like this (the original one looks different but I want to give an easy example here):
select ld.username
from mo_orders mo inner join login_details ld on mo.admin_id=ld.id;

This Statement does not have any syntax errors but how to write a statement when admin_id is NULL then print '-' else mo.admin_id=ld.id ?

A: If I understand correctly, you want left join with coalesce():
select mo.*, coalesce(ld.username, '-') as username
from mo_orders mo left join
     login_details ld
     on mo.admin_id = ld.id;


text:
Q: Unable to parse AMF model Get error when running Mulesoft app from Anypoint Studio - run the app, clicking console button in Studio opens browser and throws error "Unable to parse AMF model."
Found potential resolution here:
https://help.mulesoft.com/s/article/Unable-to-parse-AMF-model-error-with-APIKit-Console
But I do not know how to get to these option in Anypoint Studio to try and see if they resolve the issue for me.
I get the same error on both Windows and Mac.

A: This was an issue with the router config and the solution shared above from MuleSoft did not work. When pulling an API down from Exchange there was something wrong with the Router. If you are look at the Global Elements tab next to Message Flow in the IDE you should see an entry there for Router. It was almost as if the router didn't exist so I clicked the Create button. Once it was there and I could edit it I selected the option to Keep RAML/OAS base URI and to set the Parser option to AUTO. This resolved the issue for me.


text:
Q: Question on the use of auxiliary verbs In Breaking Bad TV series, there's a conversation between Jesse Pinkman and Saul Goodman:

Jesse: You want a job?
Saul: A job?
Saul: Who's got a job for me?
Jesse: I do.

I'd like to know why he says "I do" in respond to "who has got ...?" and why not "I have"?

A: Because the verb phrase "HAS GOT" (a more informal and, in my opinion, redundant way of saying "HAS") was already mentioned by Saul in "Who'S GOT a job for me?". In English, we respond to a question like this by substituting the verb or verb phrase used with "DO/DOES".
Remember that "has got" here is present simple and not present perfect (don't let the word "has" confuse you). In an interrogative sentence in the present perfect tense, such as:
"Who's cleaned the kitchen?"
The answer will be "I have" and not "I do".


text:
Q: how to test touch events on emulator I have some code to check onTouchEvent on an ImageView
public boolean onTouchEvent(MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN) {
            Log.d("M", "down");
        }
        if(event.getAction() == MotionEvent.ACTION_MOVE) {
            Log.d("M", "moved");
        }
        return super.onTouchEvent(event);
    }

But I am unable to test this on emulator. Can someone help me out

A: Touch events should be emulated already (no pun intended) with the mouse.
Try setting your listener like this:
 yourImageView.setOnTouchListener(new OnTouchListener()
        {
            @Override
            public boolean onTouch(View v, MotionEvent event)
            {
                return false;
            }
       });

Taken from this previous question.


text:
Q: Running just one Test suites with Maven not working I have in my pom.xml two test suites
      <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>3.0.0-M4</version>
    <configuration>
      <suiteXmlFiles>
                    <file>src/test/resources/weekly.xml</file>
                    <file>src/test/resources/monthly.xml</file>

                     <!-- <suiteXmlFile>${suiteXmlFile}</suiteXmlFile>  -->

                </suiteXmlFiles>
            </configuration>
        </plugin>

When I'm trying to run only one from the command line with mnv test -Dsurefire.suiteXmlFile=src/test/resources/monthly.xml
Is running both of them and generate repost for both of them.
How can I run only one xml?

A: I just checked and executed the pom.xml. If you want to pass the xml file location at the runtime, your pom.xml should look like
<plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>3.0.0-M4</version>
                    <configuration>
                        <suiteXmlFiles>
                            <suiteXmlFile>${suiteXmlFile}</suiteXmlFile>
                        </suiteXmlFiles>
                        <source>${java.version}</source>
                        <target>${java.version}</target>
                    </configuration>
                </plugin>

You can use the maven command mentioned as below to execute :
mvn test -DsuiteXmlFile=src/test/resources/.xml


text:
Q: Should I install x86_64 or i386 RPM packages? I want to install an RPM package, but I'm not sure whether to install the x86_64 or i386 version. WHM says CENTOS 6.5 i686 virtuozzo at the top.
How can I determine which version to install?

A: You can simply use the "arch" command in order to have your answer.

A: You need the 32-bit (i.e. the i386) package as the "i686" report shows that you're running a 32-bit platform.
As a general rule, if you're not sure of the destination platform, get the 32-bit build, as a 64-bit platform can run a 32-bit image, but not the other way around.

A: A quick overview of architecture names for x86 systems:

*

*i386: The 80386 CPU has historically been the bare minimum for running Linux on a PC-compatible system.  Consequently, a package for "i386" is designed for maximum compatibility and can run on any x86-like system; a system that describes itself as "i386" is either ancient or exotic, and can only be counted on to run i386 packages.

*i485, i586: Rarely-seen, these refer to the 80486 and Pentium (80586) CPUs.  Almost nobody builds packages specifically for them, targeting either i386 or i686 instead.

*i686: This is the "P6" microarchitecture, used by Intel for the Pentium Pro and newer.  It's generally considered the baseline for "modern" 32-bit x86 systems.  An "i686" package is designed to run on these systems (and will usually perform better than a "i386" version); an "i686" system can run any i386, i486, i586, or i686 package.

*x86_64: This is the 64-bit instruction set for x86 CPUs.  An "x86_64" package can only run on x86_64 systems; an "x86_64" system requires special kernel and library support (which almost all mainstream Linux distros provide) to run packages from the i*86 family.

You've got an "i686" system, so given the choice between "i386" and "x86_64", you want the "i386" version.

A: In this case, use the i386 (or 32-bit) package.


text:
Q: Postgresql Loop with Begin End block inside it is interrupted when the exception is thrown, while it is intercepted; loop should run until the end I have a function like that:
create or replace function produciblepwforregulation(now date, timerange integer, devicename character varying) returns void
    language plpgsql
as $$
BEGIN
    FOR t IN 1..timeRange BY 1
        LOOP
            BEGIN
            insert into values
            (value, time, devicename)
            values (    2200 +
                        600 *
                                round(abs(sin(((t) * 0.042))) + 0.1) *
                                (sin(sin(((t) * 2 / 2.0 / 2.155172413793103 * PI()))) /
                                abs(sin(sin(((t) * 2 / 2.0 / 2.155172413793103 * PI()))))) *
                                (3 - exp(-12.5 + floor((t) * 2 / 2.0 / 2.155172413793103) * 2.155172413793103 * PI() * 2 * round(abs(sin(((t) * 0.042))) + 0.1) - ((t) * 2 * PI())))
                        +
                        600 *
                                abs(round(abs(sin(((t) * 0.042))) + 0.1) - 1) *
                                (sin(sin(((t) / 2.0 / 4.310344827586207 * PI()))) /
                                abs(sin(sin(((t) / 2.0 / 4.310344827586207 * PI()))))) *
                                (3 - exp(-25.5 + floor((t) / 2.0 / 4.310344827586207) * 4.310344827586207 * PI() * 2 * abs(round(abs(sin(((t) * 0.042))) + 0.1) - 1) - ((t) * PI())))
                        + 50 * sin(3 + (t) * 0.092) + 350 * sin(3 + (t) * 0.012),
                    now + t * INTERVAL '1 second' - 1 * INTERVAL '1 milliseconds',
                    devicename);
              EXCEPTION WHEN others THEN NULL;  -- <- here I expect the funtion will just go ahead with its loop
              END;
        END LOOP;
END

$$;

alter function produciblepwforregulation(date, integer, varchar) owner to postgres;

When the function is called, the timerange passed as the parameter in order to expect 86400 steps
  select produciblepwforregulation('2020-11-18', 86400, '1');

However, the execution stops on 194 steps, possibly facing some exception (the function inside is capable for underflow exception). My expectation that the exception just stops the Begin-End block inside the Loop and thus we just switch to another t value in the loop, and the execution shouldn't stop. But it is actually stops and never overcome the t value in the loop that causes the problem.
PS. I know that it is very unoptimized, but I really need got that to be executed as a part of postgresql function.
PPS. I see absolutely no error message here when I call the function execution, so the error (that's according to my expectation is an error) is silent for me:


text:
Q: PHP: Doctrine & twig, many queries executed for joins I've recently started rebuilding a old PHP application using Silex, Doctrine and Twig.
One of the main entities is "issue" (It's a issue tracking system), the issue has relations to many other entities, like "status", "Owner", "creator" , etc.
I've created all entities as doctrime ORM entities and defined all relationships.
From the controller, I fetch one "issue" and send it to the twig template like this:
$issue = $app['orm.em']->getRepository('MMW\Entity\Issue')->find($issueId);

In the twig template i can easily print out the related entities, like:
{{ issue.status.name }}

and
{{ issue.owner.name }}

It works like a charm, but when I enable logging to see what queries are send to the database like this:
$em->getConnection()
  ->getConfiguration()
  ->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger());

I notice that for each join, a separate query is send to the database. I would think that performance wise, one query with SQL joins would be much faster.
Should I build my application in a different way, maybe use the querybuilder in the controller to fetch the exact columns and entities I need? Or is there a way to force doctrine to build the query in a different way?
Or should I just not worry about it and leave it as is...?

A: You should use Doctrine fetch joins to fetch the entire entity and prevent this way to access for every field. I recommend you to read the Doctrine documentation: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html#joins


text:
Q: Some product categories keep loading without results I am uncertain what is happening over here, but it is realy bugging me.
We installed the module Tierprices from MagPleasure (version 1.2.2) on our website, but it seems to load some of our product categories endless.
We disabled and enabled all third party modules to see if this works.
But the results remain the same.
This is what we have tried to make it work:
1. Contacted MagPleasure about this bug (they fixed a lot but couldn't find the issue about this one).
2. Disabled all modules one by one via app/etc/all xml files.
3. Disabled all modules via database.
4. Edited a couple of errors in the log (nothing to worry about and nothing had to do anything with the tierprices).
5. We even changed template to default.
But all for naught.
I hope someone knows anything about this bug/error (nothing specific is reported in the logs) and would mind sharing their experience.
If I find out about anything I will ofcourse report back.
Thanks for the help.
This is one of our endless loading pages: www.dekabelexpert.nl/testlocation/utp-stp-sftp/patchkabels.html


text:
Q: Cast timestamp from ms to string format in Hive 3.1.3 I am trying to convert a milliseconds timestamp into string format while keeping the ms part.
Code below:
select from_unixtime(cast(unix_timestamp(current_timestamp) + regexp_extract(string(current_timestamp),'\.(\d+)$',1) as int), "yyyy-MM-dd HH:mm:ss.SSS") as date_formatted_ms
However I am not getting the ms part in a good format:
How can I fix this?
Thank you


text:
Q: Redux app state via url -> query param Using https://github.com/reactjs/react-router-redux/
If I want to reload app (Redux) state based on url query params is the proper way to do that by getting the state.routing.locationBeforeTransitions.query property?

It works ... just wondering if that's the proper way.

A: Using a Redux connected component you can access the router's props from the 2nd argument of mapStateToProps:
function mapStateToProps (state, ownProps) {
  return {
    num: state.items.num,
    query: ownProps.location.query
  }
}

export default connect(mapStateToProps, null)(YourComponent)

See https://github.com/reactjs/react-router-redux#user-content-how-do-i-access-router-state-in-a-container-component .
You can also check out a demo here https://github.com/timarney/react-router-redux-query-params .

A: From the docs:

You should not read the location state directly from the Redux store. This is because React Router operates asynchronously (to handle things such as dynamically-loaded components) and your component tree may not yet be updated in sync with your Redux state. You should rely on the props passed by React Router, as they are only updated after it has processed all asynchronous code.

The correct way is in the docs, but you can only do that in route components (those that you put in <Route path='/' component={Component} />).
I normally pass down the location property if I want to access it in some inner component.


text:
Q: setup cloud code for Parse.com I have gone through the instruction found on Parse.com to setup Cloud code. I downloaded exe file as instructed in 1. It seems like there is a step missing before step 2.
When i run "parse new" in the command prompt i get "not recognized as an internal or external command". What am i missing? How do i install/use cloud code?

Get the Parse tool

*

*The Parse command line tool for Windows is available here. Download
  the Windows executable named: parse.exe at this link. Note that this
  is not an installer, it is just a plain Windows executable.
Set up a Cloud Code directory.

*From the Command Prompt, run the command parse new and follow
  instructions. In this quickstart we'll see how to set up your server
  code on Heroku. Please read docs for more details.

A: I just downloaded the parse CLI on my Windows desktop to figure it out and I believe I've found your solution.
You need to open up a standard command line on windows and then navigate to where you have stored parse.exe. Once the command line is at the same directory as the exe, you will be able to run parse new and any of the other CLI commands.
For example, you could do the following:

*

*Hit the Windows key (or start menu) and search "cmd" then hit enter to open the command line

*Navigate to where parse.exe is located. If it's on your desktop, it could be something along the lines of cd C:\Users\<name>\Desktop

*parse help, parse new and so on should now work from this directory

The documentation feels a bit vague and could use some clarification for the Windows platform. Hope this helps!


text:
Q: IOS Quartz2D cannot get image from current context What am I missing? Been stuck for several hours, drawRect draws as expected, getTheImage() is called from a viewcontoller UIGraphicsGetImageFromCurrentImageContext() returns nil; tried many variations.
Any help is appreciated.
- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    UIGraphicsBeginImageContext(self.bounds.size);
    CGContextSetLineWidth(context, 5.0);
    CGContextSetStrokeColorWithColor(context, [[UIColor    blackColor]CGColor]);
    CGContextMoveToPoint(context,100.0,100.0);
    CGContextAddLineToPoint(context,200.0,200.0);
    CGContextMoveToPoint(context,200.0,200.0);
    CGContextAddLineToPoint(context,200.0,400.0);
    CGContextStrokePath(context);
}

-(UIImage *)getTheImage
{
    UIImage *drawImage = UIGraphicsGetImageFromCurrentImageContext();
    NSLog(@"drawImage %@",drawImage);
    return drawImage;
}

A: Can you try this?
-(UIImage *)getTheImage
{
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, [UIScreen mainScreen].scale);
    [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES];
    UIImage *drawImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSLog(@"drawImage %@",drawImage);
    return drawImage;
}

A:
You should call this function only when a bitmap-based graphics context is the current graphics context. If the current context is nil or was not created by a call to UIGraphicsBeginImageContext, this function returns nil.

appearantly your call is not in a context.


text:
Q: In a helm template how can i use items in 1 list to iterate over another list i want to pre-populate a kubernetes cluster with namespaces and their respective secrets for our apps and services.
For that i would like to be able to specify 2 lists, 1 list with secrets, and 1 list with namespaces. Each namespace in the list has a list of secrets.
Like this values.yaml:
secrets:
  - name: secret1
    data: key1
  - name: secret2
    data: key2
  - name: secret3
    data: key3

namespaces:
  - name: app1
    secrets:
      - secret1
      - secret2
  - name: app2
    secrets:
      - secret1
      - secret3

Then i want to loop over namespaces to create the namespaces, like:
{{- range $namespaces := .Values.namespaces }}
apiVersion: v1
kind: Namespace
metadata:
  name: {{ $namespaces.name }}
---
{{- end }}

In that loop i want another loop inside this loop that creates the secrets per namespace with the data from the secrets list. A bit like this:
{{- range $secrets := .secrets }}
apiVersion: v1
kind: Secret
metadata:
  name: {{ .name }}
  namespace: {{ $namespaces.name }}
type: kubernetes.io/tls
data: $secrets.data
---
{{- end }}

But if i put that loop inside the namespace loop, it just creates all secrets in the secrets list in all namespaces.
How can i make the loop only create the secrets specified in the namespaces list?
I think it can be done with the go template index function, but i don't know how.

A: I have made reproduction on your problem and find answer for that.
Your example
I used your yamls to create namespaces and changed the second one so it's actually work now.
values.yaml
secrets:
  - name: secret1
    data: key1
  - name: secret2
    data: key2
  - name: secret3
    data: key3

namespaces:
  - name: app1
    secrets:
      - secret1
      - secret2
  - name: app2
    secrets:
      - secret1
      - secret3

templates/namespaces.yaml
{{- range $namespaces := .Values.namespaces }}
apiVersion: v1
kind: Namespace
metadata:
  name: {{ $namespaces.name }}
---
{{- end }}

{{- range $namespace := .Values.namespaces }}
{{- range $secret := $namespace.secrets }}
---
apiVersion: v1
kind: Secret
metadata:
  name: {{ $secret }}
  namespace: {{ $namespace.name }}
type: kubernetes.io/tls
data: $secrets.data
---
{{- end }}
{{- end }}

Result:
COMPUTED VALUES:
namespaces:
- name: app1
  secrets:
  - secret1
  - secret2
- name: app2
  secrets:
  - secret1
  - secret3
secrets:
- data: key1
  name: secret1
- data: key2
  name: secret2
- data: key3
  name: secret3

HOOKS:
MANIFEST:

---
# Source: mychart/templates/namespaces.yaml
apiVersion: v1
kind: Namespace
metadata:
  name: app1
---
# Source: mychart/templates/namespaces.yaml
apiVersion: v1
kind: Namespace
metadata:
  name: app2
---
# Source: mychart/templates/namespaces.yaml
apiVersion: v1
kind: Secret
metadata:
  name: secret1
  namespace: app1
type: kubernetes.io/tls
data: $secrets.data
---
# Source: mychart/templates/namespaces.yaml
apiVersion: v1
kind: Secret
metadata:
  name: secret2
  namespace: app1
type: kubernetes.io/tls
data: $secrets.data
---
# Source: mychart/templates/namespaces.yaml
apiVersion: v1
kind: Secret
metadata:
  name: secret1
  namespace: app2
type: kubernetes.io/tls
data: $secrets.data
---
# Source: mychart/templates/namespaces.yaml
apiVersion: v1
kind: Secret
metadata:
  name: secret3
  namespace: app2
type: kubernetes.io/tls
data: $secrets.data

My idea of doing that
Instead of creating secrets for namespaces, do it the other way around, create secrets and add namespaces to them.
values.yaml
Secret1:
- namespace1
- namespace2

Secret2:
- namespace2

templates/namespaces.yaml
{{- range $namespaces := .Values.namespaces }}
apiVersion: v1
kind: Namespace
metadata:
  name: {{ $namespaces.name }}
---
{{- end }}

templates/secrets.yaml
{{- range .Values.Secret1 }}
---
apiVersion: v1
data:
  password: MWYyZDFlMmU2N2Rm
  username: YWRtaW4=
kind: Secret
metadata:
  creationTimestamp: null
  name: secret1
  namespace: {{ . }}
{{- end}}
{{- range .Values.Secret2 }}
---
apiVersion: v1
data:
  password: MWYyZDFlMmU2N2Rm
  username: YWRtaW4=
kind: Secret
metadata:
  creationTimestamp: null
  name: secret2
  namespace: {{ . }}
{{- end}}

Result:
COMPUTED VALUES:
Secret1:
- namespace1
- namespace2
Secret2:
- namespace2
namespaces:
- name: namespace1
- name: namespace2

HOOKS:
MANIFEST:

---
# Source: mychart/templates/namespaces2.yaml
apiVersion: v1
kind: Namespace
metadata:
  name: namespace1
---
# Source: mychart/templates/namespaces2.yaml
apiVersion: v1
kind: Namespace
metadata:
  name: namespace2
---
# Source: mychart/templates/namespaces.yaml
apiVersion: v1
data:
  password: UyFCXCpkJHpEc2I=
  username: ZGV2dXNlcg==
kind: Secret
metadata:
  creationTimestamp: null
  name: secret1
  namespace: namespace2
---
# Source: mychart/templates/namespaces.yaml
apiVersion: v1
data:
  password: ZGV2dXNlcg==
  username: UyFCXCpkJHpEc2I=
kind: Secret
metadata:
  creationTimestamp: null
  name: secret2
  namespace: namespace2
---
# Source: mychart/templates/namespaces.yaml
apiVersion: v1
data:
  password: UyFCXCpkJHpEc2I=
  username: ZGV2dXNlcg==
kind: Secret
metadata:
  creationTimestamp: null
  name: secret1
  namespace: namespace1

More informations about Flow Control(if,else if,range) can be found here.

A: I found this post very usefull.
I need a bit different usecase that i couldn't achieve as of now.
Values.yaml
    customCerts:
  - name: test
    secrets:
      tls.crt: |
        -----BEGIN CERTIFICATE-----
        xxxx
        -----END CERTIFICATE-----
      tls.key: |
        -----BEGIN RSA PRIVATE KEY-----
        xxxx
        -----END RSA PRIVATE KEY-----
  - name: test2
    secrets:
      tls.crt: |
        -----BEGIN CERTIFICATE-----
        xxxx
        -----END CERTIFICATE-----
      tls.key: |
        -----BEGIN RSA PRIVATE KEY-----
        xxxx
        -----END RSA PRIVATE KEY-----

Secret.yaml
{{- range $customCerts := .Values.customCerts }}
---
apiVersion: v1
kind: Secret
metadata:
  name: {{ .name }}
  namespace: {{ .Release.Namespace }}
stringData:
  {{ .secrets  | indent 2 }}
---
{{- end }}

I have 2 problems:

*

*.Release.Namespace doesn't work inside the {{ range }}

*I can't manage to get the secret with {{ .secrets }}

Edit:
I fixed the problem with .Release.Namespace by adding this at the beginning: {{- $root := . -}}  and then use {{ $root.Release.Namespace }}

*

*But i still couldn't fill the secret with the tls.key and tls.crt entries

Edit 2:
i'm now able to list the secrets, but i can't remove the '|' character :
values.yaml:
customCerts:
  - name: test
    secrets: |
      tls.crt: |
        -----BEGIN CERTIFICATE-----
        xxxx
        -----END CERTIFICATE-----
      tls.key: |
        -----BEGIN RSA PRIVATE KEY-----
        xxxx
        -----END RSA PRIVATE KEY-----
  - name: test2
    secrets: |
      tls.crt: |
        -----BEGIN CERTIFICATE-----
        xxxx
        -----END CERTIFICATE-----
      tls.key: |
        -----BEGIN RSA PRIVATE KEY-----
        xxxx
        -----END RSA PRIVATE KEY-----

secrets.yaml:
{{- $root := . -}}
{{- range $customCerts := .Values.customCerts }}
---
apiVersion: v1
kind: Secret
metadata:
  name: {{ .name }}
  namespace: {{ $root.Release.Namespace }}
stringData:
  {{ toYaml .secrets }}
---
{{- end }}

Output:
# Source: ciam-app/templates/secretsCustomCerts.yaml
apiVersion: v1
kind: Secret
metadata:
  name: test
  namespace: qbel1-ciam
stringData:
  |
  tls.crt: |
    -----BEGIN CERTIFICATE-----
    xxxx
    -----END CERTIFICATE-----
  tls.key: |
    -----BEGIN RSA PRIVATE KEY-----
    xxxx
    -----END RSA PRIVATE KEY-----
---
# Source: ciam-app/templates/secretsCustomCerts.yaml
---
apiVersion: v1
kind: Secret
metadata:
  name: test2
  namespace: qbel1-ciam
stringData:
  |
  tls.crt: |
    -----BEGIN CERTIFICATE-----
    xxxx
    -----END CERTIFICATE-----
  tls.key: |
    -----BEGIN RSA PRIVATE KEY-----
    xxxx
    -----END RSA PRIVATE KEY-----

I can't get rid of the | after stringData
Edit 3:
I finally found a way :
  {{ toYaml .secrets | trimPrefix "|" | trim }}

Maybe that will help someone else.


text:
Q: Is it possible to autosave temporary buffers that are not visiting a file? Suppose I'm entering a bunch of text in a buffer that's not visiting a file (it could be a new org2blog post, or just some scratch buffer).  Is it possible to autosave it somewhere in case disaster strikes and Emacs dies?

A: phils' answer cleared things up for me, but I ended up using a somewhat different approach. I am posting it as a separate answer for documentation's sake.  Here is my autosave stanza:
;; Put autosave files (ie #foo#) in one place
(defvar autosave-dir (concat "~/.emacs.d/autosave.1"))
(defvar autosave-dir-nonfile (concat "~/.emacs.d/autosave.nonfile"))
(make-directory autosave-dir t)
(make-directory autosave-dir-nonfile t)
(defun auto-save-file-name-p (filename) (string-match "^#.*#$" (file-name-nondirectory filename)))
(defun make-auto-save-file-name ()
  (if buffer-file-name (concat autosave-dir "/" "#" (file-name-nondirectory buffer-file-name) "#")
    (expand-file-name (concat autosave-dir-nonfile "/" "#%"
                              (replace-regexp-in-string "[*]\\|/" "" (buffer-name)) "#"))))

Creating a separate directory for the non-visited file buffers is optional in this context; they could as well go in the centralized location (in this case, autosave-dir).  Note also that I have to do some basic file name cleanup in case the temporary buffer name is something like "*foo/bar*" (with stars and/or slashes).
Finally, one can automatically turn on autosave in certain modes' temp buffers using something like
(add-hook 'org2blog/wp-mode-hook '(lambda () (auto-save-mode t)))

A: auto-save-mode actually works with non-file buffers. It just doesn't get enabled by default -- that usually happens in (after-find-file).
So: M-x auto-save-mode RET
By default the auto-save file will be written to the default-directory of the buffer (or /var/tmp or ~/, depending on write permissions; see C-hv buffer-auto-save-file-name RET) which may be a little awkward to figure out after a crash, so setting that to something standard is probably a good idea.
The following would ensure that these auto-save files are written to your home directory (or M-x customize-variable RET my-non-file-buffer-auto-save-dir RET), if auto-save-mode is invoked interactively. That will hopefully avoid this conflicting with any other uses of auto-save-mode with non-file buffers (the code mentions Mail mode, for instance).
(defcustom my-non-file-buffer-auto-save-dir (expand-file-name "~/")
  "Directory in which to store auto-save files for non-file buffers,
when `auto-save-mode' is invoked manually.")

(defadvice auto-save-mode (around use-my-non-file-buffer-auto-save-dir)
  "Use a standard location for auto-save files for non-file buffers"
  (if (and (not buffer-file-name)
           (called-interactively-p 'any))
      (let ((default-directory my-non-file-buffer-auto-save-dir))
        ad-do-it)
    ad-do-it))
(ad-activate 'auto-save-mode)


text:
Q: Form is not submitting in jQuery ajax success I am making a simple form of single text input.I want to cross check from db that is it exist or not.So my html is
<form action="zoneAdd" method="post"  id="zoneAdd" name="zoneAdd">

                    Zone Name*
                    <input type="text" class="form-control" name="zone_name" id="zone_name" placeholder="Enter Zone Name" />

                <input type="submit" class="btn btn-primary btn-flat btn-sm" name="submit" value="Submit"/>

        </form>

and my javasript is
 $('document').ready(function(){
    $("[name=submit]").click(function(e){
         e.preventDefault();
        if ($('#zone_name').val().length <= 0) {
            $('#zone_name').addClass("errMsg");
            $('#zone_name_error').addClass("errMsgDngr");
            $('#zone_name_error').html('Please enter Zone name!');
            //isStepValid = false;
        }
        else if(!$('#zone_name').val().match(/^[a-zA-Z\s-, ]+$/)){
            $('#zone_name').addClass("errMsg");
            $('#zone_name_error').addClass("errMsgDngr");
            $('#zone_name_error').html('Please use only alphabats!');
            //isStepValid = false;
        }else{
            var data = {'zone':$('#zone_name').val()}
            $.ajax({
                type:"post",
                data:data,
                url:"<?php echo site_url('zone/checkZoneName');?>",
                success:function(err){
                    if(err == 0)
                    {
                        console.log('hello');
                        $('#zone_name_error').html('');
                        $('#zone_name_error').removeClass("errMsg");
                        $('#zone_name_error').removeClass("errMsgDngr");
                        //document.forms["zoneAdd"].submit();
                        $('form#zoneAdd').submit();
                        //console.log($('form#zoneAdd').submit());
                    }
                    else
                    {
                        $('#zone_name').addClass("errMsg");
                        $('#zone_name_error').addClass("errMsgDngr");
                        $('#zone_name_error').html('Zone Name already existed!');
                    }
                }
            });
        }

    });
});

every thing is going right. My problem is my form is not submit in ajax success

A: I think problem in form action.
Specify exact path in the form action such that
<form action="<?php echo site_url('filenameWhereyouSubmit')?>"        method="post"  id="zoneAdd" name="zoneAdd">

A: Start form like this :
  <form id="FORM-ID" method="post" action="">

For ajax submit
$(document).ready(function(){
     $('#FORM-ID').submit(function(e) {

        var myarray=  array of all form values
        var data = JSON.stringify(myarray);

        e.preventDefault();

        $.ajax({
        type: "POST",
        data: {value:data},
        url: "URL TO SUBMIT",
        success: function() {
             //Sucess function
        }

    });
 });

A: *

*You don't have a handler function on form submit and your ajax call
happens after $("[name=submit]").click().

*You're submitting the form after ajax success:
success:function(err){
        if(err == 0)
            {
               ...
               $('form#zoneAdd').submit();
               ...
            }

   }

*but the submit is not ajax call, so try to handle the form
onsubmit.

something like this:
$('document').ready(function(){
    $('form#zoneAdd').submit(function(e){
         e.preventDefault();

         // You checks code ...

         var data = {
               'zone': $('#zone_name').val()
             };

         $.ajax({

                type:"post",
                data:data,
                url:"<?php echo site_url('zone/checkZoneName');?>",
                success: function (err){

                    if(err == 0)
                    {
                        console.log('hello');
                        $('#zone_name_error').html('');
                        $('#zone_name_error').removeClass("errMsg");
                        $('#zone_name_error').removeClass("errMsgDngr");
                    }
                    else
                    {
                        $('#zone_name').addClass("errMsg");
                        $('#zone_name_error').addClass("errMsgDngr");
                        $('#zone_name_error').html('Zone Name already existed!');
                    }

                }
         });

    });
});


text:
Q: How to apply dynamic content with dynamic content on page? Ionic 3 & angular 4 I'm working on an ionic 3 app.
So I already have a page that has data that is dynamic (The data pulls fine i.e. names and page). If you look at the code you'll notice that each "childStuff" has the same "childPage". My question is how do I get each "childStuff" to determine what is shown on "childPage"?
A real life example would be each of these "childStuff" is the name of a city and that city has information about it. "childPage" is layed out exactly the same for the data of each "childStuff". So what I want is when I tap (for example) Miami, "childPage" shows "Miami, X number of people live here." But when I tap Cleveland, "childPage" shows "Cleveland, XA number of people live here."
So basically I want the parent page to be able to say "When 'childStuff(instance 1) is tapped show the information pertaining to 'childStuff(instance 1) on 'childPage'"
Does that make sense?
Typescript - HTML

import { Component } from '@angular/core';
import { Nav, Platform, NavController } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

import { NewPage } from '../new/new';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})

export class HomePage {
  childStuff: Array<{name: string, childPage: any}>;

  constructor(public navCtrl: NavController) {
      this.childStuff= [
        {
          name: 'new',
          childPage: NewPage
        },{
          name: 'new2',
          childPage: NewPage
        },{
          name: 'new3',
          childPage: NewPage
        },{
          name: 'new4',
          childPage: NewPage
        },{
          name: 'new5',
          childPage: NewPage
        },{
          name: 'new6',
          childPage: NewPage
        },{
          name: 'new7',
          childPage: NewPage
        },{
          name: 'new8',
          childPage: NewPage
        }
      ];
  }

  goToNewPage(page) {
    //push another page onto the history stack
    //causing the nav controller to animate the new page in
    this.navCtrl.push(page.childPage);
  }

}

{{c.name}}

A: Basically, the beauty of a component-based framework is to have a lot of reusable components. You don't want to have a separate components for each city. You'd simply have the same CityPage and just pass params to the navCtrl.push() method:
goToNewPage(params) {
    this.navCtrl.push(CityPage, params);
}

And on the CityPage you'd handle the input params and structure your view accordingly.
import { NavParams } from 'ionic-angular';

@Component({
  template: `
  <ion-header>
    <ion-navbar>
      <ion-title>City Page</ion-title>
    </ion-navbar>
  </ion-header>
  <ion-content>I'm the other page!</ion-content>`
})
class CityPage {
  constructor(private navParams: NavParams) {
     let city = navParams.get('city');
     let population = navParams.get('population');
  }
}

This will help: https://ionicframework.com/docs/api/navigation/NavController/
UPDATE
In your parent component you can store parameters:
this.childStuff= [
    {
      city: 'Miami',
      population: 500000
    },{
      city: 'Cleaveland',
      population: 40000
    }
  ];


text:
Q: Using Streambuilder with Flutter and GoRouter to persist User State Anyone used Streambuilder with Flutter and GoRouter before to persist User state?
Currently, I'm using the default Flutter navigation and it's working fine (see below) but I'm trying to replace with GoRouter now
My previous navigation setup using default Flutter navigation
home: StreamBuilder(
           stream: AuthMethods().authChanges,
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(
              child: CircularProgressIndicator(),
               );
             }

             if (snapshot.hasData) {
               return const TabsScreen();
            }

            return const AuthScreen();
           }),
    );
   }

My current goRouter code. I'm wondering where I can use Streambuilder in d code below to persist user state for my app (or whether Streambuilder can be used at all with go router)
GoRouter routeConstruct() {
  return GoRouter(
    routes: <RouteBase>[
      GoRoute(
          path: '/',
          builder: (BuildContext context, GoRouterState state) {
            return const PublicScreen();
          },
          routes: <RouteBase>[
            GoRoute(
              path: Events_Screen,
              builder: (BuildContext context, GoRouterState state) {
                return const EventsScreen();
              },
            ),
            GoRoute(
              path: "$EventDetail_Screen/:eventId",
              builder: (BuildContext context, GoRouterState state) {
                return EventDetailScreen(eventId: state.params['eventId']!);
              },
            ),
            ...
          ]),
    ],
  );

Can I use Streambuilder with Flutter and GoRouter to persist User authentication state? If can, where in the goRouter code can I use Streambuilder to determine which widget to show based on Auth state? Thanks
###########################
class AuthMethods
class AuthMethods {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  final FirebaseFirestore _firestore = FirebaseFirestore.instance;

  Stream<User?> get authChanges => _auth.authStateChanges();
// --> use of bang ! operator here
  User get user => _auth.currentUser!;

  Future<bool> signInWithGoogle(BuildContext context) async {
    bool res = false;

    try {
      final GoogleSignInAccount? googleUser = await GoogleSignIn().signIn();
      final GoogleSignInAuthentication? googleAuth =
          await googleUser?.authentication;

      final credential = GoogleAuthProvider.credential(
          accessToken: googleAuth?.accessToken, idToken: googleAuth?.idToken);

      UserCredential userCredential =
          await _auth.signInWithCredential(credential);

      User? user = userCredential.user;

      if (user != null) {
        if (userCredential.additionalUserInfo!.isNewUser) {
          await _firestore.collection('users').doc(user.uid).set({
            'username': user.displayName,
            'uid': user.uid,
            'profilePhoto': user.photoURL,
          });
        }
        res = true;
      }
    } on FirebaseAuthException catch (e) {
      showSnackBar(context, e.message!);
      res = false;
    }
    return res;
  }

class RouteNotifier
class RouterNotifier extends ChangeNotifier {
  RouterNotifier(this._authMethods) {
    _authMethods.authChanges.listen((event) {
      notifyListeners();
    });
  }

  final AuthMethods _authMethods;

  String? redirect(BuildContext context, GoRouterState state) {
    final onLoginPage = state.location == '/$AuthScreen';
    final onHomePage = state.location == '/$Tabs_Screen';

// --> The getter 'isEmpty' isn't defined for the type 'User'.
// --> User get user => _auth.currentUser!; used a bang operator
    if (_authMethods.user.isEmpty && onHomePage) {
      return '/$AuthScreen';
    }

// --> The getter 'isEmpty' isn't defined for the type 'User'.
    if (_authMethods.currentUser.isNotEmpty && onLoginPage) {
      return '/$Tabs_Screen';
    }

    return null;
  }
}

router.dart
GoRouter routeConstruct() {
  return GoRouter(
    refreshListenable: router,

    routes: <RouteBase>[
      GoRoute(
          path: '/',
          builder: (BuildContext context, GoRouterState state) {
            return const PublicScreen();
          },
          routes: <RouteBase>[
            GoRoute(
              path: Events_Screen,
              builder: (BuildContext context, GoRouterState state) {
                return const EventsScreen();
              },
            ),
            GoRoute(
              path: "$EventDetail_Screen/:eventId",
              builder: (BuildContext context, GoRouterState state) {
                return EventDetailScreen(eventId: state.params['eventId']!);
              },
            ),
          ]),
    ],
  );
}

A: before go router 5.0.0 :
go router has class called GoRouterRefreshStream, so in go router
GoRouter (
....
refreshListenable: GoRouterRefreshStream(AuthMethods().authChanges),

but after go router 5.0.0, they remove it
so you must create your own notifier :
class RouterNotifier extends ChangeNotifier {

  RouterNotifier(this._authMethods) {
    _authMethods.authChanges.listen((event) {
      notifyListeners();
    });
  }

  final AuthMethods _authMethods;
}

on go Router:
GoRouter(
      debugLogDiagnostics: false,
      ....
      ...
      refreshListenable: RouterNotifier(AuthMethods()),
      ...
      );

and how go router can work like stream builder you use before?

redirect come in handy:
final router  = RouterNotifier(AuthMethods());

GoRouter (
...
refreshListenable: router,
redirect: router.redirect,

in RouterNotifier class :
class RouterNotifier extends ChangeNotifier {

      RouterNotifier(this._authMethods) {
        _authMethods.authChanges.listen((event) {
          notifyListeners();
        });
      }

      final AuthMethods _authMethods;

    String? redirect(BuildContext context, GoRouterState state) {

    final onLoginPage = state.location == '/login';
    final onHomePage = state.location == '/';

    if (_authMethods.currentUser.isEmpty && onHomePage) {

      return '/login';
    }

    if (_authMethods.currentUser.isNotEmpty && onLoginPage) {

      return '/';
    }

    return null;
  }

}
class User model :
class User {

String id;
.........
some variable i need from db;

static const empty = User(id: '');

bool get isEmpty => this == User.empty;
bool get isNotEmpty => this != User.empty;

}

on Stream :
Stream<User> get user {
    // map the user if user null is mean empty
    return _firebaseAuth.authStateChanges().asyncMap((fUser) async {

      if (fUser == null) {
      const User user = User.empty;
      return user;
      } else {
      // in my case i need to take some data from Firestore
      ....
      await datafromDb() // if you dont need to wait future, remove async map, just use normal map
      return fUser.withBiodata();


text:
Q: Accessing option page localStorage from content script I'm trying to code a simple chrome extension but I'm experiencing some difficulty when trying to access the options.html's local storage from my content script "auto.js".
From what i've gathered (googling and reading Chrome's confusing documentation) this is only possible using:
chrome.runtime.sendMessage & chrome.runtime.onMessage.addListener

Content script "auto.js":
var quantity   = ""
var shoe_size  = ""

function addToCart() {

chrome.runtime.sendMessage({localstorage: "qty"}), function(response){
    var quantity = response.qty;
}

chrome.runtime.sendMessage({localstorage: "size"}), function(response){
    var shoe_size = response.size;
}
...

My listener in "options.js":
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse){

  if(request.localstorage == "qty")
    sendResponse({qty: localStorage.qty});
  else if(request.localstorage == "size")
    sendResponse({size: localStorage.size});
  else
    sendResponse({});
});
...

The problem is my vars quantity & shoe_size are never set to the 'returned' values from the html local storage.
There are no errors given in my js console and i'm not sure on how to debug this. Any feedback is greatly appreciated.

A: That is because codes after sendMessage is run right after sendMessage is triggered. They ARE set but it wont wait for response, they are set after the time you need them. I had the same problem with this here Synchronously get Stored data from content scripts. To solve it you can put whatever function you want inside
chrome.runtime.sendMessage({localstorage: "qty"}), function(response){
    var quantity = response.qty;
}

in order to see that it is set, test this:
chrome.runtime.sendMessage({localstorage: "qty"}), function(response){
    var quantity = response.qty;
}

alert("waiting for a second, to make sure that response is ready ...");
alert("Not it is set:" + quantity);

A: You're writing var quantity = response.qty; with a preceding var inside the sendMessage callback function. That will create a local variable with, coincidentally, the same name as the global variable. But it's a different variable. And the memory storing it will be freed as soon as sendMessage is finished, because this is only a local scope.
Leave the var away inside sendMessage.
Also, you're missing the semicolons on those global vars.
var quantity   = "";
var shoe_size  = "";

Other than that, you can use console.log in your content script 'auto.js', inside the sendMessage callback function. It will land in the console of whatever webpage is loading that script.


text:
Q: Windows Server 2012 : Selected server has pending reboots and does not clear when rebooted Similar to the issue here, I am blocked from Deploying what used to be called Terminal Server, and is now (confusingly) called a "Session Based Desktop Deployment" scenario within the context of the Add Roles and Features Wizard, under the top level service named "Remote Desktop Services".
I select Quick Start, and I get this far: The server has reboots pending...
The link in the question above shows that you should remove a registry key. I did that, and the error is still not going away, and I have rebooted seven times, and still the error is not going away. I am getting a bit frustrated. Any ideas?

A: For a while I thought the role is already installed, but that's only one of dozens of obvious checks that the RDS/TS Deployment features in WS2012 do not do properly.  If you get part way through the RDS deployment and it bails out due to an error, you will be stuck here.
My RDS role was partially installed, but not installed enough that you can confirm a role deployment from powershell, with the following command:
PS C:\Users\myname > get-RDLicenseConfiguration
get-RDLicenseConfiguration : A Remote Desktop Services deployment does not exist on servername.domain.local. This
operation can be performed after creating a deployment. For information about creating a deployment, run "Get-Help
Set-VDIDeployment" or "Get-Help Set-RDSHDeployment".
At line:1 char:1
+ get-RDLicenseConfiguration
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Get-RDLicenseConfiguration

Here are the problems in the order that I hit them, and how I ended up thinking I was stuck where I thought I was stuck above: Trying to deploy the RDS role appears blocked on a reboot when the real problem is that the RDS role is already mostly installed, although one or more role services are not. In other words, when a feature that a normal human being wants to deploy on a computer is composed of so many little "tiny installable bits" and some are installed, and some are not, you get into a state that they did not plan for or test for. This is one of those states.
FIX PART 1:
There is a registry key that  is >0 when the system needs a reboot. It was NOT getting cleared.
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\ServerManager

Look for key named CurrentRebootAttempts and if >0 then change to zero.
Second half of the problem has to do with the Remote Desktop licensing system has a Grace Period, a way of getting you out of the box and up and running without exposing you to one of Microsoft's worst and most annoying licensing systems ever (RDS licensing), when this Grace Period ends, and licensing is properly configured, Microsoft's own tools are supposed to delete a registry key that says "Grace Period".  However, Microsoft's own people have configured that registry key so that it has permissions that not even Microsoft's tools can overcome, it cannot be deleted, in short, and you end up stuck where I'm stuck.  It looks like Licensing services were not installed, licensing modes were not configured, and licensing roles were not deployed, when in fact they were, and the real problem is that Microsoft's product (Windows Server 2012) is broken, and is lying to you.
FIX PART 2:
Deploy RDS licensing from powershell, run powershell as Administrator, and type, obviously changing servername.domain.local to your own FQDN:
import-module RemoteDesktop
New-SessionDeployment -ConnectionBroker servername.domain.local

When prompted, answer values shown here:
Supply values for the following parameters:
 - WebAccessServer: servername.domain.local
 - SessionHost[0]: servername.domain.local
 - SessionHost[1]:     (press enter, but don't type anything here)
Finally, run  Get-RDLicenseConfiguration and if not configured, use this command to configure licensing mode:
Set-RDLicenseConfiguration -LicenseServer host.domain.local  -Mode PerUser -ConnectionBroker host.domain.local

A: One other possible cause for these messages is a Pending File Rename operation that is not clearing out.
From here: http://www.virtualizationadmin.com/kbase/VirtualizationTips/DesktopVirtualization/MicrosoftVirtualDesktopInfrastructureTips/General/SolvethependingrebooterrorinRDSdeploymentsRDMSinWindowsServer2012.html

In that case the obvious remedy is of course to reboot the server. If that does not help, check if the key:
"HKLM\System\CurrentControlSet\Control\Session Manager\PendingFileRenameOperations"
exists, if so delete it and try again. Of course it is recommended to back up the registry before doing so.

When the above solution didn't work, this ended up being the fix in my specific case.

A: This worked for me on server 2012 R2 preview:
Solve the pending reboot error in RDS deployments (RDMS) in Windows Server 2012


text:
Q: How to change google cloud platform account from company to personal, or how to delete company account created by mistake? I already have a google cloud platform account from my personal mail.
As I just joined a new company, I got a google mail account and thought I could use it to create another google cloud platform account (for creating projects and using some google APIs).
I don't remember how I created this new account or if I selected "company" or "individual", but I suspect I selected "company". Now, google asks me to verify the "organisation" with the company domain! I won't do this obviously, so I am wondering how I can switch it to "individual"! How to do this?
My other idea is to delete and create back.
I have tried to delete the account using this link (delete your organization's google account).
I have been able to remove my personal billing account, delete the automatically created project but I cannot do the step 6: completely closing the account (so I can repurpose it to create an "individual" account instead)! Step 6 did not work because I could not sign in to the admin account.
Any help would be super appreciated I am banging my head for 2 hours for this since this morning!

A: Account you've been assigned probably belongs to a Google Workspace or Cloud Identity.
As suggested in the comment, you should contact your Organization Administrator.
You can look for that role on the IAM page.


text:
Q: Are antagonistic viewpoints welcome on SE? Christianity.SE is IMO very different from other SE sites, because its subject is religious, and thus very prone to antagonistic viewpoints (like mine). I obviously expected my opinion to be not welcome there:

But I've been noticing also that my comments are disappearing (the post itself was also deleted). So, are antagonistic viewpoints welcome on SE sites like Christianity.SE?

A: Your question is based on a flawed premise.
In the comments, random linked to a meta discussion for Christianity.SE that clearly spells out why comments are being deleted: it's not about you having antagonistic viewpoints, but about keeping the site clean of off-topic and tangential discussions.
You link to a screenshot of downvotes you've received: you have no proof that people are downvoting you because you have an antagonistic viewpoint. You could have just as easily been downvoted because people view your posts to be wrong or not useful. This isn't Reddit: merely having an opinion doesn't mean people should or will up-vote you.
It's easy to dismiss negative feedback as "oh these people are just trying to supress my viewpoints", but I guarantee you will find Stack Exchange more enriching and rewarding if you take the negative feedback you received, consider it given in good faith, and see how you can improve on what you've been doing.

A: Writing on the wall
So you didn't expect your opinion to be welcome, observed that your opinion was not welcome, and you've now come here to ask us if your opinion is welcome?
Oh, what the hell. Yes, your opinion is welcome. Because SE sites luuuuurve opinions. There's even a close reason that mentions them, because we want them so badly. The more antagonistic, the better. Nothing we want more than some good ol' content-free flame-wars - this "useful Q&A" shtick just gets so boring!  Please, jump on the next new SE site you see and share some opinions.
Or, y'know, read the FAQs, note the response that posting flame-bait garners, and adjust your behavior accordingly.

A: I'm not a friend of organized religion, have nothing invested in Christianity.SE and probably never will, but what's the point of participating in a Christianity related site if you're an atheist?
It's like being fundamentally, totally opposed to every aspect of programming but still participating in Stack Overflow (or programmers.SE). It doesn't work.
As far as I'm concerned, unless one intends to contribute something truly constructive, one should not contribute to the religion sites at all.


text:
Q: When to use different request methods in spring I've been tasked with creating a simple REST API, where a single double is provided, and another one is derived from it according to some rules.
When creating a controller, I made the method for parsing said base double in two ways.
@GetMapping("calculate/{income:.+}")
public ResponseEntity<?> calculateEAT(@PathVariable double income){
  return ResponseEntity.ok(TaxDAO.addResult(income));
}

@PostMapping("calculate/{income:.+}")
public ResponseEntity<?> calculateEAT(@PathVariable double income){
  return ResponseEntity.ok(TaxDAO.addResult(income));
}

The only difference is the type of mapping used. The only difference I noticed was that I could type income in the browser address bar with GET mapping - and it worked. With post mapping, I could only get results using Postman.
I'm assuming it's possible to write an entire controller using GET mapping. I don't really feel like it's a good practice though. Are there any rules for using Request Methods in controllers?

A: GET and POST requests are different HTTP methods. The browser will do a GET request when you type something in the browser address bar, that is why you can only make it work in Postman (where you can select which HTTP method to use).
You should use GET when you want to retrieve something from the REST API. You should use POST when you want to submit something to the REST API, usually creating a resource or triggering some kind of process. You can read more about each HTTP method in the following online resources:

*

*https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods

*https://www.restapitutorial.com/lessons/httpmethods.html


text:
Q: How to stop adding and removing an object? I'm making a like button for my app and I want a way to make it so that it doesn't crash if you click the button before it's done saving. I've tried many things but they don't seem to work, but basically what's happening is the app crashes if it isn't done adding or removing the userId...
func like(sender: UIButton) {

    var buttonPosition: CGPoint = sender.convertPoint(CGPointZero, toView: self.table)

    var indexPath: NSIndexPath = self.table.indexPathForRowAtPoint(buttonPosition)!

    testConnection()

    var post = posts[indexPath.row]

    var postCell = PostCell()

    if sender.currentTitle == "Unlike" {

        dispatch_async(dispatch_get_main_queue()) {

            sender.setTitle("Like", forState: .Normal)

            post.removeObject(PFUser.currentUser()!.objectId!, forKey: "likers")

            self.liked[indexPath.row] = true

            self.table.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None)

            post.saveInBackgroundWithBlock({ (success, error) -> Void in

            })

        }
    } else {

        dispatch_async(dispatch_get_main_queue()) {

            sender.setTitle("Unlike", forState: .Normal)

            post.addUniqueObject(PFUser.currentUser()!.objectId!, forKey: "likers")

            self.liked[indexPath.row] = true

            self.table.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None)

            post.saveInBackgroundWithBlock({ (success, error) -> Void in

            })
        }
    }
}

Here is my crash log...
Terminating app due to uncaught exception 'NSInternalInconsistencyException',        reason: 'Operation is invalid after previous operation.'
*** First throw call stack:
(
    0   CoreFoundation                      0x000000010821ec65 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x0000000107eb5bb7 objc_exception_throw + 45
    2   AppName                               0x0000000105251e39 -[PFAddUniqueOperation applyToValue:forKey:ofObject:] + 0
    3   AppName                               0x000000010526f9be -[PFObject(Private) performOperation:forKey:] + 287
    4   AppName                               0x00000001052785a6 -[PFObject addUniqueObjectsFromArray:forKey:] + 126
    5   AppName                               0x000000010527850c -[PFObject addUniqueObject:forKey:] + 126
    6   AppName                               0x0000000105205348 _TTSf2n_d_i_n_d_i___TFFC5AppName4Feed4likeFS0_FCSo8UIButtonT_U0_FT_T_ + 968
    7   AppName                               0x00000001051f2347 _TTRXFo__dT__XFdCb__dT__ + 39
    8   libdispatch.dylib                   0x0000000108acd186 _dispatch_call_block_and_release + 12
    9   libdispatch.dylib                   0x0000000108aec614 _dispatch_client_callout + 8
    10  libdispatch.dylib                   0x0000000108ad4a1c _dispatch_main_queue_callback_4CF + 1664
    11  CoreFoundation                      0x00000001081861f9 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9
    12  CoreFoundation                      0x0000000108147dcb __CFRunLoopRun + 2043
    13  CoreFoundation                      0x0000000108147366 CFRunLoopRunSpecific + 470
    14  GraphicsServices                    0x00000001098e1a3e GSEventRunModal + 161
    15  UIKit                               0x0000000106a528c0 UIApplicationMain + 1282
    16  AppName                               0x000000010520da57 main + 135
    17  libdyld.dylib                       0x0000000108b21145 start + 1
    18  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)


text:
Q: Python transforming value to tuple In python, I receive JSON data. The data looks like the following stub:
{
    "id": 1,
    "naam": "4.13",
    "ruimte_temperatuur_sensor": {...},
     // etc
}

I map this json to an object (note the sensor is mapped already):
    ruimte = Ruimte(id=id,
                    naam=naam,
                    ruimte_temperatuur_sensor=temperatuur_sensor,
                    ruimte_humiditeit_sensor=humiditeit_sensor,
                    ruimte_beweging_sensor=beweging_sensor,
                    airco_temperatuur_sensor=airco_sensor,
                    radiator_temperatuur_sensor=radiator_sensor)

The strangest thing happens:
The id field in JSON is an integer, but Python maps it to a tuple. In my debugger, you can clearly see that the id=id maps to an integer, but then all of a sudden my object contains a tuple:

The object's constructor should not cause that:
class Ruimte:
    def __init__(self,
                 id: int,
                 naam: str,
                 ruimte_temperatuur_sensor: Sensor,
                 ruimte_humiditeit_sensor: Sensor,
                 ruimte_beweging_sensor: Sensor,
                 airco_temperatuur_sensor: Sensor,
                 radiator_temperatuur_sensor: Sensor):
        self.id = id,
        self.naam = naam,
        self.ruimte_temperatuur_sensor = ruimte_temperatuur_sensor
        self.ruimte_humiditeit_sensor = ruimte_humiditeit_sensor
        self.ruimte_beweging_sensor = ruimte_beweging_sensor
        self.airco_temperatuur_sensor = airco_temperatuur_sensor
        self.radiator_temperatuur_sensor = radiator_temperatuur_sensor

In the sub-objects the id is not parsed to a tuple, for exampe ruimte.airco_temperatuur_sensor.id is an integer:

but that JSON is parsed the same way:
def _parse_json_to_sensor(self, json: dict) -> Sensor:
    id = json["id"]
    type = SensorType(json["type"])
    meet_interval_sec = json["sensorInstelling"]["meetIntervalSec"]
    opslaan_interval_sec = json["sensorInstelling"]["opslaanIntervalSec"]

    sensor = Sensor(id=id,
                    type=type,
                    meet_interval_sec=meet_interval_sec,
                    opslaan_interval_sec=opslaan_interval_sec)

I'm totally lost on this. What could cause this?

A: You have commas after the lines where you assign self.id and self.naam. Remove them.
a_string = 'string',
type(a_string)
>>> tuple

A: The comma in the line:
self.id = id,

leads to the creation of a tuple. See this example:
a = 1

b = 1
c = 1,

print(b)
print(c)


text:
Q: Why is each rendering counted 2 times instead of 1 for useRef and Set per component? Why is each rendered component the count and store appended 2 instead of 1 in the counter with useRef and in the Set for the callback functions for each component?
import React, { useRef, useState } from 'react';

const store = new Set();
let count = 0;

export function Forms() {

  const [value, setValue] = useState(0);
  const countRef = useRef(++count);

  const submit = (e) => {
    e.preventDefault();
    console.log(value);
  }

  store.add(submit);
  console.log(`Created functions: ${store.size}
  Counter useRef: ${countRef.current}`);

  return (
      <form>
        <input type="text" onChange={(e) => setValue(e.target.value)} />
        <button onClick={submit}>Submit</button>
      </form>
  );
}

function App () {
  return (
    <>
      <Forms />
      <Forms />
      <Forms />
    </>
  )
}

export default App;

console.log

A: its because you are probably using strict mode in react(when creating app with create-react-app the default is strict mode).
when wrapping your app with StrictMode each render will cause another render.
go to your index.js and remove the wrapping StrictMode over your app.


text:
Q: Stopping a function currently running from an interrupt handler Let's say I have two functions in C, a() and b().
And let's say I have two interrupts corresponding to both functions. The first interrupt should start running function a() and stop b() from running if it was interrupted during its run. Similarly,  the second interrupt does the same thing for function b().
If I am currently running in a(), and I triggered the interrupt for b(). How can I start b() and prevent a() from completing after the interrupt handler finished?
The Code is as follows:
int main(void)
{
    Init();
    while (true)
    {
    if (run_A)
    {
      a();
      run_A = false;
    }
    if (run_B)
    {
      b();
      run_B = false;
    }
}

void Handler(void)
{
    IntClear(interruptMask);

    if (INTERRUPT_FOR_A)
    {
        run_A = true;
    }

    if (INTERRUPT_FOR_B)
    {
        run_B = true;
    }
}

A:
I have a situation where b() calls a function that does some work that I don't need if I want to switch back to a(). I want to prevent it from happening when I call a(), and minimize the time it takes to start a()

Basically this situation will occur if INTERRUPT_FOR_B happens and a very short time later INTERRUPT_FOR_A happens, and if b() has a longer run time.
You need to carefully think about this situation and find out the chance of happening before doing premature optimizations.
But, if you want to go ahead, you can have some check points in the function b() to see if run_A is true.
e.g.
void b(void)
{
    // some code.
    if (run_A == true) return;
    // some code
    if (run_A == true) return;
    // etc
}

Note that you need to properly analyze and test b function with all the return paths to ensure that this function runs properly in all cases.

A: Overall it isn't very meaningful to speak about this in general terms. It depends on your requirements and what kind of hardware that is generating the interrupt.
You can't/shouldn't just stop a function mid-execution. The best way to do this is either to keep the functions small and let the current one finish, or alternatively have the functions poll a flag variable repeatedly.
A more intrusive but simple method would be to simply shut off the undesired interrupt, but that might lead to loss of data. Depending on the nature of the interrupt, this may or may not be fine.
And then there are of course evil ways to set the PC manually with assembler or longjmp, but this is very bad practice and almost certainly the wrong solution to any problem.

A: This is the kind of problem for which the setjmp(3)/longjmp(3) functions where designed in old UNIX(tm).  You need to call setjmp(3) before entering the function you want to interrupt and in case the interrupt comes (you must ensure the interrupt is handled in the context of the function you are going to interrupt) then yo make a call to longjmp(3) and restore the stack at the point of the call.

A: Sounds like you are looking for a feature similar to coroutines. While not directly supported in C, you maybe able to implement a version good enough for your needs. As mentioned above, this will probably involve setjmp/longjmp or the mind-bending "Duff's Device" if you want to do it in portable C.


text:
Q: GeoIP issue when automatically setting storeview in Magento 2 (`geoip_country_code_by_name` function) In order to automatically switch store views depending on a user's location we have decided to add the code provided here:Magento 2 pragmatically set storeview to ourindex.php file as shown below:
<?php
/**
 * Application entry point
 *
 * Example - run a particular store or website:
 * --------------------------------------------
 * require __DIR__ . '/app/bootstrap.php';
 * $params = $_SERVER;
 * $params[\Magento\Store\Model\StoreManager::PARAM_RUN_CODE] = 'website2';
 * $params[\Magento\Store\Model\StoreManager::PARAM_RUN_TYPE] = 'website';
 * $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $params);
 * \/** @var \Magento\Framework\App\Http $app *\/
 * $app = $bootstrap->createApplication(\Magento\Framework\App\Http::class);
 * $bootstrap->run($app);
 * --------------------------------------------
 *
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

try {
    require __DIR__ . '/app/bootstrap.php';
} catch (\Exception $e) {
    echo <<getMessage()}

HTML;
    exit(1);
}

$myipaddressis = $_SERVER['REMOTE_ADDR'];
$mycountryis = geoip_country_code_by_name($_SERVER['REMOTE_ADDR']);
$store='default';
if($mycountryis =='FR')
  {
   $store='FR';
  }
if($mycountryis =='ES')
  {
   $store='ES';
  }

$params = $_SERVER;
$params[\Magento\Store\Model\StoreManager::PARAM_RUN_CODE] = $store;
$params[\Magento\Store\Model\StoreManager::PARAM_RUN_TYPE] = 'store';
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $params);

/**
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
 @var \Magento\Framework\App\Http $app
*/

$app = $bootstrap->createApplication(\Magento\Framework\App\Http::class);
$bootstrap->run($app);

Although we did face some installation hurdles getting GeoIP work, we know that we have correctly installed the geoip_country_code_by_name function as we have tested it with a simple php file using the code below:
<?php
$myipaddressis = $_SERVER['REMOTE_ADDR'];
$mycountryis = geoip_country_code_by_name($_SERVER['REMOTE_ADDR']);
$country = geoip_country_code_by_name('www.google.com');
if ($country) {
    echo 'This host is located in: ' . $country;
    echo ' ---- My ip address is: ' . $myipaddressis;
    echo ' ---- My country is: ' . $mycountryis;
}
?>

which produces the following output:
www.google.com is located in: US ---- My ip address is: 92.150.xxx.xx ---- My country is: FR

Therefore we know the issue is not comming from GeoIP. However, when we navigate to our store homepage nothing happens in other words the location does not change but we do not get any errors either - just the default page. We have checked error/debug logs and see nothing there which would hint at where the issue is coming from. Our guess is that there is something wrong in the code we have added to theindex.php file. Any pointers would be greatly appreciated.

A: As usual the devil is in the detail... onthe server side index.php we were using
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
instead of
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $params);
so in the example in the original question above actually works but we hadn't defined the $boostrap variable correctly when adding the code so the instructions weren't being passed on... hope the question is helpful for anyone wanting to use GeoIP.


text:
Q: Java - Catching an exception from a reflectively called constructor I am creating a object using reflection. Depending on the actual object being constructed, the constructor might have a throws declaration for a particular custom exception and its important I can catch this.
Unfortunately, when I attempt to add the exception to catches of the try block that encompasses the reflective construction, the code will not compile because:

"Unreachable catch block. This exception is never thrown from the try
  statement body"

I realise that catching the base class Exception would work, and infact that is ok for my code. However, it might not always be the case, since other different exceptions may apply for other objects in the future and using instanceof inside of a catch and re-throwing everything else seems inelegant.
Is there a way to signal that this exception might be thrown, so that I can catch it specifically?
edit: Some code as requested. Does not compile because of above.
try{
  Constructor<? extends Thing> constructor = getClassType().getDeclaredConstructor(SomeParameter.class);
  Thing thing = constructor.newInstance(new SomeParameter());
}
catch(FoobarException e){
  //new Thing(SomeParameter p) might throw this
}
catch(ReflectiveOperationException | IllegalArgumentException | SecurityException e){}

A:
Is there a way to signal that this exception might be thrown, so that I can catch it specifically?

No.
Because at the point, any exception thrown by the constructor will have been caught and an InvocationTargetException will have been thrown in its place.  This is explained succinctly by the javadoc as follows:

"Throws: [...] InvocationTargetException - if the underlying constructor throws an exception."

(Note that it says "an exception", so this applies to both checked and unchecked exceptions thrown by the constructor.)
So in fact, compiler is telling the truth in that compilation error.  The checked exception you were trying to catch cannot possibly be propagating at that point. Indeed, the JLS reachability rules state that the code is definitely unreachable ... hence the compilation error.

A: The exception will be thrown wrapped in an InvocationTargetException. Catch that and have a look at the cause.


text:
Q: Postgres behave abnormally I have production application running on PostgreSQL database on a on premise Ubuntu System. Recently I have been facing one strange issue, that Postgres service is getting killed itself and then it is restarted.
I am getting below error in JBoss 7.1 server, which is strange and is not occurring on fixed method or line :
In server.log :

An I/O error occurred while sending to the backend

Then I checked into Postgres log, it shows that,
In Postgres log postgresql-9.4-main.log :

Process was terminated by signal 9

However, I have stopped Jboss server and executed my one query in PSQL and received below error :
server closed the connection unexpectedly
    This probably means the server terminated abnormally
    before or while processing the request.
The connection to the server was lost. Attempting reset: Failed.

Same exact replication in AWS Ubuntu, is running fine with same database. So, I am not able to find actual root cause. Please help.
Kindly note, I have not made any configuration changes in PostgreSQL. Let me know, if any other information required.

A: In my case,
After so many try, we just re-install Postgres with existing data restore. Now, everything is working fine as expected.
If anyone has still any suggestion, post your answer/comment.