text:
Q: Iterate through df rows faster I am trying to iterate through rows of a Pandas df to get data from one column of the row, and using that data to add new columns. The code is listed below but it is VERY slow. Is there any way to do what I am trying to do without iterating thru the individual rows of the dataframe?
ctqparam = []
wwy = []
ww = []
for index, row in df.iterrows():
    date = str(row['Event_Start_Time'])
    day = int(date[8] + date[9])
    month = int(date[5] + date[6])
    total = 0
    for i in range(0, month-1):
        total += months[i]
    total += day
    out = total // 7
    ww += [out]
    wwy += [str(date[0] + date[1] + date[2] + date[3])]

    val = str(row['TPRev'])
    out = ""
    for letter in val:
        if letter != '.':
            out += letter
    df.replace(to_replace=row['TPRev'], value=str(out), inplace = True)

    val = str(row['Subtest'])
    if val in ctqparam_dict.keys():
        ctqparam += [ctqparam_dict[val]]

# add WWY column, WW column, and correct data format of Test_Tape column
df.insert(0, column='Work_Week_Year', value = wwy)
df.insert(3, column='Work_Week', value = ww)
df.insert(4, column='ctqparam', value = ctqparam)

A: It's hard to say exactly what your trying to do.  However, if you're looping through rows chances are that there is a better way to do it.
For example, given a csv file that looks like this..
Event_Start_Time,TPRev,Subtest
4/12/19 06:00,"this. string. has dots.. in it.",{'A_Dict':'maybe?'}
6/10/19 04:27,"another stri.ng wi.th d.ots.",{'A_Dict':'aVal'}

You may want to:

*

*Format Event_Start_Time as datetime.

*Get the week number from Event_Start_Time.

*Remove all the dots (.) from the strings in column TPRev.

*Expand a dictionary contained in Subtest to its own column.

Without looping through the rows, consider doing thing by columns.  Like doing it to the first 'cell' of the column and it replicates all the way down.
Code:
import pandas as pd

df = pd.read_csv('data.csv')

print(df)

     Event_Start_Time    TPRev                              Subtest
0    4/12/19 06:00       this. string. has dots.. in it.    {'A_Dict':'maybe?'}
1    6/10/19 04:27       another stri.ng wi.th d.ots.       {'A_Dict':'aVal'}

# format 'Event_Start_Time' as as datetime
df['Event_Start_Time'] = pd.to_datetime(df['Event_Start_Time'], format='%d/%m/%y %H:%M')

# get the week number from 'Event_Start_Time'
df['Week_Number'] = df['Event_Start_Time'].dt.isocalendar().week

# replace all '.' (periods) in the 'TPRev' column
df['TPRev'] = df['TPRev'].str.replace('.', '', regex=False)

# get a dictionary string out of column 'Subtest' and put into a new column
df = pd.concat([df.drop(['Subtest'], axis=1), df['Subtest'].map(eval).apply(pd.Series)], axis=1)

print(df)

     Event_Start_Time      TPRev                       Week_Number    A_Dict
0    2019-12-04 06:00:00   this string has dots in it  49             maybe?
1    2019-10-06 04:27:00   another string with dots    40             aVal

print(df.info())

Data columns (total 4 columns):
 #   Column            Non-Null Count  Dtype
---  ------            --------------  -----
 0   Event_Start_Time  2 non-null      datetime64[ns]
 1   TPRev             2 non-null      object
 2   Week_Number       2 non-null      UInt32
 3   A_Dict            2 non-null      object
dtypes: UInt32(1), datetime64[ns](1), object(2)

So you end up with a dataframe like this...
     Event_Start_Time      TPRev                       Week_Number    A_Dict
0    2019-12-04 06:00:00   this string has dots in it  49             maybe?
1    2019-10-06 04:27:00   another string with dots    40             aVa

Obviously you'll probably want to do other things.  Look at your data.  Make a list of what you want to do to each column or what new columns you need.  Don't mention how right now as chances are it's possible and has been done before - you just need to find the existing method.
You may write down get the difference in days from the current row and the row beneath etc.).  Finally search out how to do the formatting or calculation you require.  Break the problem down.


text:
Q: XSL, comparing dates to exclude any past events I have an RSS of an events feed. I would like to hide previous events.
Assuming XML data subset of
<Navigation Name="ItemList" Type="Children">
<Page ID="x32444" URL="..." Title="Class..."
EventStartDate="20090831T23:00:00" EventEndDate="20090904T23:00:00"
  EventStartTime="20090830T15:30:00" EventEndTime="20090830T18:30:00" Changed="20090830T20:28:31" CategoryIds="" Schema="Event"
  Name="Class of 2010 BAKE SALE"/>
 <Page ID="x32443" URL="x32443.xml?Preview=true&Site=&UserAgent=&IncludeAllPages=true&tfrm=4" Title="Class of 2010 BAKE SALE"
  Abstract="Treat yourself with our famous 10-star FRIED ICE CREAM!" EventStartDate="20090831T23:00:00" EventEndDate="20090904T23:00:00"
  EventStartTime="20090830T15:30:00" EventEndTime="20090830T18:30:00" Changed="20090830T20:25:35" CategoryIds="" Schema="Event"
  Name="Class of 2010 BAKE SALE"/>
 <Page ID="x32426" URL="x32426.xml?Preview=true&Site=&UserAgent=&IncludeAllPages=true&tfrm=4" Title="Tribute to ..."
  Abstract="Event to recognize and celebrate the lifetime of leadership and service ..."
  EventStartDate="20091206T00:00:00" EventEndDate="20091206T00:00:00" EventStartTime="20090828T23:00:00" EventEndTime="20090828T04:00:00"
  Changed="20090828T22:09:54" CategoryIds="" Schema="Event" Name="Tribute to ...."/>

</Navigation>

How would I not include anything past today's date
<xsl:apply-template select="Page[@EventStartDate=notBeforeToday()]"/>

A: Easiest with XSL parameters that you set from outside.
<xsl:param name="today" select="'undefined'" />

<!-- time passes... -->

<xsl:apply-templates select="Page[@EventStartDate < $today]"/>

Your date format is such that you can compare it using string comparison, unless there are different timezones involved. You would simply set
20091001T00:00:00

as the param value for $today. Have a look into your XSLT processor's documentation to see how.
The alternative would be to use an extension function. Here it depends on which extension functions your XSLT processor supports, so this approach won't be portable.

A: For this purpose, i usually add an extra date attribute in the XML which contains the day number since year 1900.
for example @dateid='9876543' or @seconds="9876675446545"
then i can can easily compare with today or another variable in the XSL.
You can also use this technique to compare times using "Unix time" for example

redpajama_set_name: RedPajamaStackExchange


text:
Q: Increasing Upload File Size Limit in Google Cloud I am trying to increase upload file size limit in Google Cloud.
I open nano /opt/bitnami/php/etc/php.ini and increase upload_max_filesize and post_max_size
I also restart the apache by sudo /opt/bitnami/ctlscript.sh restart apache
Retart also works well, so I am sure the code is correct. But when I am trying to upload the file in WordPress backend, it says Maximum upload file size is 40MB.
I am trying to migrate a website by All in one WP migration plugin.
Thanks in advance!

A: Do a full restart and not just the Apache restart as one of the user had commented using the below command.
"sudo /opt/bitnami/ctlscript.sh restart"


text:
Q: Where is ECS Task Stopped Reason now? I am using the AWS interface to configure my services on ECS. Before the interface change, I used to be able to access a screen that would allow me to see why the task had failed (like in the example below), that interface could be accessed from the ECS service events by clicking on the taskid. Does anyone know how to get the task stopped reason data with the new interface?

A: You can see essentially the same message if you do the following steps:

*

*Select your service from your ECS cluster:

*Go to Configuration and tasks tab:

*Scroll down and select a task. You would want to chose one which was stopped by the failing deployment:

*You should have the Stopped reason message:


text:
Q: rc.local does not execute all of the commands #!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.

echo "rc.local executed successfully" > /tmp/rclocal_executed

/usr/bin/synclient TapButton2=0
/usr/bin/synclient RightButtonAreaLeft=3
/usr/bin/tilda &

exit 0

command
echo "rc.local executed successfully" > /tmp/rclocal_executed

executed successfully, but the rest is not.
I assume the problem could be that these commands should be executed after I log in, and rc.local probably executed when just OS starts, therefore it might have no effect.
How to execute specified commands on a start up?

A: The problem was that the following commands require X server to be running, but rc.local executed prior X initialized, therefore commands can not be executed.
Solution:
In Ubuntu 12.04 invoke "Startup Applications" app, and put these commands there.


text:
Q: Google Cloud Build & GitHub Enterprise IP Allow List How can I allow Google Cloud Build through GitHub Enterprise's IP allow list restriction?
I have already added all 80 IP ranges for the region of the Cloud Build I am using and that did not seem to work.


text:
Q: YogaKit.modulemap not found after running the IOS Simulator I have problems running my IOS Simulator within XCode, everytime I try to run the simulator, I get an error message saying:
"fatal error: module map file '/Users/maurice/Library/Developer/Xcode/DerivedData/feedIt-etmfdpwrwadziocunpypqhkwucsd/Build/Products/Debug-iphonesimulator/YogaKit/YogaKit.modulemap' not found"
Expected behavior:
XCode runs the simulator.
Actual Behavior:
The Build fails and I get the described error message.
I already tried to update Pods and delete the Derived Data, but apparently that didn't work.
How can I fix this issue?
I'm running on MacOS 10.15.5 and XCode 11.6

A: According to the comments in this issue, the problem could be that you opened up .xcodeproj instead of .xcworkspace. Some of the other suggested fixes include:

*

*Make sure your cocoapods build target is the same version as your projects build target. link

*Try rebooting your machine. link

*Examine your podfile to make sure your build scheme is included in it. link
I was experiencing a similar issue when trying to build the project from the command line and the root issue was that I was using the .xcodeproj instead of .xcworkspace. From what I could tell this error could be caused by multiple different factors.

A: The issue I was facing when I received this error was, I had opened the wrong file in Xcode. Instead of opening the '.xcworkspace' file, I opened the '.xcodeproj' file.
The solution to this issue is to open the '.xcworkspace' file in Xcode instead of the '.xcodeproj' file.

A: If you are using M1 chip

*

*Add arm64 in Excluded Architecture

*Add following lines in podfile

*Remove node_modules from root, Podfile.lock and Pods from ios folder

*Run in root terminal yarn install && cd ios && pod install && pod update

*Clean your project and open again

*Wait for indexing the project

*Run project

A: Add this to your Podfile if you are using a M1 chip Mac
    installer.pods_project.build_configurations.each do |config|
      config.build_settings["EXCLUDED_ARCHS[sdk=iphonesimulator*]"] = "arm64"
    end

A: Described solution will work 100% on Apple silicon and while running Xcode without rosetta.
Please try necessary steps only but if still not work than Please try everything including necessary and unnecessary steps.
1 - Not important(Package.json)
"dependencies": {
 "react": "17.0.1",
 "react-native": "0.64.2"
}

2 - necessary
  use_flipper!()
  post_install do |installer|
    react_native_post_install(installer)
        installer.pods_project.build_configurations.each do |config| config.build_settings["EXCLUDED_ARCHS[sdk=iphonesimulator*]"] =  "arm64"
        end
  end

OR
  use_flipper!()

  post_install do |installer|
    react_native_post_install(installer)
      installer.pods_project.targets.each do |target|
          target.build_configurations.each do |config|
            config.build_settings["ONLY_ACTIVE_ARCH"] = "NO"
          end
      end
  end

3 - Add arm64 under Architectures->Excluded Architectures

4 - Add a swift file under your project, can be empty, can be BridgingFile.swift(nothing special in it), this will trigger a bridging header. Wallah, here you go.

A: I have solved this problem with adding to Debug Any iOS Simulator SDK with value arm64 to excluded architecture in Pods project (apple MacBook
Pro m1)

A: The issue for me was not setting the VALID_ARCHS = "arm64 arm64e armv7 armv7s x86_64"; like this in xyzApp/ios/xyzApp.xcodeproj/project.pbxproj

A: try running the project on on terminal with this command:
npx react-native run-ios
and the run it on Xcode again

A: I have searched a lot and almost wasted my  day but in the end, I have tried two solutions that solved my problem

*

*Update the Xcode to the latest version

*Open xxx.xcworkspace instead of xxx.xcodeproj in Xcode

*Clean and build the project

Hope your problem solve :)

A: *

*run brew uninstall watchman

*run brew install watchman or arch arm64 brew install watchman if you are on an M1

*closed the current terminal (console) session

*open it again and go to the project directory

*cd ios && rm -rf Pods Podfile.lock && pod install --repo-update

*run watchman watch-del-all

*if you have the iOS simulator opened, closed it

*run yarn react-native run-los

A: in my case, this is solved by changing
build active architecture only > release > yes in build settings

A: make sure to your deployment target should be same in podfile, project and target.

A: I have got an M1 mac setup. The above methodologies were not working for me.
However, this worked: Run XCode Rosetta

Finder -> Xcode in applications folder -> Get Info -> set Open with
Rosetta to true

Xcode is now under Rosetta.

A: open xxx.xcworkspace instead of xxx. xcodeproj

A: Once of reason can export this error is setting on User-Defined. Recently, I pull a project to continue dev. I can't build it on simulator. It's always so this error.

Module map not found

for all lib. Its take me a lot of times to fix this. I check of all config & found problem is previous dev set VALID_ARCHS are only: arm64e armv7s arm64
I changed it to both ios device & simulator: arm64 arm64e armv7 armv7s x86_64 or simple delete VALID_ARCHS from User-Defined.
Now it can work. Hope this help :-)


text:
Q: post__in and tag__not_in conflict I have related post section in my theme. I would like to exclude posts from a certain tag.
This is my query:
'post__in'            => $related_posts_ids,
'orderby'             => 'post__in',
'posts_per_page'      => $max_posts_to_show,
'ignore_sticky_posts' => true,

Using tag__not_in is working but the number of posts doesn't stay same. I mean, total number of posts is 6. After excluding 1 post from that tag, total number of posts becomes 5.
If I remove the post__in, number of posts stays same but then related post section doesn't work as expected.
Is there a way to keep post__in, exclude posts from a certain tag and keep the number of posts same?


text:
Q: How do I run a binary program without showing the gear icon? I created a automator workflow, add a Run Shell Script part and put these lines in:

/Users/xxx/Library/Android/sdk/tools/android avd

I saved it as an app and it works.
But I will always see a gear icon on the menu bar.
I tried to put a & or nohup, if so the program won't start.
Any ideas? The android I'm trying to execute is a shell script

A: You will always see the gear in the menu bar if you are using Automator. If you want it to exit quickly, create a wrapper that forks off your android script into another process, and exits.
For example, you could run

echo "/Users/xxx/Library/Android/sdk/tools/android avd" | /usr/bin/at now

(source for script is from this Apple Discussions page near the bottom)


text:
Q: Exportar Kendo Grid para PDF Tenho uma função que exporta para Excel e preciso de outra que exporte para PDF.  A função deverá exportar os dados de uma Kendo Grid.
function ExportarParaExcel(grid) {
   grid = grid == undefined ? "#grid" : grid;
   var grd = $(grid).data("kendoGrid");
   grd.bind("excelExport", function (e) {
       var rows = e.workbook.sheets[0].rows;
       for (var ri = 0; ri < rows.length; ri++) {
           var row = rows[ri];
           var dd = '';
           if (row.type == "group-header" || row.type == "header" || row.type == "group-footer" || row.type == "footer") {
               for (var ci = 0; ci < row.cells.length; ci++) {
                   var cell = row.cells[ci];
                   if (cell.value) {
                       cell.value = ajustaAcentosXLS(cell.value);
                   }
               }
           }
       }
   });
   grd.saveAsExcel();
}

A: Encontrado a solução na pergunta do Stack Overflow (Inglês). Ela soluciona o problema de exportação, mas identifiquei que para o meu caso, é melhor exportar somente para Excel.


text:
Q: como colocar de forma simples um ícone na actionBar? Quero colocar um ícone na minha ActionBar já procurei por essa informação aqui no StackOverFlow, mas as respostas que encontrei são muito complicadas (sou iniciante) e por isso queria saber se tem uma forma bem simples.

A: Você pode utilizar a Toolbar para isso.
A Toolbar substitue a ActionBar padrão do Android e com ela é bem mais fácil de trabalhar.
Primeiramente, você deverá configurar o tema da sua aplicação para suportar a Toolbar, dizendo que você quer alterar a ActionBar padrão (não esqueça de alterar no seu AndroidManifest.xml):
styles.xml:
<style name="Seu.Tema" parent="Theme.AppCompat.NoActionBar">
    <item name="colorPrimary">@color/suaPrimaryColor</item>
    <item name="colorPrimaryDark">@color/suaPrimaryDarkColor</item>
</style>

AndroidManifest.xml
 <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/Seu.Tema">
        ...
</application>

Agora, você precisa colocar a Toolbar em seu layout. Lembre-se que ele é um componente qualquer do Android, então ele deve estar dentro do seu .xml:
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

     <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"/>

</LinearLayout>

Uma vez no .xml, agora você consegue manipuna-la em sua classe. Dentro dela, você precisa dizer a sua Activity que você quer trocar a ActionBar padrão, para isso você deve utilizar o método setSupportActionBar():
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

Pronto, agora sua Toolbar já é a sua ActionBar e você pode customiza-la como quiser. Para alterar o ícone padrão (ou o Navigation Icon), você simplesmente:
toolbar.setNavigationIcon(R.drawable.seu_icone);


text:
Q: storing images in phone memory using picasso or universal image loader instead of cache i am using using picasso library for loading images from url and the images are loading perfectly but the problem is it stores the images on cache memory of device and after loading many images it runs out of memory so is their any way to store images  on phone memory , the images downloaded should be shored as APP DATA of the application so that when device is disconnected from the net it still can  fetch the image.

If its not posssible to store images on device using picasso  the how can we achive the same using  universal image loader , i wanted to know the UIL option configuration.
thanks

A: Storing of Image using picasso we can achieve.
Picasso.with(getActivity()).load(mUrl).into(target);
private Target target = new Target() {
    @Override
    public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
    }
}

Write ur logic in onBitmapLoaded to store images into disk.
Check Glide library it may help you, where it does everything for you.


text:
Q: Find the derivative of 9x^2 f(x) I don't think I fully understand the question. If I knew f(x) I would use the chain rule or product rule, but since I don't, how do I know what to do? Thanks for any help I appreciate it.

A: You can use the product rule for this provided $f$ is differentiable. Write your function as
$$9 \cdot x^2 \cdot f(x)$$
Then by linearity,
$$\frac{d}{dx} 9x^2f(x) = 9 \cdot \frac{d}{dx} \left( x^2 \cdot f(x) \right)$$
You can use the product rule here as normal.

Example: Say we want to find the derivative of $\sin(x)g(x)$ where $g$ is a differentiable function. By the product rule,
$$\frac{d}{dx} \sin(x)g(x) = \cos(x)g(x) + \sin(x)g'(x)$$

More generally, as long as $f,g$ are differentiable,
$$\frac{d}{dx} f(x)g(x) = f'(x)g(x) + f(x)g'(x)$$
In our example, we simply set $f(x) = \sin(x)$. In your case, you could set $g(x) = x^2$, as another means of looking at it.


text:
Q: Order of authors in footnote in elsarticle my friends.
I am preparing a latex file in elsarticle format. The below code is my MWE.
  \documentclass[review,3p,times,fleqn]{elsarticle}
  \usepackage[hyperfootnotes=false,raiselinks=true,colorlinks,linktoc=all]{hyperref}
  \begin{document}
  \begin{frontmatter}
  %----------------------------------------------------
  %          Title of Paper
  %----------------------------------------------------
  \title{Computation of flow and heat transfer}
  %----------------------------------------------------
  %          Author Names
  %----------------------------------------------------
  %% Group authors per affiliation:
  \author[label1]{\textcolor{blue}{Mohammad Fazli}}
  \ead{mohammad.fazli@ut.ac.ir}
  %-------------
  \author[label1]{\textcolor{blue}{Mehrdad Raisee}\corref{cor1}}
  \ead{mraisee@ut.ac.ir}
  %-------------
  \cortext[cor1]{Corresponding author}
  %----------------------------------------------------
  %          Author's Affiliations
  %----------------------------------------------------
  \address[label1]{Hydraulic Machinery Research Institute, School of Mechanical Engineering, College of Engineering, University of Tehran, Tehran, P.O. Box: 11155-4563, Iran}
  \end{frontmatter}
  \section{Bibliography styles}
  In another study, Hwang et al. measured the local distribution of heat transfer coefficient and thermal performance in a channel with a staggered array of dimples and protrusions.
  \end{document}

As I mentioned, I am using the elsearticle class. My problem is in my affiliation and its footer section. I have set "mohammad fazli" and "mehrdad raisee" in affiliation section, respectively. But I want to set these names with a reverse order at the footer. I mean email of mehrdad raisee and email of mohammad fazli at the footer. Can anybody help me?
I mean:
names:
mohammad fazli, mehrdad raisee
footer:
email of mehrdad raisee, email of mohammad fazli


text:
Q: Visual Studio settings files corrupt / MySQL connection issues My Visual Studio 2012 Professional is having problems with a three project solution.
I have been struggling all day with a LinqToMySQL.edmx file and getting a MySQL data connection option to appear in Server Explorer.
For this I have tried installing EFTools6.1.0ForVS2012. The mysql connector I have tried is mysql-connector-net-6.7.4. This worked at one point but other problems with MySQL dll versions means I am back to square one (when I got the latest version of the DLL which I got from nuGet 6.8.3, it was still looking for 6.7.4). I have since got 6.7.4 and added the reference to the dll for all project. I've also tried editing machine.config to look for the correct mysql data provider. Still no joy.
But now...
For each solution the app.config or web.config files can't be read when trying to access Properties > Settings.

An error occurred while reading the app.config file. The file might be
  corrupted or contain invalid XML

All files seem valid when checked under an XML validator.
When opening a project in VS2012 I get the error:

Microsoft Visual Studio
  The ProviderPackage package did not load correctly.
  The problem may have been caused by a configuration change
  or by the installation of another extension. You can get more
  information by examining the file
  t:\Users\John\AppData\Roaming\Microsoft\VisualStudio\11.0\A
  ctivityLog.xml.

When trying to create a new project I get:

Failed to create a 'ImageSource' from the text
  '..\lmages\Medium.png'.

After re-installing Visual Studio the problem persists.
In the activity log the last errors are:
    <entry>
    <record>235</record>
    <time>2014/03/25 10:28:31.202</time>
    <type>Warning</type>
    <source>Microsoft.VisualStudio.CommonIDE.ExtensibilityHosting.VsShellComponentModelHost</source>
    <description>The catalog cache file is not up-to-date and has to be regenerated:</description>
    <path>C:\Users\John\AppData\Local\Microsoft\VisualStudio\11.0\ComponentModelCache\Microsoft.VisualStudio.Default.cache</path>
  </entry>
<entry>
    <record>236</record>
    <time>2014/03/25 10:28:31.211</time>
    <type>Error</type>
    <source>VisualStudio</source>
    <description>SetSite failed for package [Visual Studio Component Model Host Package]</description>
    <guid>{49D12072-378B-4FFA-A09E-40E0B5D097CC}</guid>

80131902

    <errorinfo>Configuration system failed to initialize</errorinfo>
  </entry>
 <entry>
    <record>237</record>
    <time>2014/03/25 10:28:31.241</time>
    <type>Error</type>
    <source>VisualStudio</source>
    <description>End package load [Visual Studio Component Model Host Package]</description>
    <guid>{49D12072-378B-4FFA-A09E-40E0B5D097CC}</guid>

80131902

    <errorinfo>Configuration system failed to initialize</errorinfo>
  </entry>

A: Looks like most of these errors were caused by malformed XML in the machine.config file in the framework folder. The machine.config file in framework64 was fine which must have caused me confusion. That's what editing with notepad gets you!
Still having problems with the mysql connector but that's a separate issue.


text:
Q: How do I insert a new node into a binary tree in C? I've been trying to get this to work for a while now, but there is clearly something I don't understand.
I have to insert a new node into a binary tree with "phone" as it's value.
void bst_insert_node(bstree* bst, unsigned long phone, char *name) {
    bst_node* new_node = malloc(sizeof(bst_node));
    new_node->phone = phone;
    bst_node* y = NULL;
    bst_node* x = bst->root;

    while(x != NULL)
    {
        y = x;
        if(phone <= x->phone)
             x = x->left;
        else x = x->right;
    }
    if (y == NULL)
    {
        bst->root = new_node;
    }
    else
    {
        if (phone <= y->phone)
             y->left->phone = phone;
        else y->right->phone = phone;
    }
}

I would appreciate any type of comments and explanations.
Thank you very much in advance.
Edit:
I have corrected y->left->phone = phone to y->left = new_node as one of your comments suggested.
Still, it does not work.
Valgrind gives me this:
valgrind ./a.out telefonbuch_einfach.txt ==5941== Memcheck, a memory error detector
==5941== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==5941== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==5941== Command: ./a.out telefonbuch_einfach.txt
==5941==
==5941== error calling PR_SET_PTRACER, vgdb might block
==5941== Conditional jump or move depends on uninitialised value(s)
==5941==    at 0x4013AB: bst_insert_node (introprog_telefonbuch.c:19)
==5941==    by 0x400A5E: read_file (introprog_main_telefonbuch.c:54)
==5941==    by 0x400CB6: main (introprog_main_telefonbuch.c:119)
==5941==
==5941== Use of uninitialised value of size 8
==5941==    at 0x401435: bst_insert_node (introprog_telefonbuch.c:31)
==5941==    by 0x400A5E: read_file (introprog_main_telefonbuch.c:54)
==5941==    by 0x400CB6: main (introprog_main_telefonbuch.c:119)
==5941==
==5941== Invalid write of size 8
==5941==    at 0x401435: bst_insert_node (introprog_telefonbuch.c:31)
==5941==    by 0x400A5E: read_file (introprog_main_telefonbuch.c:54)
==5941==    by 0x400CB6: main (introprog_main_telefonbuch.c:119)
==5941==  Address 0x18 is not stack'd, malloc'd or (recently) free'd
==5941==
==5941==
==5941== Process terminating with default action of signal 11 (SIGSEGV)
==5941==  Access not within mapped region at address 0x18
==5941==    at 0x401435: bst_insert_node (introprog_telefonbuch.c:31)
==5941==    by 0x400A5E: read_file (introprog_main_telefonbuch.c:54)
==5941==    by 0x400CB6: main (introprog_main_telefonbuch.c:119)
==5941==  If you believe this happened as a result of a stack
==5941==  overflow in your program's main thread (unlikely but
==5941==  possible), you can try to increase the size of the
==5941==  main thread stack using the --main-stacksize= flag.
==5941==  The main thread stack size used in this run was 8388608.
==5941==
==5941== HEAP SUMMARY:
==5941==     in use at exit: 832 bytes in 6 blocks
==5941==   total heap usage: 7 allocs, 1 frees, 4,928 bytes allocated
==5941==
==5941== LEAK SUMMARY:
==5941==    definitely lost: 0 bytes in 0 blocks
==5941==    indirectly lost: 0 bytes in 0 blocks
==5941==      possibly lost: 0 bytes in 0 blocks
==5941==    still reachable: 832 bytes in 6 blocks
==5941==         suppressed: 0 bytes in 0 blocks
==5941== Rerun with --leak-check=full to see details of leaked memory
==5941==
==5941== For counts of detected and suppressed errors, rerun with: -v
==5941== Use --track-origins=yes to see where uninitialised values come from
==5941== ERROR SUMMARY: 5 errors from 3 contexts (suppressed: 0 from 0)
Segmentation fault (core dumped)

A: Your search for the correct node to do the insertion is fine. The problems are:

*

*When you allocate a new node, you neglect to set left and right to NULL. These will have junk values.

*After you find the node, you try to assign just the phone number to these junk values. You need to assign the newly created node.

void bst_insert_node(bstree* bst, unsigned long phone, char *name) {
    // Use calloc, memset, or manually set all values to NULL
    bst_node* new_node = malloc(sizeof(bst_node));
    // TODO: verify new_node is not NULL
    new_node->phone = phone;
    new_node->left = NULL;
    new_node->right = NULL;
    new_node->name = NULL;  // TODO: use strdup to copy name

    bst_node* y = NULL;
    bst_node* x = bst->root;

    while(x != NULL)
    {
        y = x;
        if(phone <= x->phone)
             x = x->left;
        else x = x->right;
    }
    if (y == NULL)
    {
        bst->root = new_node;
    }
    else
    {
        if (phone <= y->phone)
             y->left = new_node;
        else
            y->right = new_node;
    }
}

A: For starters there is a typo
else
{
    if (phone <= y->phone)
         y->left->phone = phone;
    else y->right->phone = phone;
}

There should be
else
{
    if (phone <= y->phone)
         y->left = new_node;
    else y->right = new_node;
}

The function does not use the parameter name.
Also data members left and right are not initialized for the newly created node.
The function can be defined the following way as it is shown below. I assume that the corresponding structures are defined like
typedef struct bst_node
{
    unsigned long phone;
    char *name;
    struct bst_node *left;
    struct bst_node *right;
} bst_node;

typedef struct
{
    bst_node *root;
} bstree;

Here is the function.
int bst_insert_node( bstree* bst, unsigned long phone, const char *name )
{
    bst_node *new_node = malloc( sizeof( bst_node ) );
    int success = new_node != NULL;

    if ( success )
    {
        new_node->name = malloc( strlen( name ) + 1 );

        success = new_node->name != NULL;

        if ( !success ) free( new_node );
    }

    if ( success )
    {
        strcpy( new_node->name, name );
        new_node->phone = phone;
        new_node->left = NULL;
        new_node->right = NULL;

        bst_node **current = &bst->root;

        while ( *current != NULL )
        {
            if ( new_node->phone < ( *current )->phone )
            {
                current = &( *current )->left;
            }
            else
            {
                current = &( *current )->right;
            }
        }

        *current = new_node;
    }

    return success;
}

If the data member name is a character array then the function will look simpler because you will not need to allocate memory to store name.


text:
Q: Dropzone JS и flask: паралельная загузка чанков Я пытаюсь загружать файл с помощью dropzone.js и бекендом на flask. Конфигурация dropzon:
<form method="POST" action='/process_chunk' class="dropzone dz-clickable"
     id="dropper" enctype="multipart/form-data">
</form>

<script type="application/javascript">
   Dropzone.options.dropper = {
       {# https://gitlab.com/meno/dropzone/wikis/faq#chunked-uploads #}
       paramName: 'file',
       acceptedFiles: '.csv',
       chunking: true,
       forceChunking: true,
       chunkSize: 100000, // bytes
       parallelChunkUploads: true,
       maxFilesize: 1025, // megabytes
</script>

и колбек-функция на бекенде, которая обрабатывает чанки:
@app.route('/process_chunk', methods=['POST'])
def process_chunk():
    current_chunk = int(request.form['dzchunkindex'])

    file = request.files['file']
    save_path = os.path.join(app.config['DATA_DIR'], file.filename)

    try:
        with open(save_path, 'ab+') as f:
            # Goto the offset, aka after the chunks we already wrote
            f.seek(int(request.form['dzchunkbyteoffset']))
            f.write(file.stream.read())
    except OSError:
        # log.exception will include the traceback so we can see what's wrong
        log.exception('Could not write to file')
        return make_response(("Couldn't write the file to disk", 500))

    total_chunks = int(request.form['dztotalchunkcount'])

    if current_chunk + 1 == total_chunks:
        # This was the last chunk, the file should be complete and the size we expect
        if os.path.getsize(save_path) != int(request.form['dztotalfilesize']):
            log.error(f"File {file.filename} was completed, "
                      f"but has a size mismatch."
                      f"Was {os.path.getsize(save_path)} but we"
                      f" expected {request.form['dztotalfilesize']} ")
            return make_response(('Size mismatch', 500))
        else:
            log.info(f'File {file.filename} has been uploaded successfully')
    else:
        log.debug(f'Chunk {current_chunk + 1} of {total_chunks} '
                  f'for file {file.filename} complete')

    return make_response(("Chunk upload successful", 200))

Все работает замечательно, если установить parallelChunkUploads в false. Чанки загружаются последовательно один за другим, и загруженный файл выглядит в точности, как исходный. Для примера, я беру маленький файл (409 байт) и устанавливаю размер чанка в 50 байт:
.
Когда я устанавливаю parallelChunkUploads в true, чанки загружаются параллельно:

Но данные в загруженном файле полностью перепутаны
original file
cod,char,xx
01,aaaa,xx
02,bbbb,xx
03,cccc,xx
04,dddd,xx
05,eeee,xx
06,ffff,xx
07,gggg,xx
08,iiii,xx
09,kkkk,xx
10,llll,xx
11,mmmm,xx
12,gerf,xx
13,flrg,xx
14,erge,xx
15,lkro,xx
16,ergf,xx
17,kiwu,xx
18,erjg,xx
19,hytj,xx
20,utkj,xx
21,rger,xx
22,ehth,xx
23,kmik,xx
24,ergb,xx
25,ergk,xx
26,egeg,xx
27,ejer,xx
28,gtrh,xx
29,thrh,xx
30,rhtr,xx
31,gtrh,xx
32,thrh,xx
33,rhtr,xx

uploaded file
cod,char,xx
01,aaaa,xx
02,bbbb,xx
03,cccc,xx
0iiii,xx
09,kkkk,xx
10,llll,xx
11,mmmm,xx
12,gerf,xx
13,flrg,xx
14,erge,xx
15,lkro,xx
16,ergf4,dddd,xx
05,eeee,xx
06,ffff,xx
07,gggg,xx
08,x
21,rger,xx
22,ehth,xx
23,kmik,xx
24,ergb,xx
,xx
17,kiwu,xx
18,erjg,xx
19,hytj,xx
20,utkj,x9,thrh,xx
30,rhtr,xx
31,gtrh,xx
32,thrh,xx
33,rhtr,xx

25,ergk,xx
26,egeg,xx
27,ejer,xx
28,gtrh,xx
2

Последний чанк красного цвета потому, что фронт получает респонс от фласки 'Size mismatch', 500 - размер файла после загрузки последнего чанка не совпадает.
У кого есть идеи, как это пофиксить?


text:
Q: balanced 2-partition with equal cardinality (cardinality difference = 1 (max)) Given a set $S$ of $N$ numbers, my aim is to partition it into two sets ($S_1$ and $S_2$), so that
(i) the difference $\sum S_1 - \sum S_2$ is minimized and
(ii) the difference $|S_1| - |S_2|$ is $1$ if $N$ is odd, and $0$ if $N$ is even.
I am able to come up with a dynamic programming algorithm (inspired by dp - knapsack) using a two-dimensional array; however I am unable to keep track of the elements in a particular set and hence am not able to pass some typical cases.
Can anyone please suggest me what approach should I look into to solve this problem?
Any pointers are helpful.
Thanking You,
Dj

A: If you actually mean the difference $\sum S_1 - \sum S_2$, then just pick the largest $N/2$ numbers for $S_2$, and the smallest $N/2$ numbers for $S_1$.
If you mean the absolute difference (which is more likely), then there is an easy reduction from SUBSET-SUM showing that the decision variant of this problem is NP-complete. Conceivably you can find a very similar problem in the approximation algorithm literature - this would tell you how well an efficient algorithm can approximate the optimum.


text:
Q: Create an msi for jre by using wix which is to install jre files in my package? I have jre files which are used by mypackage.msi. I want to create the jre.msi which is another msi called by mypackage.msi. mypackage.msi is created by using wix files. So please do help me in this... I need the wix script for the above mentioned.... My package uses install script as well but the files are called by wix....

A: You won't be able to call the jre.msi from within the mypackage.msi as you can only have one msi transaction running at once. Either place the jre files within the mypackage.msi or create a burn bootstrapper to chain the msi's together. Check the wix chm included on install of wix.


text:
Q: Django loose coupling in apps I'm trying to code an application that can work for several projects. I'm facing a problem that I have always to specify the name of the project when I do the imports like doing import some_project_name.models  inside my app, how can I overcome this coupling so that I can use the app in several projects?

A: *

*Move the app to a common directory, outside of any project.

*Each project's PYTHONPATH must then include this common directory.


text:
Q: Intellij IdeaVim plugin - run current file Is it possible to call Intellij IDE actions with IdeaVim plugin (via some bindings maybe)?
For example:
:runfile

Will run current Java class.
I know about Quick Action Menu Cmd+Shift+A, but I want to use IDE in Vim style.

A: Yes, you can use :action and :actionlist commands.


text:
Q: Insert random codes between images loaded from mysql table I have the following code:
<?php

    mysql_connect("localhost","root","");
    mysql_select_db("bravo");
    $res=mysql_query("select * from coisas");

?>

<?php
    while ($row=mysql_fetch_array($res)) {

    echo "";

    }
?>

And i need to show an adsense code in random position between the images, can anyone help-me?

A: Add some code in the while:
while ($row=mysql_fetch_array($res)) {
   echo "";
   echo "--- adsense code here---";
}

Which will inject it after every image.
Or if you really want to place it in totally random positions:
$chanceOfAdsense = 35; // 35% chance of adsense appearing between any given images

while ($row=mysql_fetch_array($res)) {
   echo "";

   if (mt_rand(0,99) < $chanceOfAdsense) {
      echo "--- adsense code here---";
   }
}

A: Build an output array from the while loop, then count the number of values in it. Calculate a random number with rand() using count(array) and then iterate over the output array, with an if statement for when the index matches the random number.
<?php

    mysql_connect("localhost","root","");
    mysql_select_db("bravo");
    $res=mysql_query("select * from coisas");

?>

<?php
    $output_array = array();
    while ($row=mysql_fetch_array($res)) {

      $output_array[] = "";

    }

    //If you want the image to appear closer to middle, use fractions of $output_array
    //EG: rand(count($output_array)/3, count($output_array)*2/3));
    $rand_key = rand(0, count($output_array)-1);

    foreach ($output_array as $key => $img) {
       if ($key == $rand_key) {
           //echo your adsense code
       }
       echo $img;
    }
?>


text:
Q: Problems with HttpWebRequest/HttpWebResponse and cookies I'm having troubles with HttpWebRequest/HttpWebResponse and cookies/CookieContainer/CookieCollection.
The thing is, if the web server does not send/use a "path" in the cookie, Cookie.Path equals the path-part of the request URI instead of "/" or being empty in my application.
Therefore, those cookies do not work for the whole domain, which it actually does in proper web browsers.
Any ideas how to solve this issue?
Thanks in advance

A: Ah, I see what you mean. Generally what browsers really do is take the folder containing the document as the path; for '/login.php' that would be '/' so it would effectively work across the whole domain. '/potato/login.php' would be limited to '/potato/'; anything with trailing path-info parts (eg. '/login.php/') would not work.
In this case the Netscape spec could be considered wrong or at least misleading in claiming that path defaults to the current document path... depending on how exactly you read 'path' there. However the browser behaviour is consistent back as far as the original Netscape version. Netscape never were that good at writing specs...
If .NET's HttpWebRequest is really defaulting CookieContainer.Path to the entire path of the current document, I'd file a bug against it.
Unfortunately the real-world behaviour is not actually currently described in a standards document... there is RFC 2965, which does get the path thing right, but makes several other changes not representative of real-world browser behaviour, so that's not wholly reliable either. :-(

A: Seems like I cannot go any further with the default cookie handler, so I got annoyed and I did it the hard way. Haha. So parsing response.Headers["Set-Cookie"] myself is my solution. Not my preferred one but it works. And I simply eliminated the problem with splitting at the wrong comma using regular expressions.
If I could give out points here, I would give you some of them, bobince, because you gave me valuable information. I would also vote up if I could (need higher rep. score), but since this behavior probably is a bug, as you mentioned, I will accept that as an answer.
Thank you. :)

A: That's the way cookies work. 'Proper' web browsers do exactly the same, as originally specified in the ancient Netscape cookies doc: http://cgi.netscape.com/newsref/std/cookie_spec.html
Web apps must effectively always set a 'path' (often '/').


text:
Q: FlexMDI & RobotLegs: How to use multiple context, that can run independentely and sometimes shares the same view? Hy!
What I really need is to make a mainContext and within add other contexts that are kind of other applications. The main context has a MDICanvas where all the windows are added, but the problem is that some windows comes from different context. The next problem is that I want that windowX only listens to contextX:
Example:
 mainContext
  ->open login window
    ->open register window
  ->open register window
  taskmanagerContext
   servicesContext
    ->open add new service window
  worldEngineContext


text:
Q: rename files (preferably using python) I can not manage to solve a problem, hope you can help me.
I have several folders, containing files *.gz and I need to modify slightly the name as shown in the example below.
I was thinking about creating a dictionary with the {filenames:[ list spliting by "_"]} and then join again but changing the order of 001_R1 for R1_001 to finally "os.rename", but there must be a better way.
Thanks for your help.
Old name:
Folder1/

F02_TAGCTT_L005_R1_001.fastq.gz

F02_TAGCTT_L005_R1_002.fastq.gz

Folder2/

J02_TAGCTT_L005_R1_001.fastq.gz

J02_TAGCTT_L005_R1_002.fastq.gz

New name:
Folder 1/

F02_TAGCTT_L005_001_R1.fastq.gz

F02_TAGCTT_L005_002_R1.fastq.gz

Folder2/

J02_TAGCTT_L005_001_R1.fastq.gz

J02_TAGCTT_L005_002_R1.fastq.gz

A: If you have the GNU userspace, I'd use the rename command:
rename _R1_ _ *.gz

rename .fastq.gz _R1.fastq.gz *.gz

Otherwise, in Python, list the directories, filter on extension (or whatever), map the rename function and call os.rename on each pair of original and new names.

A: I think I have found a solution to my own problem. Since I have just started learning python, I am sure there are better ways to do it. Please, feel free to give me any advice.
This is the script to rename the files:
#!/usr/bin/env python -tt

import os

def fq_filelist():fqlist=os.popen('ls *.gz').read().rstrip().split('\n')
       return fqlist

def split_filename():
  mydict = {}
  fqlist = fq_filelist()
  for i in fqlist:
    a = i.rstrip('.fastq.gz')
    for x in a:
      mydict[i] = [a.split('_')]
  return mydict

def myrename():
  mydict = split_filename()
  for i in mydict.keys():
      for x in mydict[i]:
        newname = x[0]+"_"+x[1]+"_"+x[2]+"_"+x[4]+"_"+x[3]+".fastq.gz"
        os.rename(i,newname)

myrename()


text:
Q: Does C# 6.0 work for .NET 4.0? I created a sample project, with C#6.0 goodies - null propagation and properties initialization as an example, set target version .NET 4.0 and it... works.
public class Cat
{
    public int TailLength { get; set; } = 4;

    public Cat Friend { get; set; }

    public string Mew() { return "Mew!"; }
}

class Program
{
    static void Main(string[] args)
    {
        var cat = new Cat {Friend = new Cat()};
        Console.WriteLine(cat?.Friend.Mew());
        Console.WriteLine(cat?.Friend?.Friend?.Mew() ?? "Null");
        Console.WriteLine(cat?.Friend?.Friend?.TailLength ?? 0);
    }
}

*

*Wikipedia says .NET framework for C# 6.0 is 4.6.

*This question (and Visual Studio 2015 CTP test) says CLR version is 4.0.30319.0.

*This MSDN page says that .NET 4, 4.5, 4.5.2 uses CLR 4. There isn't any information about .NET 4.6.

Does it mean that I can use C# 6.0 features for my software that targets .NET 4.0? Are there any limitations or drawbacks?

A: Just want to focus on how to understand Wikipedia and other links.
When Wikipedia says C# 6.0 is with .NET Framework 4.6, it simply means the production version of the compiler (msc.exe) will be part of the .NET Framework 4.6 release. Via multi-targeting, such compilers can support lower versions of .NET Framework releases. Of course, since Roslyn became an open source project, the compiler is now completely an individual component.
When something refers the CLR version of 4.0.30319(.0), it actually can be .NET Framework 4.* (4.0, 4.0.*, 4.5, 4.5.*, 4.6, 4.6.*), as they all implement the CLR version 4 specification. Not to mention Xamarin/Mono also implement the same CLR specification.
The MSDN page is not yet fully updated, but some page already has .NET Framework 4.6 listed in Version Information section.
In all, language specs (as well as C# compiler), CLR specs, and .NET Framework releases are not tightly coupled with each other. It does give developers enough flexibility to utilize new compilers to target older CLRs and .NET Frameworks.

A: Yes, you can use newer compilers for older frameworks and get access to the new compiler features (as long as those features do not require new types introduced in .NET 4.6).
Other examples of this are methods with default parameters was introduced with C# 4.0 (.NET 4.0) but you are able to use them in .NET 2.0 (C# 2.0) and .NET 3.5 (C# 3.0) projects.
You are also able to use Extension Methods (introduced in C# 3.0) in .NET 2.0 or .NET 3.0 if you do one small workaround to make the compiler happy so it can find a attribute that was introduced in .NET 3.5.

A: Yes (mostly). C# 6.0 requires the new Roslyn compiler, but the new compiler can compile targeting older framework versions. That's only limited to new features that don't require support from the framework.
For example, while you can use the string interpolation feature in C# 6.0 with earlier versions of .Net (as it results in a call to string.Format):
int i = 3;
string s = $"{i}";

You need .Net 4.6 to use it with IFormattable as only the new framework version adds System.FormattableString:
int i = 3;
IFormattable s = $"{i}";

The cases you mentioned don't need types from the framework to work. So the compiler is fully capable of supporting these features for old framework versions.

A: If you are using building ascripts remember to change path to new builder:
set CPATH=C:\Program Files (x86)\MSBuild\14.0\Bin
[Rebuild.bat]
set CPATH=C:\Program Files (x86)\MSBuild\14.0\Bin
call nuget_restore.bat
"%CPATH%\msbuild" YourSolution.sln /t:Rebuild /p:Configuration=Release /fileLogger /flp:logfile=JustErrors.log;errorsonly /verbosity:minimal

if %errorlevel% neq 0 goto ERROR

REM call deploy Release  //Things like deploy files..
goto END

:ERROR
       echo ERROR: %errorlevel%
       pause

:END

A: Answer by @oobe is actually importatnt. I could build my solution through a batch file only after using the MSBuild.exe from C:\Program Files (x86)\MSBuild\14.0\Bin.


text:
Q: PopBackStack but keep the first fragment in android I am working on fragment transaction, and the backstack is like this:
fragA => fragB => fragC => fragD

I would like to return to fragA after back fromn the fragD
fragD => onBackPress => fragA

So, I tried code like:
getChildFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);

but it clear all the backstack , how can I keep the first fragment in the backstack? Thanks a lot

A: Because the "back stack" has a stack-like behaviour...last-in, first-out...the last fragment you added to the back stack will be popped out of the back stack first. You will need to implement the behaviour you required manually by specifying your own. This is not that hard using the FragmentManager class methods.
If you "tag" your fragments as you add them to the transaction...
 fragmentTransaction.add(new FragmentA(), "FragmentA_Tag");

you can later determine which fragment to show when the back button is pressed...
FragmentA f = fragmentManager.findFragmentByTag("FragmentA_Tag");
if(f != null){
    f.show();
}

How you determine which fragment to show it's entirely up to you. You can keep track of the current visible fragment or you can use the isHidden method of the Fragment class...BTW, I'm talking about native fragments here, not support library's fragment.

A: The backstack contains records about transactions, not fragments itself.
So you should not add first transaction's record (null -> fragA) to backstack.
And all other transaction's record should be added to backstack.
In this case, then you preformpopBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); android removed all fragments except fragA, because there isn't any records about how fragA was added.

A: E.g. you can do following:

*

*add fragA without adding it to backStack. So it always be in
activity, and won't react on back button.

*when you open fragD you should clear fragment BackStack. So when you press back button from D frag you go back to A.

P.S. There are other ways how to do what you want. It depends...

A: Only a few days ago I start learning about fragments in Android. And I faced with this problem too. Here I show my solution and how I resolve this. Please, fix if my code is not right. What we have at this time? Acivity, many fragments and their backstack. We want open every fragment from Drawer menu and clear all other fragments from backstack. But, we must hold only one Home fragment. When we stay on Home fragment and user press Back button app is goeing closing.
Activity.class
protected void onCreate(Bundle savedInstanceState)
{
    ...
    // adding Home fragment without adding transaction into backstack
    FragmentManager manager = getSupportFragmentManager();
    FragmentTransaction ft = manager.beginTransaction();
    ft.replace(R.id.container, HomeFragment.newInstance("args"), null);
    ft.commit();
}

@Override
public void onBackPressed() {
    if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
        finish();
    }
}

public void addFragmentFromMenu(Fragment fragment){
    String backStateName =  fragment.getClass().getName();
    clearBackStack();
    FragmentManager manager = getSupportFragmentManager();
    if(manager.getBackStackEntryCount()> 0)
    {
        boolean fragmentPopped = manager.popBackStackImmediate(backStateName, 0);

        if (!fragmentPopped && manager.findFragmentByTag(backStateName) == null) {
            //fragment not in back stack, create it.
            addFragment(fragment, manager, backStateName);
        }
    }
    else // no fragments
    {
        addFragment(fragment, manager, backStateName);
    }
}

public void addFragment(Fragment fragment, FragmentManager manager, String backStateName)
{
    FragmentTransaction ft = manager.beginTransaction();
    ft.replace(R.id.container, fragment, backStateName);
    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
    ft.addToBackStack(backStateName);
    ft.commit();
}

public void clearBackStack() {
    getSupportFragmentManager().popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}

And on click on drawer menu item
@Override
public boolean onNavigationItemSelected(MenuItem item) {

    int id = item.getItemId();

    if (id == R.id.nav_camera) {
        addFragmentFromMenu(CameraFragment.newInstance("cam1", "cam2"));
    } else if (id == R.id.nav_gallery) {
        addFragmentFromMenu(TestFragment.newInstance("test1","test2"));
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

A: After looking through many posts, I figured it out this way:
in fragC => fragD method, do two transactions:
1 clear back stacks, fragC => fragA
2 fragA => fragD
But in this way, the original state of fragA may be destroyed.
public static void changeFragCtoD(FragmentManager fm, Fragment fragD){
    fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
    FragmentTransaction fragmentTransaction = fm.beginTransaction();
    fragmentTransaction
            .replace(R.id.containerViewId, new fragAClass())
            .commit();

    FragmentTransaction fragmentTransaction = fm.beginTransaction();
    fragmentTransaction
            .replace(R.id.containerViewId, fragD)
            .addToBackStack(fragD.getClass().getName())
            .commit();
}

Now pressing back on fragD goes back to fragA.

A: I have done following way. Clear all fragment then add first home fragment
FragmentManager fm = getActivity().getSupportFragmentManager();
                    fm.popBackStack(Constants.TAG_HOME, FragmentManager.POP_BACK_STACK_INCLUSIVE);

                    ((MainActivity) activity).manageFragment(new HomeFragment(), Constants.TAG_HOME);
 //        write down below function in main activity
     public void manageFragment(Fragment fragment, String tag) {

            FragmentManager fragmentManager = getSupportFragmentManager();
            if (!fragmentManager.popBackStackImmediate(tag, 0)) {

                FragmentTransaction ft = fragmentManager.beginTransaction();
                ft.add(R.id.content_frame, fragment, tag);
                ft.addToBackStack(tag);
                ft.commit();

            }
        }

A: 1) Add First Fragment using below code
android.support.v4.app.FragmentManager fm = getActivity().getSupportFragmentManager();
        android.support.v4.app.FragmentTransaction ft=fm.beginTransaction();
        if (fm.findFragmentById(R.id.fragment_container) != null) {
            ft.hide(fm.findFragmentById(R.id.fragment_container));
        }
        ft.add(R.id.fragment_container, new OneFragment(),OneFragment.class.getCanonicalName())
                .addToBackStack(OneFragment.class.getCanonicalName()).commit();

2) Add Second Fragment From First fragment using below code
android.support.v4.app.FragmentManager fm = getActivity().getSupportFragmentManager();
                    android.support.v4.app.FragmentTransaction ft=fm.beginTransaction();
                    if (fm.findFragmentById(R.id.fragment_container) != null) {
                        ft.hide(fm.findFragmentById(R.id.fragment_container));
                    }
                    ft.add(R.id.fragment_container,new TwoFragment(),TwoFragment.class.getCanonicalName())
.addToBackStack(TwoFragment.class.getCanonicalName()).commit();

3) Add Third Fragment From Second fragment using below code
android.support.v4.app.FragmentManager fm = getActivity().getSupportFragmentManager();
                android.support.v4.app.FragmentTransaction ft=fm.beginTransaction();
                if (fm.findFragmentById(R.id.fragment_container) != null) {
                    ft.hide(fm.findFragmentById(R.id.fragment_container));
                }
                ft.add(R.id.fragment_container, new ThreeFragment(),ThreeFragment.class.getCanonicalName())
                        .addToBackStack(ThreeFragment.class.getCanonicalName()).commit();

4) Add Forth Fragment From Third fragment using below code
android.support.v4.app.FragmentManager fm = getActivity().getSupportFragmentManager();
                android.support.v4.app.FragmentTransaction ft=fm.beginTransaction();
                if (fm.findFragmentById(R.id.fragment_container) != null) {
                    ft.hide(fm.findFragmentById(R.id.fragment_container));
                }
                ft.add(R.id.fragment_container, new FourFragment(),ThreeFragment.class.getCanonicalName())
                        .addToBackStack(FourFragment.class.getCanonicalName()).commit();

5) onBackPressed() please write below code
@Override
    public void onBackPressed() {
        hideKeyboard(MainActivity.this);
        Fragment currentFragment = this.getSupportFragmentManager().findFragmentById(R.id.fragment_container);

        if (currentFragment.getClass().getName().equalsIgnoreCase(FourFragment.class.getName())) { // Using this code come from third fragment to first fragment
            Fragment f = this.getSupportFragmentManager().findFragmentByTag(TwoFragment.class.getCanonicalName());
            if (f != null) {
                this.getSupportFragmentManager().popBackStackImmediate(f.getClass().getCanonicalName(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
            }
        }else {
            super.onBackPressed();
        }
    }

A: Mark my words, complete FragmentTransactions are added to backstack not just a fragment, means even if you add and remove fragment in a single transaction calling poBackStack() will reverse the complete transaction. Passing a tag in its argument pops all the transaction till the tagged transaction or even pops the tagged transaction (in case FragmentManager.POP_BACK_STACK_INCLUSIVE added to the argument)
So it's more about how you added it not how you removing it.
See Performing Fragment Transactions

A: I know it's too late as an answer to your question, but this might be helpful to other people.
Since I have been looking for a solution for the past few days... I have solved it out with using for loop, and I think it's the simplest possible way.
First, initialize an integer in this way
int count = getSupportFragmentManager().getBackStackEntryCount();

where getBackStackEntryCount() will count the number of transactions.
And then just before calling the FragmentTransaction method in your fragD add this for loop
for (int i = 0; i < count; i++){
                getSupportFragmentManager().popBackStack();
            }

for loop will do the trick for you and popBackStack() will return you to the fragA
it looks like this
int count = getSupportFragmentManager().getBackStackEntryCount();
            for (int i = 0; i < count; i++){
                getSupportFragmentManager().popBackStack();
            }
            fragmentTransaction.replace(R.id.frame_layout, new FoodFragment(), "Food").addToBackStack(null);
            fragmentTransaction.commit();

A: You an override the onbackpressed (Mainactivity) and using the getBackStackEntryCount()  of the fragment manager, you can check if its not equal to 1 and popbackstack on only that condition.
@Override
public void onBackPressed() {
  if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
     if (!(getSupportFragmentManager().getBackStackEntryCount() == 1)) {
      getSupportFragmentManager().popBackStack() ;
    }
  }
}


text:
Q: Can ReSharper generate code that copies properties from one object to another? I'm looking for a way to accelerate a repeatable task when  I write code. I have ReSharper and I'm thinking a customization could do what I need.
I have two objects of the same type. I want to copy all of the public properties of one object to the other object. I want the tool, ReSharper in this case, to do generate the code for me. I'll tell it the names of the first object and the second object. I want it to find all the public properties of the first object and copy the values to the second object.
Here's the type of code I'm looking to have generated with a tool like ReSharper:
foo.Name = moo.Name;
foo.Age = moo.Age;
foo.City = moo.City;

Automating this simple code that copies values from right to left would save a ton of time and I'm thinking that ReSharper can do it. However, I haven't seen anything pop-up in searches for it though.
I'm not looking for a CodeSmith code generation technique or T4 template because I only want it to generate these specific lines inside my class, not generate and entire class or a separate file.
Does anyone know a way to press a few keystrokes, enter the "foo" and "moo" object names above and have the tool generate these copy from right to left lines of code?
Update:
I've found some documentation on building extensions to ReSharper, and this can probably be achieved by that path, but it looks really involved.
http://www.jetbrains.net/confluence/display/ReSharper/PowerToys+Pack+3.0+User+Guide
This is beginning to look like a weekend challenge unless someone else has already written it.

A: I don't believe Resharper can do this, but Open Source AutoMapper can. New to AutoMapper? Check out the Getting Started page.

A: It's really easy.  ReSharper doesn't do it, but you can use a super duper REGEX!
In Visual Studio:
    public string Email { get; set; }
    public string CellPhone { get; set; }
    public int NumChildren { get; set; }
    public DateTime BirthDate { get; set; }

*

*Select all your properties.  Hit CTRL-D to copy down.

*Now hit CTRL-H to replace.  Make sure .* is selected for Regex matching.

*Replace: public [\w?]* (\w*) .*  (This Regex may need to be tweaked)

*With: dest.$1 = source.$1;
Now you have some beautiful code you can put in a method of your choosing:
    dest.Email = source.Email;
    dest.CellPhone = source.CellPhone;
    dest.NumChildren = source.NumChildren;
    dest.BirthDate = source.BirthDate;

EDIT: New alternatives

*

*You can use AutoMapper for dynamic runtime mapping.

*Mapping Generator is really nice for static mapping.  It can generate the code above and it works well with R#.

A: I agree with @Ben Griswold.
In most situations, Automapper is the way to go.
But when you truly want to generate code that copies properties from one object to another, try this:

*

*Create a brand new class and derive from the class from which you want to copy properties.

*Right-click on this new derived class and click 'Refactor > Extract Interface'.

*Check all properties that you wish to copy.

*Choose 'Place beside' because this interface will be only temporary.

*Click 'Next'.

*Modify your derived class so that you are no longer inheriting from the base class and you are only implementing your new interface. Expect to see a red squiggle.

*Place your cursor over the red squiggle and hit 'ALT-ENTER' to 'Implement Members'.

*Click 'Finish'.

*Delete that temporary interface and modify your class so that you are no longer implementing it.

A: This is somewhat derivative from answer by @Jess (his regex didn't work for me on VS2013) but instead of using Visual Studio I am using regex101
Click link above and just paste your properties into Test string field and you will get them mapped.
Regex I used
public [A-Za-z\?]* ([A-Za-z0-9]*) .*
and replace
Dest.$1 = Source.$1
hope this saves you some time.

A: Here's a simple class to clone an object.  It's not exactly what you asked for but perhaps this will be useful for you:
//.Net 2.0
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace YourNameSpace {
   public static class ObjectCloner {
      public static T Clone<T>(T obj) {
         using (MemoryStream buffer = new MemoryStream()) {
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(buffer, obj);
            buffer.Position = 0;
            T temp = (T)formatter.Deserialize(buffer);
            return temp;
         }
      }
   }
}

A: Based on @Matas answer I created a more robust version using regex101 that ignores generics, attributes and comments and normalizes spaces.
Regex: *((\/+.*\n*.*)|(\[.*\]\n*.*))*public [A-Za-z\_\?\<\>]* ([A-Za-z0-9\_]*).*(\n| )*
Replace: $4 = person.$4,\n

A: Simply copying values from one side to the other is pretty ugly.
You might find it better to create a method to include in your classes that uses reflection to copy public properties.  You could save this method in resharper to regenerate into other classes you need this functionality in.

A: This is the kind of thing for which Cog shines.  Basically, Cog is code generation tool.  Code is generated via Python.


text:
Q: drawing ball from an urn with replacement Suppose we have an urn with $N$ white balls and $M$ black balls. Suppose we draw $n$ balls and each time a ball is drawn, then we put it back. Let $X =$ number of white ball we get. Let $U = \{1,2,...,N+M\}$. For our probability space, we take $\Omega = U^n $. We want to find
$$ P(X = x) \; \; \; \text{where} \; 0 \leq x \leq n  $$
I am stuck trying to solve this problem. I know the cardinality of $\Omega$ is $(N+M)^n$.

A: We have $X\sim Bin(n,p)$, where $p=\frac{N}{N+M}$ is the probability that you draw a white ball.
For a binomial distribution $$P(X=x)=\binom{n}{x} p^x (1-p)^{n-x}$$
You can think of it this way: There are $\binom{n}{x}$ ways you can draw $x$ white balls and each of these ways has a probability of $p^x (1-p)^{n-x}$.


text:
Q: I am receiving 2 line items when running workflow I am very new to creating workflows; this is my very first one.
After creating a new item, I would like my workflow to push the result for a calculated column.  And it does that, but also adds another line item.
This is my workflow:
1. Create Item in Project / ACR Number Assignment Log.
2. '{WorkflowVariable:Change Control}' equals '{WorkflowVariable:Change    Control}' or '{WorkflowVariable:Project File}' equals '{WorkflowVariable:Project File}'.
3. The Location field on the current item equals 'VH' or The Location field on the current item equals 'MN' or The Location field on the current item equals 'DR'.
4. Commit pending changes.
5. Wait for a change in 'ID'.
6. Send a message to:
{ItemProperty:Created By}

7. End the workflow.

This is my result:
CC-IS-VH-000
CC-IS-VH-059
Of course, the second line item is the desired result.  How can I achieve only the desired result?


text:
Q: Hide directory name from URL I just want to hide the dir name from URL.
From: example.com/dirname/somepage
To: example.com/somepage
That code doesn't work for me, I have probably made some mistakes
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule    /  /dir/$1    [L]

I have already this in .htaccess (to hide php extension)
RewriteEngine On
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteCond %{REQUEST_URI} !/$
RewriteRule (.*) $1\.php [L]

A: This should be your complete .htaccess:
Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteCond %{REQUEST_URI} !/$
RewriteRule (.*) $1\.php [L]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+dirname/([^\s]+) [NC]
RewriteRule ^ %1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (?!^dirname/)^(.*)$ /dirname/$1 [L,NC]


text:
Q: Comparing two lists of stellar x-y coordinates to find matching objects I have two .txt files that contain the x and y pixel coordinates of thousands of stars in an image. These two different coordinate lists were the products of different data processing methods, which result in slightly different x and y values for the same object.
File 1 *the id_out is arbitrary

id_out  x_out       y_out         m_out
0       803.6550    907.0910     -8.301
1       700.4570    246.7670     -8.333
2       802.2900    894.2130     -8.344
3       894.6710    780.0040     -8.387

File 2

xcen      ycen      mag           merr
31.662    37.089    22.759        0.387
355.899   37.465    19.969        0.550
103.079   37.000    20.839        0.847
113.500   38.628    20.966        0.796

The objects listed in the .txt files are not organized in a way that allows me to identify the same object in both files. So, I thought for every object in file 1, which has fewer objects than file 2, I would impose a test to find the star match between file 1 and file 2. For every star in file 1, I want to find the star in file 2 that has the closest match to x-y coordinates using the distance formula:
distance= sqrt((x1-x2)^2 + (y1-y2)^2) within some tolerance of distance that I can change. Then print onto a master list the x1, y1, x2, y2, m_out, mag, and merr parameters in the file.
Here is the code I have so far, but I am not sure how to arrive at a working solution.
#/usr/bin/python
import pandas
import numpy as np

xcen_1 = np.genfromtxt('file1.txt', dtype=float, usecols=1)
ycen_1 = np.genfromtxt('file1.txt', dtype=float, usecols=2)
mag1 = np.genfromtxt('file1.txt', dtype=float, usecols=3)

xcen_2 = np.genfromtxt('file2.txt', dtype=float, usecols=0)
ycen_2 = np.genfromtxt('file2.txt', dtype=float, usecols=1)
mag2 = np.genfromtxt('file2.txt', dtype=float, usecols=2)
merr2 = np.genfromtxt('file2.txt', dtype=float, usecols=3)

tolerance=10.0

i=0
file=open('results.txt', 'w+')
file.write("column names")
for i in len(xcen_1):
    dist=np.sqrt((xcen_1[i]-xcen_2[*])^2+(ycen_1[i]-ycen_2[*]^2))
    if dist < tolerance:
        f.write(i, xcen_1, ycen_1, xcen_2, ycen_2, mag1, mag2, merr2)
    else:
        pass
    i=i+1
file.close

The code doesn't work as I don't know how to implement that every star in file 2 must be run through the test, as indicated by the * index (which comes from idl, in which I am more versed). Is there a solution for this logic, as opposed to the thinking in this case:
To compare two independent image coordinate lists with same scale but coordinate-grid having some rotation and shift
Thanks in advance!

A: You can use pandas Dataframes. Here's how:
import pandas as pd
# files containing the x and y pixel coordinates and other information
df_file1=pd.read_csv('file1.txt',sep='\s+')
df_file2=pd.read_csv('file2.txt',sep='\s+')
join=[]
for i in range(len(df_file1)):
    for j in range(len(df_file2)):
        dis=((df_file1['x_out'][i]-df_file2['xcen'][j])**2+(df_file1['y_out'][i]-df_file2['ycen'][j])**2)**0.5
        if dis<10:
            join.append({'id_out': df_file1['id_out'][i], 'x_out': df_file1['x_out'][i], 'y_out':df_file1['y_out'][i],
                         'm_out':df_file1['m_out'][i],'xcen':df_file2['xcen'][j],'ycen':df_file2['ycen'][j],
                         'mag':df_file2['mag'][j],'merr':df_file2['merr'][j]})

df_join=pd.DataFrame(join)
df_join.to_csv('results.txt', sep='\t')


text:
Q: Reverse Quadratic Formula in Javascript I have a PHP page with includes two text boxes, id=rev1 and id=rev2. Here is the formula used to populate rev2 based on rev1 input.
var rev2 = Math.round((((a*((rev1-c)*(rev1-c))+d)/100+1)*rev1) * 100) / 100;
I plan to setup two more text boxes - rev3 and rev4 - with rev4 is the input box (essentially rev4=rev2 and rev3=rev1).
I'd like a javascript function that scrolls through the various rev3 options between rev3=20.01 and rev3=60 in 0.01 increments to find rev4 as input and returns the rev3 value.
Can anyone assist? It would be much appreciated.


text:
Q: How to determine type in disk file before reading to ArrayList? If I read a file using
Scanner in = new Scanner(new File(diskFile));

How, after that, would I be able to determine which type it is so I can read it into an arraylist of the same type? It's easier to do when you know which type it is such as int
do {
    nextInt = in.nextInt();
    n.add(nextInt);
}while(in.hasNextInt() == true);

but if I don't know if the file type is String, int, double, etc. How would I be able to add them to an ArrayList of the same type? So my solution would be to figure out the type before adding it to an ArrayList, but I have no idea how to do that.

A: Assuming you have a single unknown value per line in your input file, I'd recommend you read it as a String and then test the string value using the simple parsers available with the common types.  You can test by catching exceptions.  Here is an example for Integer.
        int newData = 0;
        boolean haveInt = true;
        try {
                 newData = Integer.parseInt(theInputString);
        } catch (NumberFormatException e) {
            haveInt = false;
        }
        if (haveInt) {
           intArrayList.add(newData);
        }


text:
Q: How can I supply style selector to SVG (byte[]) when I use OmniFaces graphicImage tag? Follow-up to How to embed SVG graphics properly in JSF application using OmniFaces
I'm using the OmniFaces 2.1 snapshot in order to output SVG files from byte[] arrays. I need to suffix #a on SVG URL's in order to activate a CSS style inside the SVG.
Example img:

As you can see, my #a is appended at the right side of the URL as %23a.
If this had been a regular URL it would be

It would then pick the CSS style and, in my case, paint the background of this sign yellow.
I'm really hoping BalusC comes to my rescue here. Heh. :)

A: As per this commit, the <o:graphicImage> got a new fragment attribute. This should enable you to pass SVG view modes via URL fragment identifier. It's available in today's 2.1 SNAPSHOT.
E.g.
<o:graphicImage value="#{bean.svg(imageId)}"
    type="svg" fragment="svgView(viewBox(0,200,1000,1000))" />


text:
Q: VBScript Out Of Memory Error I have a classic ASP CRM that was built by a third party company.  Currently, I have access to the source code and am able to make any changes required.
Randomly throughout the day, usually after some prolonged usage by users, most of my pages start getting an Out of Memory error.
The way that the application is built, is all the pages and scripts pull core functions from a Global.asp file.  In that file are embeds to other global files as well, but the error presented shows

Out Of Memory
WhateverScriptYouTriedToRun.asp Line 0

Line 0 is the include for the global.asp file.   Once the error occurs, after an unspecified amount of time the error occurence subsides for some time but then begins to reoccur again.  With how the application is written, and the functions it uses, and the "diagnostics" I've already done - it seems to be a common used function that is withholding data such as recordset or something of that nature and then not releasing it properly.  Other users then try to use the same function and eventually it just fills up causing the error. The only way for me to effectively clear the error is to actually restart IIS, Recycle the App Pool, and Restart the SQL Server Services.
Needless to say, myself and my users are getting annoyed....
I can't pinpoint the error due to the actual error message presented being Line 0 - but from there I have no idea where in the 20K lines of code it could be hanging up.  Any thoughts or ideas on how to isolate or at least point me in the right direction to begin clearing this up?  Is there a way for me to increase "memory" size for VBScript?  I know there is a limitation but is it set at say...512K and you can increase it to 1GB?
Here are things I have tried:

*

*Removing SQL Inline statements into Views

*Going through several hundred scripts and ensuring that every OpenConnection & OpenRecordSet is followed by an appropriate Close.

*Going through the Global File and commenting out any large SQL statements such as ApplicationLog (A function that writes the executed query into a table).

*Some smaller script edits.

A: Common Memory Leak
You say you are closing all recordsets and connections which is good.
But are you deleting objects?
For example:
Set adoCon = new
Set rsCommon = new

'Do query stuff

'You do this:
rsCommon.close
adocon.close

'But do you do this?
Set adoCon = nothing
Set rsCommon = nothing

No garbage collection in classic ASP, so any objects not destroyed will remain in memory.
Also, ensure your closes/nothings are run in every branch.  For example:
adocon.open
rscommon.open etc

'Sql query
myData = rscommon("condition")

if(myData) then
  response.write("ok")
else
  response.redirect("error.asp")
end if

'close
rsCommon.close
adocon.close
Set adoCon = nothing
Set rsCommon = nothing

Nothing is closed/destroyed before the redirect so it will only empty memory some of the time as not all branches of logic lead to the proper memory clearance.
Better Design
Also unfortunately it sounds like the website wasn't designed well.  I always structure my classic ASP as:
<%
    Option Explicit

    'Declare all vars
    Dim this
    Dim that

    'Open connections
    Set adoCon...
    adocon.open()

    'Fetch required data
    rscommon.open strSQL, adoCon
        this = rsCommon.getRows()
    rsCommon.close

    'Fetch something else
    rscommon.open strSQL, adoCon
        that = rsCommon.getRows()
    rsCommon.close

    'Close connections and drop objects
    adoCon.close
    set adoCon = nothing
    set rscommon = nothing

    'Process redirects
    if(condition) then
        response.redirect(url)
    end if
%>
<html>
<body>

<%
    'Use data
    for(i = 0 to ubound(this,2)
        response.write(this(0, i) & " " & this(1, i) & "<br />")
    next
%>

</body>

</html>

Hope some of this helped.

A: Have you looked at using a memory monitoring tool to see how much memory fragmentation is happening?  My guess at a possible cause is that some object of a size is trying to be created but there isn't enough room in the memory to store it as one contiguous chunk.  Imagine needing room to store an object that would take 100 MB and while there may be several hundred megabytes free, the largest contiguous chunk is 90MB then this doesn't fit.

Debug Diagnostic Tool v1.1 would be a tool where Bernard's articles may help in understanding how to use the tool.
Another thought is the question of how much string concatenation is there in the code?  I remember where I used to work had problems with doing a lot of string concatenation operations that sucked up memory that may be another idea to consider.

Yeah, I could see some shock at that kind of number the first few times you see it but then if you understand what the code is doing it may make sense for why so much space gets reserved right off the bat at times.

I haven't used that debug tool specifically but I did have a tool that took a snapshot of memory when pages were hung so I couldn't tell if there was a performance impact of the tool or not.  Course in my case I used a similar tool in 2004 so it has been a few years since I've had to research this kind of issue.

A: Just going to throw this in here, but this problem has taken a long time to solve.  Here's a breakdown of what we did:

*

*We took all the inline SQL and made SQL Views, every SELECT statement is now handled with a VIEW first.

*I took every single SQL INSERT and UPDATE (as much as I could without breaking the system) and put them into Stored Procedures.
#2 was the one item that really made the biggest difference

*Went through several thousand scripts, and ensured that variables were properly disposed of, and all the DB Open Connections were followed correctly with a Close Connection and same with Open/Close RecordSet.

*One of the slow killers was doing something like:
ID = Request.QueryString("ID)
at the top of the page.  Before redirecting, or closing a page, there is always a:
Set ID = Nothing

or the complete removal of the inference.


text:
Q: Inhomogeneous Second Order PDE Given $3u_{tt} + 10u_{xt} + 3u_{xx} = \sin(x+t)$ find the general solution.
I have yet to solve any inhomogeneous second order PDE (or even first order ones at that). For homogeneous PDE of same order, I managed to solve them by factoring the operators and so forth. Being new to PDEs (self studying via Strauss PDE book) I lack the intuition to find a clever way of solving these, however from my experience with ODEs I reckon there is a way to solve these by first solving the associated homogeneous first by factoring operators and so forth and stuff.. but not finding much progress on incorporating the $\sin(x+t)$ term.
Any help & direction to solving this would be greatly appreciated.

A: I'm sure you have some change of variables formulas in your PDE course, meant to simplify the given equation. I don't remember the formulas, but there is a way to avoid them. The equation can be written in the following way:
$$ A u = \sin(t+x) $$ where $A$ is the operator
$$ A= 3\frac{\partial^2}{\partial t^2}+10\frac{\partial^2}{\partial t \partial x} +3 \frac{\partial^2}{\partial x^2}.$$
In this case, the operator can be factored (just like a binomial expression) in the following way:
$$ A =\left( \frac{\partial }{\partial t}+3\frac{\partial}{\partial x}\right)\left(3\frac{\partial}{\partial t}+\frac{\partial }{\partial x} \right).$$
Now, change the variables such that each of the two factors will be a partial derivation.
$$ \frac{\partial}{\partial y}=\left( \frac{\partial }{\partial t}+3\frac{\partial}{\partial x}\right), \frac{\partial}{\partial z}=\left(3\frac{\partial}{\partial t}+\frac{\partial }{\partial x} \right)$$
For this, change the variables to $\displaystyle \begin{cases} t=y+3z \\ x=3y+z \end{cases}$ and define $w(y,z)=u(t,x)$. Then we have
$$\frac{\partial^2w }{\partial y \partial z}=Au= \sin(x+t)=\sin(4y+4z)$$
Integrate two times, with respect to $y,z$ and you will find $w$. From there it is easy to get to $u$.
This might not be the most efficient method (for an exam, for example), but it might show from where the change of variables formulas come from. I did this in my exam, once, because I didn't remember the formulas. (I got zero points, because my teacher didn't like the method and there were some small mistakes). It is best to learn all the cases for change of variable, because that gains you time in an exam, but is also important to know from where those change of variable formulas come from.

A: $$3u_{tt} + 10u_{xt} + 3u_{xx} =sin(x+t)$$
$$(3 \partial_{t} + \partial_{x})( \partial_{x} + 3 \partial_{t}) u= sin(x + t)$$
The characteristic lines of the two operators, we make the following change of variables,
$$\xi = t- 3x ,\,\, \eta = 3t-x,$$
$$u_t = u_{\xi} + 3 u_{\eta},\,\,\, u_{x} = -3 u_{\xi} - u_{\eta}.$$
Let's find the operators,
$$(3\partial_{t} + \partial_{x})u = 8 (\partial_{\eta})u, $$
$$(\partial_{t}  + 3 \partial_{x}) = -8 (\partial_{\xi})u.$$
After finding the variables $x$ and $t$ in terms of the variables $\xi$ and $\eta$, it is the time to write the wave equation in terms of the new variables,
\begin{align}
    (3 \partial_{t} + \partial_{x})( \partial_{t} + 3 \partial_{x}) u &= \sin(x + t)\\
    [8 (\partial_{\eta})] [-8 (\partial_{\xi})]u&=\sin(\frac{\eta - \xi}{2}),
\end{align}
$$ u_{ \xi \eta}(\xi, \eta) = -\frac{1}{64} \sin(\frac{\eta - \xi}{2}).$$
4
Integrating with respect to $\eta$ and with respect to $\xi$,
$$u_{\eta} = - \frac{1}{32} \cos{\frac{\eta - \xi}{2}} + f(\eta),$$
$$u(\xi,\eta) =-\frac{1}{16} \sin{\frac{\eta - \xi}{2}} + F(\eta) + g(\xi).$$
Finally, writing the solution in its original variables,
$$ u(x,t) = -\frac{1}{16} \sin(x+t) + F(3t -x) + g(t-3x).$$


text:
Q: How do I find if it is the last line while reading a file from within a loop in perl I am working on a log parsing script using Perl. I am reading the log file as follows:
open(LOGFILE, "$logFile") || die "Error opening log file $logFile\n";
while(<LOGFILE>)
{
  #Processing statements goes here.
}

Now in processing statements I want to check if the file reading pointer is on the last line. if yes then want to process a condition before exiting.
So the question is from within the while loop which is being used to read the file line by line, How do I find out if it's on the last line?

A: If you only care about the last line, take a look at File::ReadBackwards. It was specifically designed for logfiles and situations where the items of interest are at the end.
Once you install that module, you can pop off the last line only (rather than going through the whole file until it's found) quite easily:
#!/usr/bin/env perl
use strict;
use warnings;
use File::ReadBackwards;

my $fh = File::ReadBackwards->new( 'dir_walk.rb' )
    or die "Can't read 'dir_walk.rb': $!";

my $last_line = $fh->readline;

print $last_line;

Edit: For what it's worth, I would only recommend this if you don't want to look through the whole file. That is, if you are going to read through the entire file no matter what, then this is probably not the best solution. (I am not quite sure from your question whether you only want to check for a specific item in the last line, or if you also care about the rest of the log.)

A: my $last;
while(<MYFILE>) {
   $last = $_ if eof;
}

Though unless you are doing something with every other line, this is pretty inefficient.


text:
Q: Why is my strcmp() failing? I am a C newbie and learning string tokenizing. I am trying to compare two strings in the following way. But the string comparison I am doing is failing.
Can you please let me know what I am missing here?
I couldn't find another similar question, may be due to my inexperience in C. If one exists, can you please redirect me to it?
char* input = "comparer here";

char* args[5];

int counter = 0;
char *tok = strtok(input, " ");
while (tok != NULL) {
   args[counter] = tok;
   counter ++;
   if (counter == 5)
     break;
   tok = strtok(NULL, " ");
}

char* comp_str = "comparer";
if (strcmp(args[0], comp_str) == 1) {
        // do some stuff
}

A: It fails because strcmp (and its siblings) returns a zero value if they are equal, a negative value if the first is less than the second, and a positive value if the first is greater than the second.
The negative or positive value is not specified.  In most implementations it is the difference of the first different characters.   But that is not guaranteed.
Comparing the result to 1 is very unlikely to succeed.

A: You are defining a string called input, but using a variable called message, undefined.

A: strcmp() returns 0 when the two strings to be compared are equal. You should change 1 to 0 if you are trying to check if the two strings are equal.


text:
Q: Force git to reject commits with specific content Is it possible to add a comment to my code so GIT refuses to commit it?
The reason is that sometimes I'm working on two different strategies for fixing a problem, e.g. two different classes. Then it would be nice if could add a comment somewhere in the class like
// DONT COMMIT so that I don't accidentally commit two parallel classes.

A: A simple pre-commit hook that does the job:
#!/usr/bin/env bash

# The text that refuses the commit
# Change it to match your needs; keep it enclosed in single quotes
MARKER='// DONT COMMIT'

# Verify the staged files for the presence of the marker text
if git diff --cached --name-only | xargs grep -q "$MARKER"; then
  echo 'Cannot commit because the "no-commit" marker has been found in one of the staged files.' 1>&2
  # Refuse to commit
  exit 1
fi

Put it into the file .git/hooks/pre-commit in your project and make the file executable (chmod +x .git/hooks/pre-commit).
It is just a stub and probably does not work as expected in all situations. Expand it to match your needs.
You can tell Git to skip the hooks by passing the option -n (or --no-verify) in the git commit command line.

A: I don't know how you could do that.... But I think you could get similar functionality other ways.

*

*Add a separate version of your .py file that you add to your .gitignore (git ignores every file listed here.) When testing things out you can import this trial class from the new .py

*Use git for this. If your trialling a new feature why not make a new branch for what you are testing:
git checkout -b trying_new_class_definition
This let's you swap your two definitions by just swapping branch.
If you make updates to the main codebase you may need to rebase these onto your trial branch:
git checkout trying_new_class_definition
git rebase master


text:
Q: Why Windows 10 has a svchost process that listen on port 53? I believe this starts only recently. When my Windows 10 starts, a svchost process will start automatically and listens at port 53.
I noticed this because my pi-hole docker container failed to start recently, and I have been using a pi-hole container for about a year on the same computer.
I checked the Internet, and I could not find any information about some new Windows 10 feature that acts as a local DNS.
Update
Thank you @user1686 for the tip.
By using this command netstat -ab -p udp, I found the port is owned by the SharedAccess service which name is actually the Internet Connection Sharing (ICS) in the Services manager and which I believed is started by the Host Network Service.
Active Connections

  Proto  Local Address          Foreign Address        State
  UDP    0.0.0.0:53             *:*
  SharedAccess

But I could not found out why the Host Newtork Service suddenly got started. Since it is to "Provides support for Windows Virtual Networks.", I guess it is due to some changes in the recent Docker Desktop update which changed how docker containers utilize the Windows network.

A: credits to https://answers.microsoft.com/en-us/windows/forum/all/solved-unable-to-stop-internet-connection-sharing/b01e1ebc-4f9d-4bf6-8d15-37a782fa03ff
The key issue is the Host Network Service, which, I guess, is required by some Hyper-V services. However, the related service still works even after port 53 is used by other processes.
So to solve this issue:

*

*Stop the Host Network Service service

*Stop the Internet Connection Sharing service

*Start your service/process that uses port 53

*Start the Host Network Service service


text:
Q: Xcode "po" command retains value I've been debugging my code and found that my manager was deinitialised (that was cause of my bug - not calling delegate methods).
What's strange, that during debugging process I've used "po" command after setting the manager's delegate (weak) and it prevented it from being deinitialised (delegate methods were called).
Why is that? Is it proper behaviour?
Xcode 8.3, swift 3.1
EDIT:
//a tap starts everything :)

    @IBAction func shareButtonPressed(_ sender: Any) {
        let requestManager = FacebookPostRouteRequest() //bug fixed by changing to instance variable
        requestManager.delegate = self
        requestManager.showShareBadgeDialog(self.badge!, onViewController: self)
    }

//in FacebookPostRouteRequest
        final weak var delegate: FacebookPostRouteRequestDelegate?

        func showShareBadgeDialog(_ badge: Badge, onViewController viewController: UIViewController) {
            let dialog = self.initDialog(onViewController: viewController)
            guard let imageURL = badge.imageURL else {
                self.delegate?.facebookPostRouteRequest(self, didCompleteWithResult: false)
                return
            }

            dialog.shareContent = self.generateImageShareContent(imageURL)
            self.show(dialog)
        }

 private func show(_ dialog: FBSDKShareDialog) {
        OperationQueue.main.addOperation {
            dialog.delegate = self //when printed out dialog.delegate delegate methods were called! Deinit of FacebookPostRouteRequest is not called.
            let showResult = dialog.show()
            ...
            }
        }

extension FacebookPostRouteRequest: FBSDKSharingDelegate {
    func sharer(_ sharer: FBSDKSharing!, didCompleteWithResults results: [AnyHashable : Any]!) {
        ...
    }
        //other delegate methods implemented as well

}

A: Your problem is here:
@IBAction func shareButtonPressed(_ sender: Any) {
    let requestManager = FacebookPostRouteRequest()
    requestManager.delegate = self
    requestManager.showShareBadgeDialog(self.badge!, onViewController: self)
}

After the last line, the requestManager object will be disposed because it's no longer referenced and will not call any of the delegate methods.
Make requestManager an instance variable:
let requestManager = FacebookPostRouteRequest()
@IBAction func shareButtonPressed(_ sender: Any) {
    requestManager.delegate = self
    requestManager.showShareBadgeDialog(self.badge!, onViewController: self)
}

Your issues with the debugger are probably race conditions for stopping the main thread.


text:
Q: How to get the 'value' by dynamically passing the 'enum member name' in Python? How to get the 'value' by dynamically passing the 'enum member name' in Python?
For an example consider the below enum
import enum
class Animal(enum.Enum):
    DOG = "This is Dog"
    CAT = "This is cat"
    LION = "This is Lion"

I want to write a common function something like below, and it has to return This is Dog.
def get_enum_value("DOG"):
    #
    # SOME CODE HERE TO GET THE VALUE FOR THE GIVEN (METHOD ARGUMENT) ENUM PROPERTY NAME
    #

A: Simplified and full code :
## Enum definition
import enum
class Animal(enum.Enum):
    DOG = "This is Dog"
    CAT = "This is cat"
    LION = "This is Lion"

## method to return enum value when pass the enum member name
def get_enum_member_value(enum_member_name):
    enum_member_value = Animal[enum_member_name].value
    return enum_member_value

## execute the method and print the value
print(get_enum_member_value("DOG"))

A: Answer based on question edit:
The functionality you're after is built in:
>>> Animal["DOG"].value
"This is Dog"

or
>>> member = "DOG"
>>> Animal[member].value
"This is Dog"

The only reason to make that a function would be for error handling -- for instance, if you want to gracefully handle a non-member name being passed in.

I see two possible questions (the names of your functions and usage of terminology are confusing):

*

*How to get the .value property;

*How to get the value of any property (the two built-in are value and name)

Actually, I know also see a third option:

*

*How to get the value of property whose name is passed in (so get_enum_value is a method of Animal, not a separate function as your indentation would suggest)

Answering only the last question, the solution is something like:
import enum

class Animal(enum.Enum):
    #
    DOG = "This is Dog"
    CAT = "This is cat"
    LION = "This is Lion"
    #
    def get_enum_value(self, enum_property_name):
        return getattr(self, enum_property_name)

and in use:
>>> Animal.LION.get_enum_value('name')
'LION'


text:
Q: Setup different Internal IP for worker nodes I want to setup a kubernetes cluster locally where I would like to have 1 master node and 2 worker nodes. I have managed to do that but I am not able to access pods or see any logs of a specific pod because Internal IP address is the same for all nodes.
vagrant@k8s-head:~$ kubectl get nodes -o wide
NAME         STATUS   ROLES    AGE     VERSION   INTERNAL-IP   EXTERNAL-IP   OS-IMAGE             KERNEL-VERSION      CONTAINER-RUNTIME
k8s-head     Ready    master   5m53s   v1.15.0   10.0.2.15     <none>        Ubuntu 16.04.6 LTS   4.4.0-151-generic   docker://18.6.2
k8s-node-1   Ready    <none>   4m7s    v1.15.0   10.0.2.15     <none>        Ubuntu 16.04.6 LTS   4.4.0-151-generic   docker://18.6.2
k8s-node-2   Ready    <none>   2m28s   v1.15.0   10.0.2.15     <none>        Ubuntu 16.04.6 LTS   4.4.0-151-generic   docker://18.6.2

In order to resolve this problem I have found out that following things should be done:
- add KUBELET_EXTRA_ARGS=--node-ip=<IP_ADDRESS> in /etc/default/kubelet file
- restart kubelet by running:sudo systemctl daemon-reload && sudo systemctl restart kubelet
The problem is that /etc/default/kubelet file is missing on this location and I am not able to add this additional parameter. Tried with creating file manually but it looks like it is not working when I restart kubelet, IP address is still the same.
Anyone faced this issue with missing /etc/default/kubelet file or if there is another easier way to setup different Internal IP addresses?

A: It is normal to have the same IP in every node for the Kubernetes Cluster running in VirtualBox, the reason is that it is a NAT newtork not intended for communication between virtual machines, the 10.0.2.15 IP is NATed when accessing the outside world.
The following diagram shows the networks that are created in a Kubernetes Cluster on top of VirtualBox, as you can see, every node has the same IP in the NAT newtork but different IPs on the other networks:

In order to access the PODs you can use a NodePort and the HOST ONLY network.
See a full example and download the code at Building a Kubernetes Cluster with Vagrant and Ansible (without Minikube). It is a tutorial that explains how to launch a Kubernetes cluster using Ansible playbooks, Vagrant and VirtualBox.
It uses Calico for networking and it includes another tutorial for installing Istio if you need a micro service mesh.