text:
Q: USB having periodic connection issues over <15 foot cable run - EMI or? I hope this is an appropriate topic for this stack exchange. I have a cable run just shy of 15 feet that connects a few monitors (3) and usb 3.0 devices (a USB 3.0 hub) to one of the servers on the other end of the run, in the next room. There are a total of 5 cables ran together: 3 DVI/monitor, 1 standard AC power (to power the monitors and USB hub off the same battery system of the servers, it is only in the last 4 feet of run), and 1 USB 3.0.
When I first setup the run, I tested both a powered 15ish foot active extension cable and a non-powered 15 foot cable and determined that the active cable had considerably better transfer speed (actually hitting USB 3.0 spec) so I left it with that. Weeks later I started getting complaints of all of the USB devices connected through the HUB periodically disconnecting and reconnecting. I first thought the HUB was acting up, but I ended up disconnecting the active USB cable and trying the passive cable (running it through the doorway instead of with the others) and the connection issues went away entirely. I left it like that for a few days, and with no connection dropouts, I installed a new active USB 3.0 cable in the existing cable run, and tested again for speed/dropouts. Transfer speeds went back up to USB 3.0 spec and no dropouts.
Fast-forward another few months, and same issues as before have started to appear. I know setting this up originally I could have EMI issues with the AC power cord in the same run, there's just not another good way to run that AC line separately, and it's a fairly short section that the cables are actually ran together (I wanted to try it like this first and see if we had issues). I did get a pretty heavily shielded AC cable, FWIW. The only thing that has stopped me from yanking the power cable out from this line is that this seems to only happen after a period of time from starting with a brand new USB cable.  What do you all think? Is it probably EMI or do you and other ideas that I could try as well?
Edit: In addition to the USB devices dropping out and reconnecting, there are reports that while typing, a key will suddenly "stick" and you'll end up typing something like thisssssssssssssssss.


text:
Q: DatagridView Column Sorting I have bind datagrid with following values.
Id as Int,Price as int, IsActive as bit.
Now I want to sort data based on IsActive when i click on column header of IsActive.
I did the same thing for Id and it working properly  but for IsActive it is not working.
Below is my code for IsActive field :
 private void dataGridView1_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
    {
        // Try to sort based on the cells in the current column.
        e.SortResult = System.String.Compare(e.CellValue1.ToString(), e.CellValue2.ToString());

        // If the cells are equal, sort based on the ID column.
        if (e.SortResult == 0 && e.Column.Name != "IsActive ")
        {
            e.SortResult = System.String.Compare(
                dataGridView1.Rows[e.RowIndex1].Cells["IsActive "].Value.ToString(),
                dataGridView1.Rows[e.RowIndex2].Cells["IsActive "].Value.ToString());
        }
        e.Handled = true;
    }

I want to know How can i sort Boolean data in datagridView.

A: According to MSDN -DataGridView.SortCompare Event, The SortCompare will be triggered only for columns that have their "SortMode" property set to "Automatic":
DataGridViewColumn col = this.dataGridView1.Columns["IsActive"];
col.SortMode = DataGridViewColumnSortMode.Automatic;

If I may, I would suggest letting .Net doing the dirty job.
Lets assume you have 3 rows in your grid view:

Id  Price  IsActive
1   1        1
2   2        1
3   11       1

In the way you have implemented the sorting, if you sort by price, row 3 will precede row 2 (the string "11" comes before "2"...).
Preferably you would have your data in a data table, bind the datatable to the gridview and let .Net do the rest:
 /// <summary>
    /// Binds the Grid view.
    /// </summary>
    private void BindGridView()
    {
        //Creating the columns.
        //The gridview will know how to sort Items by the type specified in the second argment
        DataTable dt = new DataTable();
        dt.Columns.Add("Id",typeof(int));
        dt.Columns.Add("Price",typeof(int));
        dt.Columns.Add("IsActive",typeof(bool));

        //Creating some random data
        //Replace this with your actual data...
        Random rnd = new Random(1);
        for (int i = 0; i < 100; i++)
        {
            int Id = i+1;
            int Price = Id%2 == 0? 500-Id*2:350+Id*3;
            bool isActive = (Id%5) !=0;

            DataRow row =  dt.NewRow();
            row["Id"] =Id ;
            row["Price"] = rnd.Next(1000) ;
            row["IsActive"] = isActive;
            dt.Rows.Add(row);
        }

        this.dataGridView1.DataSource = dt;

        //making sure all columns are sortable
        foreach (DataGridViewColumn col in this.dataGridView1.Columns)
        {
            col.SortMode = DataGridViewColumnSortMode.Automatic;
        }

    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using DateTime library in Remix to Convert Timestamp to DateTime format If anyone is familiar with importing a library into Remix, then using it, maybe you can help. What i am doing pertains to this library...
https://www.npmjs.com/package/@quant-finance/solidity-datetime?activeTab=explore
The steps i took to import this and use this library in remix with my existing contract are as follows...

*

*I went to the "code" tab on that link. Saw... DateTime.sol contract. I copied and pasted the entire contract into a file called... DateTime.sol in my folder in Remix.
Now I have my original contract file called Escrow.sol and DateTime.sol both in my Folder in Remix.

*In my main contract I import the DateTime.sol library at the top of my Escrow.sol file like this...
import "./DateTime.sol";

*Lastly I put the function I want from the DateTime.sol contract into my Escrow contract like this...
function timestampToDateTime(uint timestamp) public pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) {
      return (year, month, day, hour, minute, second);
}

*I compile both contracts now, deploy, and now in Escrow.sol (my main contract, not the library), I test the function. I put a timestamp in the function box in remix but it doesn't convert. It shows all 0's for the year, month, day.
Any idea what I am doing wrong? I am basically just copying and pasting the entire library as a separate contract in Remix, importing the library into my main contract, and then trying to use one of the library functions in my main contract (copy and pasting the one function i need from the library into my main contract) but it doesn't work. Your help is greatly appreciated.

A: Okay i just figured it out. For anyone who sees this, the function in my main contract needed to be as follows as i needed to call the other contract function like this...
   function convertTimstamp(uint timestamp) public pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { return DateTime.timestampToDateTime(timestamp);


text:
Q: why UIImageToMat neglect the third argument when being called? In openCV library, specifically, in ios.h, the UIImageToMat is declared as:
void UIImageToMat(const UIImage* image,
                         cv::Mat& m, bool alphaExist = false);

but When UIImageToMat is called, why people neglect the third argument?
for example:
UIImageToMat(image, cvImage);

A: As can be seen in the function prototype, the third argument has a default value of false: ... bool alphaExist = false. Hence, in use cases when there is no alpha, there is no need to explicitly specify the last argument.


text:
Q: Android Studio release signed apk :app:transformClassesAndResourcesWithProguardForRelease java.io.IOException I just updated to Android Studio 2.1.1 and I am trying to build a release signed apk but failed with the error below. How can I solve this ?
':app:transformClassesAndResourcesWithProguardForRelease'.
    > java.io.IOException: Please correct the above warnings first.

this is the build.gradle (module: app)
full version: https://gist.github.com/anonymous/65bb2edf94ea58c50de8e0ff107555ce
...
android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.company.project"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 13
        versionName "1.5"
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    lintOptions {
        checkReleaseBuilds false
    }
}

more on the error Message dump
https://gist.github.com/anonymous/9d822c530011b48dab1da60267f9b471
UPDATE:
content of proguard-rules.pro
https://gist.github.com/anonymous/9d822c530011b48dab1da60267f9b471
content of /Users/xxxx/Library/Android/sdk/tools/proguard/proguard-android.txt
https://gist.github.com/anonymous/d5cdfbfd7c1bfe74d594993feb35bd62
content of /Users/xxxx/Library/Android/sdk/tools/proguard/proguard-project.txt
https://gist.github.com/anonymous/d04cd0299029d4fdd648fb782f2e3021

A: As you havent added proguard rules in your proguard-android.txt file i would suggest you to add all necessary rules to make release apk from your project.
For retrofit you need to add below rules:
-dontwarn retrofit2.**
-keep class retrofit2.** { *; }
-keepattributes Signature
-keepattributes Exceptions

You also need to add other rules too like,
-keepattributes *Annotation*
-keep class com.google.android.gms.internal.*

-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class * extends android.app.backup.BackupAgent
-keep public class * extends android.preference.Preference
-keep public class * extends android.support.v4.app.Fragment
-keep public class * extends android.support.v4.app.DialogFragment

-keep class com.google.android.gms.maps.** { *; }
-keep interface com.google.android.gms.maps.** { *; }

-keepclassmembers class * implements android.os.Parcelable {
    static *** CREATOR;
}
# The Maps API uses serialization.
-keepclassmembers class * implements java.io.Serializable {
    static final long serialVersionUID;
    static final java.io.ObjectStreamField[] serialPersistentFields;
    private void writeObject(java.io.ObjectOutputStream);
    private void readObject(java.io.ObjectInputStream);
    java.lang.Object writeReplace();
    java.lang.Object readResolve();
}

This is common for most of projects and i have used for my project, Please check whole rule before using it.


text:
Q: Is there a way to do some action if a specific website is visited? I want to make something in cmd/powershell/vbs that monitors your browser activity and if a specific website is visited do something .
Powershell Example:
function Infinite-Detect {
    while($true) {
       $websites = //Browser monitor code
       Start-Sleep -Milliseconds 500
    }
}

if(websites -eq "https://www.youtube.com/") {
   Write-Output "I see. You're going to watch some videos!"
}else {
   // Don't do anything
}

Infinite-Detect

Is it possible to do something like this?
I'm currently using Google Chrome on a Windows 10 PC. I would really appreciate if you advice the codes specifically for Google Chrome.

A: Impossible : The browser works in a sandbox, totally isolated from the
operating system. It cannot launch any program.
Hackers are constantly searching for such a capability, in Chrome or any
other browsers.
Up to now the developers have done a pretty good job of blocking
totally all the possible methods.


text:
Q: Charge distribution in positronium Inspired by this: Electrical neutrality of atoms
If I have a wavefunction of the 'reduced mass coordinate' for a hydrogen like atom made from an electron and a positron, what is the spatial charge distribution?
When we solve the hydrogen atom, we change into coordinates of the center of mass, and the separation distance with the reduced mass.  Here, the masses of the constituent particles are the same.  So the center of mass is equidistant from the positron and electron, and so discussing r and -r is just swapping the particles.  Since the probability distribution for all the energy levels of the hydrogen atom are symmetric to inversion (images can be seen here http://panda.unm.edu/Courses/Finley/P262/Hydrogen/WaveFcns.html ), this seems to say no matter what energy level positronium is in, the charge distribution is neutral?  Since the energy level basis is complete, this seems to say we can't polarize a positronium atom without dissociating it!? This doesn't make sense to me, so I'm  probably making a big mistake here.

A: Okay we have the center of mass coordinate $r_{cm} = (r_e + r_p)/2$, and the reduced mass coordinate $r = r_e - r_p$.  So given the wavefunction $\psi(r_{cm},r)$ what you are asking is just a change of basis from $|r_{cm},r\rangle$ to $|r_e,r_p\rangle$.  So you just need to consider
$$\langle r_e,r_p|r_{cm},r\rangle = \delta\left(r_{cm}-(r_e+r_p)/2\right) \ \delta\left(r-(r_e-r_p)\right)$$

To get more at what appears to be confusing you, let's focus on how positronium can be polarized.  The spherical harmonics will have a defined even or odd parity to inversion, and so yes the square of the wavefunction (probability density) is invariant to inversion.  But this does not mean all superpositions of these harmonics will have this property.
Consider for instance just s + p_z orbital.  On one side the wavefunction amplitude will add constructively, while on the other it will add deconstructively.  The density is no longer symmetric to inversion.  This is the standard chemistry description of orbitals, so probably a good way to get follow up reading is searching for hybrid orbitals.
Here's a link I found with some images for you:
http://www.uwosh.edu/faculty_staff/gutow/Orbitals/N/What_are_hybrid_orbitals.shtml

A: Normally we speak of charge distribution in terms of atomic form-factors. It means Born approximation which means in turn fast charged projectiles or photons.
Para- and orto-positroniums have different magnetic fields due to different spin orientation.
For slow charged projectiles its field strongly polarizes the atom and the charge distribution is not the same as in a "free" atom.


text:
Q: Best way to test for blank list in bash? Which is generally the best practice in bash?
hotstrings=()

if [ ${#hotstrings[@]} != 0 ]; then return; fi

vs
if [ ${#hotstrings[@]} -gt 0 ]; then return; fi

vs
if [ "${hotstrings[@]}" != '' ]; then return; fi

vs
Something else?

A: The comparison against an empty string looks brittle, and needlessly interpolates a potentially large array into a string just to compare it against the empty string.
I'm not sure whether numeric or string comparison against zero is more efficient in general, and in isolation, you would be hard pressed to perceive any difference even if there is one. My hunch is that strings are more efficient, and arithmetic requires some additional work by Bash.
The following quick test seems to bear this out:
bash$ array=({1..10000})
bash$ echo "${#array[@]}"
10000
bash$ time for i in {1..10000}; do [ "${#array[@]}" -gt 0 ]; done

real    0m0.109s
user    0m0.097s
sys 0m0.007s
bash$ time for i in {1..10000}; do [ "${#array[@]}" != 0 ]; done

real    0m0.100s
user    0m0.092s
sys 0m0.007s

For an apples-to-apples comparison, you should properly measure -ne (numeric non-equivalence) instead of -gt, but it doesn't seem to make any real difference. If anything, it seems slightly slower, somewhat to my surprise.
So with this rather ad-hoc measurement I would hesitantly recommend the string comparison != 0 over the arithmetic one.  However, switching to [[ over [ makes a much bigger difference, and is more robust to boot.
bash$ time for i in {1..10000}; do [[ "${#array[@]}" != 0 ]]; done

real    0m0.065s
user    0m0.064s
sys 0m0.001s

(For the record, I did check that -gt 0 is slightly slower in this case too.)
Anyway, the test might obviously come out quite differently if your typical values are drastically different from what I guessed would be useful for a quick test, or if your Bash version is different from mine. (This was Bash 3.2.57(1)-release which is what MacOS still ships out of the box.) If this is really important, test with your own representative data.
All of these constructs are compatible back to Bash v2 at least; obviously, if you are not using Bash at all, your question is not well-defined (Zsh and ksh have similar array syntax, but you would hardly want to try to maintain compatibility across them).
Rock-bottom baseline:
bash$ time for i in {1..10000}; do true; done

real    0m0.062s
user    0m0.047s
sys 0m0.006s

A: I'd use this:
[[ ${arr[@]}  ]] || echo empty

Update, or this:
((${#arr[*]}<1)) && echo empty

Testing:
$ arr=()
$ [[ ${arr[@]}  ]] || echo empty
empty
$ ((${#arr[*]}<1)) && echo empty
empty

$ arr=('')
$ [[ ${arr[@]}  ]] || echo empty # fail (
empty
$ ((${#arr[*]}<1)) && echo empty # fine )


text:
Q: Computing the volume of intersection between a tetrahedron and a hexahedron. I am trying to compute the volume of two intersecting objects in 3D. One is a tetrahedron and the other is a hexahedron. I just need the volume but it looks like I will have to find the polyhedron that intersects these two objects and then compute it's volume. This seems very complicated.
In terms of more detail:  I know that the two objects intersect and am trying to compute the volume of the hexahedron that is in the tetrahedron. I represent both objects with vertices (in 3D space). I can compute the faces and their normals and also have the flexibility to transform them if that would help.
Is there an easier approach to just the volume or do I have to get the intersecting polyhedron and then compute the volume for it?
Here is an image.

A: If you could accept non-exact value for the intersection volume, then you can try the famous Monte Carlo Method.

*

*Surround your two polyhedrons by an iso-oriented cube and generate uniformly distributed (in this cube) sample points - for each point you can quickly verify if it's inside the intersection or not.

*Calculate two numbers - the number of all samples and the number of samples, lying inside the intersection, then divide the second one over the first one... you understand, I think.

The more the number of sample points the better the approximation.
UPDATE:
There are many strategies to select sample points. You can even distribute them regularly (without randomness) inside the cube, or inside the first polyhedron.
Any other way, which guarantees the uniform distribution of sample points, will work in this case.


text:
Q: How to concatenate two columns containing list (series) in Pandas I'd like to concatenate two columns in pandas. Each column consists of a list of floating points of 1x4 elements. I'd like to merge two columns such that the output is a vector of 1x8. The below shows a snippet of the dataframe
ue,bs
"[1.27932459e-01 7.83234197e-02 3.24789420e-02 4.34971932e-01]","[2.97806183e-01 2.32453145e-01 3.10236304e-01 1.69975788e-02]"
"[0.05627587 0.4113416  0.02160842 0.20420576]","[1.64862491e-01 1.35556330e-01 2.59050065e-02 1.42498115e-02]"

To concatenate two columns, I do the following:
df['ue_bs'] = zip(df_join['ue'], df_join['bs'])

With this, I get a new column 'ue_bs' which contains the following for the first row of df['ue_bs']:
(array([1.27932459e-01, 7.83234197e-02, 3.24789420e-02, 4.34971932e-01]),
 array([2.97806183e-01, 2.32453145e-01, 3.10236304e-01, 1.69975788e-02]))

However, they are still two arrays. In order to merge them, I did it as follows:
a = df['ue_bs'][0]
np.concatenate((a[0], a[1]), axis=0)

Then, I got
array([1.27932459e-01, 7.83234197e-02, 3.24789420e-02, 4.34971932e-01,
   2.97806183e-01, 2.32453145e-01, 3.10236304e-01, 1.69975788e-02])

I am wondering is there a neat way of doing this in single line of code, instead of having to loop through df['ue_bs'] and perform np.concatenate()?

A: Create 2d numpy array and then numpy.hstack:
a = np.array(df[['ue','bs']].values.tolist())
df['ue_bs'] = np.hstack((a[:, 0], a[:, 1])).tolist()

print (df.loc[0, 'ue_bs'])
[0.127932459, 0.0783234197, 0.032478942, 0.434971932,
 0.297806183, 0.232453145, 0.310236304, 0.0169975788]

A: To concatinate two lists in python, the easiest way is to use +. The same is true when concating columns in pandas. You can simply do:
df['ue_bs'] = df['ue'] + df['bs']

If the column type is numpy arrays you can first convert them into normal python lists before the concatination:
df['ue_bs'] = df['ue'].apply(lambda x: x.tolist()) + df['bs'].apply(lambda x: x.tolist())


text:
Q: orders have disappeared from admin except 1 I am new on Magento and i am facing this issue
All orders have disappeared from admin panel except 1. If possible please also advise cause of problem.. Please Help !!

A: Use something like PHPMyAdmin to check the contents of your sales_flat_order table, if the orders are missing from this table they have been deleted.
Let me know what you see in this table, each record corresponds to an order.
P.S: Are you running multiple shops on your store? This could have something to do with a specific store view.


text:
Q: Why is a workflow, which is associated with a content type, not associated with a document of that content type? We have Sharepoint 2010 and MS Word 2007.
I have the three default workflows (Collect Feedback, Approval, Collect Signatures) associated with a content type based on the document content type.
When I want to start a workflow, Sharepoint says there are no workflows available to start on this item.

A: The reason was that the three default workflows were disallowed on the Remove Workflows page. I merely allowed them again. Everything is fine now.
You get to the Remove Workflows page by going to the relevant document library, clicking Workflow Settings, selecting the applicable content type and then clicking the "Remove a workflow link".

A: check this , it may help,
It's not the same but could give you an idea.
http://spreza.blogspot.com.au/2013/05/reusable-workflow-which-is-associated.html


text:
Q: How to separate the result Python web scraping data with a comma I'm trying to pull data and information from different sites. I worked on a script it works well, however, when I try to print the result there is some problems like the results are like sentences there is no comma no delimiter. Nothing I tried myself and nothing.
This is the site i am working on http://www.conditions-de-banque-tunisie.com/banques-en-tunisie.html
I have tried to put a comma between results and nothing. The comma comes at the end, that's all.
linksname.find_all('p')[i].text + ','

import requests
import bs4
import csv
import io
response = requests.get('http://www.conditions-de-banque-tunisie.com/banques-en-tunisie.html')
response.status_code
soup_obj = bs4.BeautifulSoup(response.text, "html.parser")
soup_obj.prettify()

#print('shhh')
linksname = soup_obj.find(class_='bloc-banques-liste')
#linksname.text
textContent = []
for i in range(0,1): links =   linksname.find_all('p')[i].text
textContent.append(links)
for text in textContent:
    print('----------------------------')
    print(text)
    with io.open("fname.txt", "w", encoding="utf-8") as f: f.write(text)

This is the result :

North Africa International BankAdresse : Avenue Kheireddine Pacha Ennassim Montplaisir 1002 TUNISTé : +216 71 950 800Fax : +216 71 950 840Site web :  http://www.naibbank.com/
Qatar National BankAdresse : Rue de la cité des sciences - B.P. 320 - 1080 Tunis CedexTé : +216 71 750 000Fax : +216 71 235 611Site web :  http://www.qnb.com.tn/

I expect that the result will be like :

North Africa International Bank  , Adresse : Avenue Kheireddine Pacha Ennassim Montplaisir 1002 , TUNISTé : +216 71 950 800 , Fax : +216 71 950 840 ,Site web :  http://www.naibbank.com/

Or just the best results is:

North Africa International Bank , venue Kheireddine Pacha Ennassim Montplaisir 1002 , +216 71 950 800 , +216 71 950 840 , :  http://www.naibbank.com/

A: Check the code below and let me know if that helps.
import requests
import bs4
import csv
import io
response = requests.get('http://www.conditions-de-banque-tunisie.com/banques-en-tunisie.html')
response.status_code
soup_obj = bs4.BeautifulSoup(response.text, "html.parser")
soup_obj.prettify()

#print('shhh')
linksname = soup_obj.find(class_='bloc-banques-liste')
textContent = []
links = linksname.findChildren("div", class_='banques-liste-desc', recursive=True)
links = [" \n ".join([y.text for y in link.findChildren("p")]) for link in links]
print(str(links))

A: The following is a  somewhat simplified version of your code, but it should get you to where you need to be, after fitting it to your own style:
from bs4 import BeautifulSoup as bs
import requests

response = requests.get('http://www.conditions-de-banque-tunisie.com/banques-en-tunisie.html')

soup = bs(response.text, "html.parser")

textContent = []
linksname = soup.find(class_='bloc-banques-liste')
for name in linksname:
    entry =   linksname.find_all('p')[0].text
    textContent.append(entry)
    break

for bank in textContent:
    print(bank.replace(' :',',').strip())

Output:
Al BarakaAdresse, 88, Avenue Hedi Chaker 1002 TunisTé, +216 71 790 000Fax, +21671 780 235Email, contact@albarakabank.com.tnSite web,  http://www.albarakabank.com.tn/

Amen BankAdresse, Avenue Mohamed V 1002 Tunis - TunisieTé, (+216) 71 148 000Fax, (+216) 71 833 517Site web,  http://www.amenbank.com.tn/

etc.

A: Instead of using "bloc-banques-liste" class to find objects you can use "banques-liste-desc"
This will directly give you the list of all blocks.
Check following code.
import requests
import bs4
import csv
import io
response = requests.get('http://www.conditions-de-banque-tunisie.com/banques-
en-tunisie.html')
response.status_code
soup_obj = bs4.BeautifulSoup(response.text, "html.parser")
soup_obj.prettify()

linksname = soup_obj.find_all(class_='banques-liste-desc')
for i in range(0, len(linksname)):
    name = linksname[i].find('h1').find('a').text
    print(name)
    address = linksname[i].find_all('p')
    for j in range(0, len(address)):
        print(address[j].text)
    print("----------------------------")

Here I have printed all the values separately, instead of that you can directly join them using comma.


text:
Q: Javascript calling so fast I have an annoying little issue here.  I have code which loads content from page2 and appends it to #content. That works, but sometimes it happens twice, then appends page3 before page2.  Thats because in page3, there is just one post, but in page2, 4 posts.
How can I make my code wait until the append finishes to run again? Here's my code:
$(window).scroll(
  function(){
    if(browserName != "safari") {
      var curScrollPos = $('html').scrollTop();
    }
    else {
      var curScrollPos = $('body').scrollTop();
    }

    if(curScrollPos > 218) {
      $("#sidebar").addClass("open");
    }

    if(curScrollPos < 218) {
      $("#sidebar").removeClass("open");
    }

    var scrollBottom = $(document).height() - $(window).height() - $(window).scrollTop();

    if(scrollBottom == 0) {
      if(home != 0 || search != 0 || category != 0) {
        if(currentPage < numPages) {
          $("#main .loader-posts").fadeIn();
          currentPage++;

          if(search == 1) {
            var getPostsUrl = "page/"+currentPage+"/?s="+searchTerm;
          }
          else {
            var getPostsUrl = "page/"+currentPage;
          }

          $.get(getPostsUrl, function(data) {
                  $("#main .loader-posts").fadeOut(
                    'slow',
                    function(){
                      var newPosts = $(data).find("#content").html();
                      $("#content").append(newPosts);
                      $('#container.tiles').masonry('reload');
                    });
                });
        }
      }
      else {

      }
   }

A: Add a variable that keeps track of whether you are loading the next page or not and then only load if you are not currently loading something else.  This is the root of your problem.  .scroll() may fire twice before the next section is loaded, and as long as currentPage < numPages it will increment currentPage and load again.  And, because .get() is asynchronous, you are not guaranteed to finish the first .get() request before any subsequent request.  Adding a loading state fixes this.
var loading = 0;  // Loading state

if (scrollBottom == 0) {

    if (home != 0 || search != 0 || category != 0) {

        if (currentPage < numPages && !loading) {  // Only proceed if not loading
            loading = 1; // We have initiated loading

            $("#main .loader-posts").fadeIn();
            currentPage++;

            if (search == 1) {
                var getPostsUrl = "page/" + currentPage + "/?s=" + searchTerm;
            } else {
                var getPostsUrl = "page/" + currentPage;
            }

            $.get(getPostsUrl, function(data) {
                $("#main .loader-posts").fadeOut('slow', function() {
                    var newPosts = $(data).find("#content").html();
                    $("#content").append(newPosts);
                    $('#container.tiles').masonry('reload');
                    loading = 0;  // We are done loading
                });
            });
        }
    } else {

    }

}

A: Maybe you can add an isBusy flag that you can check before the $.get(), and set it to false in the $.get() callback?


text:
Q: Sending mail with attachments from Oracle apex In oracle 11gR2 database I create a directory named 'my_directory' there are some pdf file. In Oracle apex i want to send mail with attachments. Is't possible to attach file from this directory? If possible, How?
APEX version: 4.2.6

A: You need to get the file as a BLOB and then attach using APEX_MAIL.ADD_ATTACHMENT


text:
Q: Whats the difference between Q Promise library's .finally() and .done()? What is the difference between using the Nodejs Q promise library's .finally() and .done() statements.
For example whats the difference between these two?
Q(...)
.then(...)
.finally(); //or fin()

Q(..)
.then()
.done();

A: The difference is in chaining and error handling, and error logging:
Q(...)
.then(...)
.finally();

Here, if the then throws, the finally will still run, but no error will log. In Q finally is run regardless of the .then being successful or not. This is like the finally keyword in JS try/catch/finally. It is also possible to chain additional thens to the chain in this case.
Q(..)
.then()
.done();

Here, done indicates that the promise chain has ended, you can not chain to it any more. If you pass it only an onFulfilled handler it will not run if the then threw, and it will log errors if it ends with an exception.

A: promise.done(onSuccess, onError) simply allows you to process resolved value. An additional benefit is that does not imply any error swallowing (as it is the case with promise.then()), it guarantees that any involved  exception would be exposed. It also effectively ends the chain and does not return any further promise.
promise.finally(fn) is for registering a task that must be done after a given promise resolves (it doesn't matter whether promise succeeds or fails). Usually, you use it for some kind of cleanup operations e.g. imagine you set up a progress bar, that needs to be hidden after the request is done (no matter if it was successful), then just do promise.finally(hideProgressBar). Additionally promise.finally() returns input promise, so you can return it for further processing.


text:
Q: Query string value having "&" I have a query string like
www.google.com?Department=Education & Finance&Department=Health

I have these as li tags and their query string is like this:

*

*Education & Finance

*Health
*

Now the problem is when I'm doing NamevalueCollection and getting all the keys value: it is giving me just Education, not Finance .....
Any idea how to resolove this?

A: You need to encode your values by calling Server.UrlEncode before putting them into the URL.
If your values are in an array, you'll need to use a loop.  If you want precise instructions, you'll need to show us your current code.

A: The ampersand (&) is a special character in a url.  So the above URL is being interprested as www.google.com with three arguments: 2 Departments and a Finance.
Try using:
System.Web.HttpUtility.UrlEncode(string url)

to encode the URL.

A: The values in the query string should be url encoded. Now there is no way to determine the difference between the & characters that separate the value pairs and the & character inside one of the values. Also, eventhough most browsers will accept spaces in an URL, that is invalid according to the standard.
In the value Education & Finance you have to encode the spaces as + or %20, and the & character as %26 so that it becomes Education%20%26%20Finance.
So the correct URL should be:
www.google.com?Department=Education%20%26%20Finance&Department=Health


text:
Q: Rails 3.2 CarrierWave always saving image as open-uri I am using Rails 3.2.13 and Carrierwave 0.9.0.
I am extracting many pictures with this gem. I've succeed to download all these pictures, unfortunately their name are always : "open-uriXXXXXX".
I would like to have exactly the original name of these pictures.
Do you have any idea ?
Here is the code in my controller to download a picture :
var_bis = 'URL' + line['illustration_url']
image_bis = open(var_bis)
p.illustration.store!(image_bis)

Furthermore, I have not changed the original file of my uploader except for the directory store.
Thanks a lot,
EDIT :
My uploader file :
class ImageUploader < CarrierWave::Uploader::Base
  storage :file

  def store_dir
    "My_path_to_save_images"
  end

end

EDIT FINAL :
Here is the answer to add in the controller :
`f=open(File.basename(var_bis), 'wb')
f << open(var_bis).read
p.illustration.store!(f)`


text:
Q: Extract the exact number of elements from the same identifier I have a file that looks like this:
Id       Chr     Start   End
Prom_1   chr1    3978952 3978953
Prom_1   chr1    3979165 3979166
Prom_1   chr1    3979192 3979193
Prom_2   chr1    4379047 4379048
Prom_2   chr1    4379091 4379092
Prom_2   chr1    4379345 4379346
Prom_2   chr1    4379621 4379622
Prom_3   chr1    5184469 5184470
Prom_3   chr1    5184495 5184496

and I would like to count how many times the same identifier appear. Something like:
Prom_1  3
Prom_2  4
Prom_3  2

Any idea is really appreciate.

A: With GNU datamash
$ datamash -W --header-in groupby 1 count 2 < file
Prom_1  3
Prom_2  4
Prom_3  2

A: You can count the identifiers with uniq:
tail -n +2 input | cut -d' ' -f1 | sort | uniq -c

Note that uniq expects sorted input. We use tail to skip the header and cut to 'cut-out' the first column.
Example output:
  3 Prom_1
  4 Prom_2
  2 Prom_3

In case an id with a smaller number should be printed before an id with a larger number (e.g. Prom_3 before Prom_10) you can replace sort with sort -V (version sort):
tail -n +2 input2 | cut -d' ' -f1 | sort -V | uniq -c

Example output (input2 contains an extra line for id Prom_10):
  3 Prom_1
  4 Prom_2
  2 Prom_3
  1 Prom_10

A: You can use awk
awk 'NR>1 {a[$1]++} END { for (x in a) { print x,a[x] } } ' file

The NR>1 will ignore the header
a[$1]++ is a hash iterator

A: Simple way with cat, cut , sort and uniq is :
sed -n '1,$p' input | cut -d' ' -f1 | sort | uniq -c

A: Something similar to user3589054:
since there are a lot of Id, when you sort you will not have the same order of Id because for example the Id starting with Prom_1 Prom_10 etc.. will be as first. So what i did was this and it worked fine:
awk 'NR>1 {a[$1]++} END { for (x in a) { print x,a[x] } } ' file | awk -F "_" '{print $1"\t"$2"\t"}' | cut -f 2 | sort -n | awk -F " " '{print $1"\t"$2}' | sed 's/^/Prom_/' > file.output.txt
where:
awk 'NR>1 {a[$1]++} END { for (x in a) { print x,a[x] } } ' file |
you will have the output with the Id and number but not sorted
awk -F "_" '{print $1"\t"$2"\t"}' |
you will split the file in Prom , number, its Id number and its quantity
cut -f 2 | sort -n |
sort according the number Id and its correspondent amount
awk -F " " '{print $1"\t"$2}' |
here you tab the two columns
sed 's/^/Prom_/'
and finally you attach the Prom_ in front of its number Id


text:
Q: Consider sequence $(x_n)$ from $n=0$ to infinity given by $x_0=0$ and $x_{n+1}=0.1+x_n^3$.
Consider sequence $(x_n)$ from $n=0$ to $\infty$ given by $x_0=0$ and $x_{n+1}=0.1+x_n^3$ for $n=0, 1, 2, 3, \dots$ . Prove that it converges.

I start by stating $0 < x_n < x_{n+1} < L$ but I'm not sure exactly how to find the limit $L$

A: You could also argue that it is bounded, monotonically increasing (where these can be proved by induction). Then you can draw from the monotone convergence theorem and that pretty much proves it.

A: Hint: Solve $x^3-x+.1=0$.  What does that tell you?

A: start recursive,if  $x(0)=0$,then $x(1)=0.1+(x0)^3$ right?what is equal to  $x(2)?$ it is equal to $0.1+x(1)^3$  ,now  use  formula for  $x(1)$ and so on,finally use limit formula,for simplify final  denote $x(0)=k$


text:
Q: Changing the .Text of my MenuStripItems This code only changes the top menu selectors.
private void englishToolStripMenuItem_Click(object sender, EventArgs e)
    {
        menuStrip1.Items[0].Text = Languages.English.File;
        menuStrip1.Items[1].Text = Languages.English.Options;
        menuStrip1.Items[2].Text = Languages.English.Help;
    }

How can I change the subitems's .Text properties?

A: If you look in the form designer code file, you'll see that the menu items are all stored in their own variable, which you can use to change the text.
The default variable names aren't brilliant, having names like "toolStripMenuItem1". I assume you created the menus using the collections editor; if you select the menu item in there, you can change the variable name under the (Name) property.
Personally, I'd suggest naming something along the lines of "menuFileItem1", "menuFileItem2", and so on, as it'll allow you to see the hierarchy of the menu by glancing at the variable names.


text:
Q: Speed difference between Connected App created on Developer Edition vs Enterprise Edition We use a Connected App to allow our clients (from different organizations) to authorize and provide our platform API access to their data.
Our original developer set this Connected App up on our Developer Instance.
Is there any difference between having it on the Developer Edition vs creating one on the Enterprise Edition?
We use the REST API only so does this have any impact on the speed of API requests made?
I figured it doesn't because we use our client's instance (from the OAuth response) which is a production instance. However, I was wondering if SF does something behind the scenes, for example prioritizing it lower since it's a "development" Connected App.
Is there a best practice on creating Connected Apps on specific Editions?

A:
Is there any difference between having it on the Developer Edition vs creating one on the Enterprise Edition?

No. The first time it is used, it is "installed" into the client's Enterprise Edition Org so that admins can control access to it, so it doesn't really matter where you put it. Obviously, don't put it in a sandbox, because you'll lose that Connected App if you refresh.

We use the REST API only so does this have any impact on the speed of API requests made?

No. The REST API has similar performance using any session Id. It doesn't matter if this came from a Connected App, a browser session, SOAP session, etc.

I figured it doesn't because we use our client's instance (from the OAuth response) which is a production instance. However, I was wondering if SF does something behind the scenes, for example prioritizing it lower since it's a "development" Connected App.

No. Every connected app is treated identically. If that were untrue, most ISVs would be crippled because their API connections would suffer.

Is there a best practice on creating Connected Apps on specific Editions?

If you're using the connected app for yourself, put it in your production organization; it'll be copied to all Sandboxes during each refresh. If you're acting as an ISV, place it in your managed package's Developer Org. This way, you'll know exactly where it is. There's no need to add it as a member of your managed package, though.


text:
Q: What is the Problem with these conditional Statement? I am facing an issue with my script. It is a form with a gender select option. When the page loads the value of gender == true, therefore  it should satisfy the first part of the if condition, and set gender to male. Why it is going into the else condition and assigning the value gender = female?
In the database the gender column has a bit datatype.
var gender = data[0].Gender; // gender = true
if (gender == "true") {
    gender = "male";
} else {
    gender = "female"; // gender = female
}

A: Change if (gender == "true") { to if (gender == true) {. You should be comparing booleans, not strings.
EDIT: As the commenter says, if (gender) { would be more concise.

A: Since "true" is not of type boolean but of type string, the comparison if (true == "true") will always fail.
var gender = data[0].Gender;      ** gender = true/false **
   if (gender) {
     gender = "male";
   }
   else {
     gender = "female"; **gender= female**
   }

Here'r two links regarding boolean from W3Schools and comparisons


text:
Q: The old Broadcom 43xx beast strikes again... 14.04 32bit I recently rescued a "bricked" intel Imac5 by installing Ubuntu Studio 14.04 32bit as the only OS. Apple techs swore the GPU was completely fried, but with Ubuntu the thing barely throws any heat and it runs fine (for my purposes). So I consider this a success story.
However, once I started messing with Broadcom drivers things started to get hairy. Additional Drivers supplied the Broadcom-STA, and after reboot the whole system was super slow and no networks were detected. Per forum suggestions I have purged bcmwl-kernel-source and installed firmware-b43-installer b43-fwcutter and had the exact same results.
Next I found a post that listed my hardware (bcm4321) requiring linux-firmware-nonfree to work in 14.04... again a slow system and no wireless detected.
I've tried each of these methods a few times adjusting the blacklist.config appropriately, and the results are always the same.
As a last resort I've taken the ndiswrapper approach. THIS does not slow my system, however no networks are detected and no wlan shows up in iwconfig. While the ndiswrapper GUI says that the driver detects the hardware.
I'm at a loss here and almost ready to buy a REALLY long ethernet cable. If anyone has any suggestions I'd be so grateful. I'm hoping I just overlooked something dumb?
lspci=
*-network
   description: Network controller
   product: BCM4321 802.11a/b/g/n
   vendor: Broadcom Corporation
   physical id: 0
   bus info: pci@0000:03:00.0
   version: 01
   width: 64 bits
   clock: 33MHz
   capabilities: pm msi pciexpress bus_master cap_list
   configuration: driver=b43-pci-bridge latency=0
   resources: irq:10 memory:c8200000-c8203fff memory:c8000000-c80fffff

iwconfig yields=
    lo        no wireless extensions. eth0      no wireless extensions.
This one is interesting rfkill list all just shows bluetooth=
    0: hci0: Bluetooth     Soft blocked: yes Hard blocked: no

UPDATE!
I ran some software updates as they became available... I have cycled through trying all of the available drivers once more. Unfortunately, I still have no wifi, but installing these drivers no longer slows down or locks up my system.

A: After running the most recent updates I thought I would try another round of driver juggling. bcmwl-kernel-source worked, but wireless would be invisible after restart. I had the same results with firmware-b43-installer.
After restart I opened up a terminal and tried:
sudo modprobe b43

This started the wireless immediately. I can't say whether this would have worked for me prior to the most recent updates because the wireless never seemed to be recognized before. I made this change permanent as suggested in this post.
sudo -i
echo b43  >>  /etc/modules
exit

Works like a charm!


text:
Q: Select all from primary table, join to others I am hoping somebody can help me.  If I do a standard Inner Join or right join, i get very few results. Would also be great to also know why what I am trying wont work.
I have a primary Table of members. MemberID is common to all tables
Select * from apf_members

MemberID--|--AppsTitle--|--AppsFirstName--|--AppsLastName--

2015       Mrs             Naomi            Specter
2016       Mr              Marisa           Watson
2025       Mr              Elia             Barker
2031       Dr              Heth             Rowing
2044       Ms              Kathryn          McKenzie

I also want to attached 3 extra columns that are dynamically built.

--CurrentMember--|--UnrenewedMember--|--LapsedMember--

The queries below will currently return the value only ~IF~ the user has a record. where I need it to return a NULL or an empty string.
@theDate is a variable, ill assign it to Getdate for now.
Declare @theDate date
SET @theDate = GetDate()

Select Description as 'CurrentMember' from apf_finances
where @theDate between StartDate and EndDate
and Status = 'Financial Status'

Select Description as 'UnrenewedMember'
from apf_finances
where @theDate between DATEADD(year, -1, StartDate) and DATEADD(year, -1, EndDate)
and Status = 'Financial Status'

Select Description as 'LapsedMember'
from apf_finances
where @theDate between DATEADD(year, -2, StartDate) and DATEADD(year, -2, EndDate)
and Status = 'Financial Status'

Put together,final result would look like this.

MemberID--|--AppsTitle--|--AppsFirstName--|--AppsLastName--|--CurrentMember--|--UnrenewedMember--|--LapsedMember--
2015       Mrs             Naomi            Specter          f                  nf                  nf
2016       Mr              Marisa           Watson           uf                 NULL                nf
2025       Mr              Elia             Barker          NULL                NULL                NULL
2031       Dr              Heth             Rowing          co                  exp                 f
2044       Ms              Kathryn          McKenzie        NULL                f                   NULL

*UPDATE 22/10/2013 *
here is a SQL script that should re-create the tables
CREATE TABLE [dbo].[apf_Members](
    [MemberID] [int] IDENTITY(1,1) NOT NULL,
    [AppsTitle] [nvarchar](50) NULL,
    [AppsFirstName] [nvarchar](50) NULL,
    [AppsMiddleName] [nvarchar](50) NULL,
    [AppsLastName] [nvarchar](50) NULL,

)

GO

CREATE TABLE [dbo].[apf_Finances](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [MemberID] [int] NOT NULL,
    [Description] [nvarchar](50) NULL,
    [StartDate] [date] NULL,
    [EndDate] [date] NULL,
    [Status] [nvarchar](50) NULL

)

GO

SET IDENTITY_INSERT dbo.[apf_Members] ON
GO

SET IDENTITY_INSERT dbo.[apf_Finances] ON
GO

INSERT INTO [dbo].[apf_Members]
           ([MemberID],[AppsTitle],[AppsFirstName],[AppsLastName])
           VALUES     (2015,'Mrs','Naomi', 'Specter' ),

(2016    ,   'Mr'  ,'Marisa','Watson' ),
(2025   ,    'Mr' ,'Elia','Barker'),
(2031  ,     'Dr','Heth','Rowing'),
(2044 ,      'Ms','Kathryn','McKenzie');

INSERT INTO [apf_Finances]
    ([ID], [MemberID], [Description], [StartDate], [EndDate], [Status] )
    VALUES

(12381, 2016,   'f' ,'2013-10-15','2014-10-14','Financial Status'),
(12382, 2016,   ''  ,'2013-10-15','2014-10-14','Donation'),
(12361, 2025,   'f' ,'2013-10-12','2014-10-11','Financial Status'),
(12362, 2025,   ''  ,'2013-10-12','2014-10-11','Donation'),
(12357, 2031,   'f' ,'2013-10-11','2014-10-10','Financial Status'),
(12358, 2031,   ''  ,'2013-10-11','2014-10-10','Donation'),
(12379, 2044,   'f' ,'2012-10-21','2013-10-20','Financial Status'),
(12380, 2044,   ''  ,'2012-10-21','2013-10-20','Donation'),
(12377, 2016,   'f' ,'2012-10-17','2013-10-16','Financial Status'),
(12378, 2016,   ''  ,'2012-10-17','2013-10-16','Donation'),
(12373, 2025,   'f' ,'2012-10-16','2013-10-15','Financial Status'),
(12374, 2031,   ''  ,'2011-10-16','2013-10-15','Donation'),
(12375, 2031,   'f' ,'2011-10-16','2013-10-15','Financial Status'),
(12376, 2044,   ''  ,'2011-10-16','2013-10-15','Donation'),
(12371, 2044,   'f' ,'2011-10-15','2013-10-14','Financial Status');

A: Here is a Northwind example.
You can "filter" by using derived tables.
And then left join on the derived table(s).
You can write yours, and you'll have 3 derived tables.
derivedCurrentMember
derivedUnrenewedMember
derivedLapsedMember
Put your filtering/logic in each derived table.  Then left join on each one.
Here is a generic Northwind example.
My "filtering logic" is whether a discount existed or not.  (innerOd1.Discount <=0 and innerOd1.Discount > 0).   You may not need the group-by.
Use Northwind
GO

Select ords.OrderID
 , ISNULL ( derived1.MyCount , 0)  as NoDiscountCount
 , ISNULL ( derived2.MyCount , 0)  as HasDiscountCount
from dbo.Orders ords

left join
( select innerOd1.OrderID , count (*) as MyCount from dbo.[Order Details] innerOd1 where innerOd1.Discount <=0 group by innerOd1.OrderID) derived1
on ords.OrderID = derived1.OrderID

left join
( select innerOd2.OrderID , count (*) as MyCount from dbo.[Order Details] innerOd2 where innerOd2.Discount > 0 group by innerOd2.OrderID) derived2
on ords.OrderID = derived2.OrderID

order by ords.OrderID

::: APPEND :::
Here is the first one.
You can fill in the rest.
declare @theDate datetime
select @theDate = getdate()

select membs.* , currentMemberDerived.[CurrentMember]  from
[dbo].[apf_Members] membs
left join
(
Select MemberID , [Description] as 'CurrentMember' from apf_finances
where @theDate between StartDate and EndDate
and Status = 'Financial Status'
) currentMemberDerived
on membs.MemberID = currentMemberDerived.MemberID


text:
Q: Subdomain friendly url redirect on multiple folders I'm setting up a apache server and trying to make friendly url's on my subdomains. This is the current setup of folders in my root folder:
mydomain ----\
        |
        | - Folder A (folder_a) --\
        |       |
        |       | - Sub Site A(subfolder) --\
        |       |       | - index from sub folder
        |       |
        |       | index from Folder A
        |
        | - Folder B (folder_a) --\
        |       |
        |       | - Sub Site B(subfolder) --\
        |       |       | - index from sub folder
        |       |
        |       | index from Folder B
        |
        | - Folder C ...

So, what does works without any htaccess are these urls:
mydomain.com/folder_a/subfolder
mydomain.com/folder_b/subfolder

But i'm trying to achieve the following result with some htaccess:
subfolder.mydomain/folder_a
subfolder.mydomain/folder_b

I tried making this htaccess on root folder:
RewriteEngine On

RewriteCond %{HTTP_HOST} ^subfolder\.domain\.com$
RewriteRule ^(\w+)/(.*)$ $1/subfolder/index.php$2 [L]

But it gives me an error 500 on apache.
And also this htaccess inside folder_a for example:
RewriteCond %{HTTP_HOST} ^subdomain\.mydomain\.com$
# RewriteRule ^(.*)$ /folder_a/subdomain/index.php$1 [L,QSA]
# OR
RewriteRule (.*) http://subdomain.mydomain.com/folder_a/subdomain/index.php$1 [L]

And it also gives me error 500.
This is my current virtual host file for these domains:
<VirtualHost mydomain.com:80>
    ServerAdmin webmaster@dummy-host2.example.com
    DocumentRoot "W:/mydomaindevteste"
    ServerName mydomain.com
    ErrorLog "logs/dummy-host2.example.com-error.log"
    CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>

<VirtualHost subdomain.mydomain.com:80>
    ServerAdmin webmaster@dummy-host2.example.com
    DocumentRoot "W:/mydomaindevteste"
    ServerName subdomain.mydomain.com
    ErrorLog "logs/dummy-host2.example.com-error.log"
    CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>

Apache error
[Mon Jan 28 07:54:12.433767 2019] [core:error] [pid 13208:tid 2032] [client 127.0.0.1:49993] AH00124: Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.
[Mon Jan 28 07:54:12.433767 2019] [core:error] [pid 13208:tid 2032] [client 127.0.0.1:49993] AH00124: Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.


text:
Q: Automatically add and persist the current date in the database I want to create a database which has one date column that needs to be automatically filled with the current date.
I tried the following design in Sql Management Studio:

The problem with this desing is that every time I insert a new record to the table, all DateEffective rows change to the current date, and I need only the last row to change.
Is there any solution to this problem?
Thanks!

A: try creating a trigger for this:
Trigger


text:
Q: Relational database primary key requirements I am trying to put together an ER Diagram to design a fairly simple asset tag tracking/inventory management system for our servers/switches/UPS/etc.  The top-level entity corresponds to the business location, followed by entities for Room, Rack, RackU, and finally device.  Now, I know that primary keys are supposed to be unique, but is that unique over the entire database, or unique for the individual branch of the system?
By that I mean, there are one to many rooms in a location, and one to many racks in each room.  do the primary keys for the racks in one room in a given location need to be unique from those of either another room in the same location, or even from a room in a different location?
I probably didn't describe this very well, so feel free to ask for clarifications on or at any point.

A: For each relation (ie. table) the primary key value must be unique and immutable (ie. it doesn't change).
You're likely to have a relation for location, one for rooms, one for racks. The primary key values for each of them must all be unique, so two racks in different rooms would not have the same PK value. However you could have the same PK value for a rack and a location, because they are different relations. There would be no significance to the values being the same or different across relations.


text:
Q: Algorithm to discover long n-gram using limited memory? What memory efficient algorithms exist for counting large n-grams. I have a large number of binary inputs (~1k) and want to discover (using an on-line algorithm) which subsets occur together more frequently than average. Am thinking that the problem is isomorphic with searching for long n-grams (with each input equivalent to a character or word), unfortunately creating a couple of terabytes worth of tables to do a simple tally is out of the question (this is going into javascript so one gigabyte would be pushing it). Am hoping somebody can point me towards some clever algorithms or ideas that I could tweak.
I don't need to keep exact numbers, just observe when say there is a subset of ten or so inputs that occur together frequently.


text:
Q: Unable to save pdf file from link in Android I want to download a PDF file from link. I am trying this code.
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setMimeType("application/pdf");
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "filename.pdf");
long reference = downloadManager.enqueue(request);

Also using permission as follows,
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

But, it giving me "Download Unsuccessful" error

A: try this.....
//This method for download file from server by using DownloadManager class
public long downloadAttachment(Context context, String fileName, String fileExtension, String destinationDirectory, String url) {

    DownloadManager downloadmanager = (DownloadManager) context.
            getSystemService(Context.DOWNLOAD_SERVICE);
    Uri uri = Uri.parse(url);
    DownloadManager.Request request = new DownloadManager.Request(uri);

    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    request.setDestinationInExternalFilesDir(context, destinationDirectory, fileName + fileExtension);

    return downloadmanager.enqueue(request);
}

and call this method.....
downloadAttachment(MainActivity.this, filename, "pdf", DIRECTORY_DOWNLOADS, url);

Hope I will help you!


text:
Q: Session handling in a Struts application I am facing an issue in handling an object in session.
I store an object in the session like this. Assume object is the name of the object. I do this in my action class:
if(object!=null)
{
session.settAttribute("objectName",object);
return mapping.findForward("success");
}
else
{
return mapping.findForward("failure");
}

I map both success and failure to the same jsp page. I check like
if(session.getAttribute("objectName")!=null)
    {
      object=  (SomeObjectClass)session.getAttribute("objectName");
    }
   if(object!=null)
   {
    //Do this
   }
   else
   {
    //Do that
   }

Now here comes my problem. There is no problem when I set the object in first time in the session. I get a problem when I call this action class from two different browsers at the same time I go to else part for one case and if part for one case. I believe this is because session is not thread safe. Is there any solution?

A: You mention that you're trying to see the same information between two browsers... if the information you're trying to share is "global" (i.e. it should be the same for ALL users of the application, you should store the information in the application scope, not the session scope. (see http://java.sun.com/developer/onlineTraining/JSPIntro/contents.html#JSPIntro5 for explanation of scopes). For example:
ServletContext servletContext = getServlet().getServletContext(); //"application scope"
SomeObjectClass object = (SomeObjectClass) servletContext.getAttribute("objectName");

if(object !=null){
  //Do this
} else {
  //Do that
}

If you have accounts and a login mechanism and you're wanting the same login to see the same information in two different browsers, then you have a different issue. In that case the information will need to be stored in a "database" (not necessarily a rdbms, could be the application scope!, depending on your needs for persistence) and the information would need to be retrieved in the action class using the user information that could be stored in the session, cookie, etc.
//get the user info from the session, cookies, whatever
UserInfoObject userInfo = getUserInfo(request);
//get the object from the data store using the user info
SomeObjectClass object = getObjectForUser(userinfo);

if(object !=null){
  //Do this
} else {
  //Do that
}

A: When you access action/page from different browser you create a new session. In modern browsers you can share session between tabs or views. The only way to share session with more browsers is to use jSessionid param in URLs.


text:
Q: Modding Unreal Engine 4 officials games, modifying .uasset I am new in Modding (I already made Big Mods principaly on GTA V or Skyrim) , and I would like to modify Tropico 6 code .
It's a pc game , made with Unreal Engine 4 .
So I unpacked the .pak , to find the main .uasset but it's seems when I try to modify this file with
Unreal Engine 4 , it's need the source code to load the project ,
So is there any way to rebuild the source with the project , or to modify .uasset ?
Thanks for your answers


text:
Q: What are the real usage of entity definition relationships and field definition relationships in custom metadata types? The trailhead here Configure your apps with custom metadata types proposes the following scenario:

*

*A custom medata type named Support Tier with default discount and minimum spending (Create and Manage Custom Metadata Types)

*An Account object with a Total Spending, rolling up Amount on opportunities and formulas to determine with a set of if statements what is the right support tier (Use Custom Metadata Types in Formulas, Default Values, and Validation Rules

*A flow to update a Picklist on the account when the Total Spending reaches the next Minimum Spending (Use Custom Metadata Types in Flows)
Later, in the Programmatic Development with Custom Metadata Types and in particular in Use Metadata Relationship fields, the approach suggested in the previous module is questioned because using a picklist and assuming its allowed values matches the instances of the custom metadata is brittle and probably also the formula Amount Until Next Tier  would exceed the maximum formula length if the number of tiers grows.
Therefore a more complicated scenario is introduced: an org with multiple  "Support product": Email Support, Online Chat and Dedicate Phone Live. Such supports products are modelled through an SObject with a Picklist named "Support Level" with values "Free", "Premium" and "VIP":

*

*Email Support : Free

*Online Chat : Premium

*Dedicated Phone Live : VIP

It then suggests that the right pattern to handle this more complex situation would be to introduce one additional custom metadata "Support Mapping" which has:

*

*one entity definition relationship

*one field definition relationship

*one metadata relationship towards the Support Tier

Then the trailhead suggests to create an instance of this new metadata type like so:

*

*The Entity Definition Relationship  is set to Support Product

*The Field Definition Relationship is set to Support Level

*The Support Tier Relationship towards the Support Tier instances named Bronze (Discount 0%, Minimum Spending 0)]

*The Support Tier Name is set to 'Free'

It then concludes with:

Now the relationships can be used within your Apex code to provide an even more enhanced user experience for Acme Services.

The following questions arise after completing this trailhead:

*

*Is there anything smart and clever that is mapping "Support Tier Name" against the instances of the picklist "Support Level"? Or is just "text fields having the same name" and you would have to perform SOQL query in Apex and interpret those?

*Why would you want to use an Entity Definition Relationship and a Field Definition Relationship if you are always setting them towards the same SObject and the same field?

*If the 1 first question is NO, what are real use cases for Entity Definitition Relationships / Field Definition Relationships besides the one that Andrew Fawcett shows in Declarative Lookup Rollup Summary?

A: A real world use case: I am currently working on a package that allows us to declaratively configure a RESTful architecture parallel to the salesforce standard REST API via Apex REST. This gives us much more control than the Standard REST API over ...

*

*Setting up resources (defining the path/sub-directory, configure allowed expansions of sub-resources and parent resources and configuring filters)

*Setting up representations (defining the exposed fields of this representations, using different naming conventions for fields (i_like_snake_case) that are independent of the salesforce scheme, exposing only particular relationships (parent/child), and so on)

*Configuring individual representations for each HTTP-Verb (GET,POST,PATCH,etc) per Request/Response (say, you expect only 3 mandatory fields for a POST Request, but you always want to render all 15 mapped fields in a Response to this POST and use a completely different representation in a Response to a GET)

All of this functionality is fully generic, and I implemented this by making extensive use of Custom Metadata Types. To summarize:

*

*The key Metadata Objects are Resources, Representations and Representation Properties

*A representation maps to a certain SObject, so there is a custom field on the metadata type "SObject__c" of the type Entity Definition where you define a particular SObject (that will be used to dynamically generate the SOQL-Query string)

*Representation has a related list of Properties, where we configure all the properties (meaning "keys" of the rendered json): In a Property, I essentially define a field mappings: The external name (i.e email) and with a Field Definition field, the salesforce field (ArbitraryBusiness_Email__c) that will be used to retrieve/store the data.

All SOQL queries to retrieve the records (during GET calls) and DML to perform more complex operations (especially PATCH and POST) is generated dynamically, fully generic during runtime based on the meta data records.

A: In terms of your questions at the end:

*

*No, there's nothing clever here, unfortunately. Relationships to picklist values was something that we planned to support, but we don't have it and it isn't on the immediate roadmap.

*There are a number of reasons why we make you specify an Entity definition before you can specify a Field definition, but the simplest one is that populating a single dropdown list with every field in an organization would be impractical, given that standard fields and entities are included (it's not hard for an organization to have well over a million field definitions across all entities). And it would be even worse unless we used "Entity.Field" format, because, e.g., thousands of entities could all have a field called "Name".

*I'll let other customers and partners answer this one, as J. Lietzau has already done.


text:
Q: How to mark interactively specific points in a 3dplot? I have the following code
f[x_, y_, \[Alpha]_: 0] := x^3 - y^3 + 3 \[Alpha] x y
Manipulate[Plot3D[f[x, y, \[Alpha]], {x, -10, 10}, {y, -10, 10}], {\[Alpha],-5,5, 1}]

and I want to mark the points f[0,0,\[Alpha]] and f[1,-1,\[Alpha]] in the graph. I saw some other questions similar to this one but it doesnt deal with interactive content so in all cases I searched in the forum the solutions have static variables that cant be applied to this case.
I will be glad if some one shows me how to add these points to the graph. Thank you.

A: The interactivity doesn't really change anything. Just use Show in the standard way:
f[x_, y_, α_: 0] := x^3 - y^3 + 3 α x y;
Manipulate[
 Show[
  Plot3D[f[x, y, α],
   {x, -10, 10}, {y, -10, 10}],
  Graphics3D[
   {
    AbsolutePointSize[15],
    Point[{
      {0, 0, f[0, 0, α]},
      {1, -1, f[1, -1, α]}
      }]
    }
   ]
  ],
 {α, -5, 5, 1}
 ]


text:
Q: Saving state in a WPF application I am developing a WPF application with a treeview. I have Treeview like windows. Now what I want is if select I the treeviewitem, let's say...

+Desktop
|
+---My Computer
    |
    +---C:\
        |
        +---Some Folder.

I selected the foldername called Some Folder in c drive. After that I close the application. When I open the application again the focus again should be on Some Folder in c drive. In other words, I need the same path selected after re-opening the application.

A: Slightly OT - be careful with this. If you quit while pointing to a folder on a flash drive or CD, that location may not exist when you restart the application. By adding this requirement to restart in the old location, you also add the requirement to fail gracefully, and to a different location, if the old location doesn't succeed.

A: You could save the value in Application.config and then check if it has a value in there when you re-open the app and re-select the branch

A: Save you TreeView "SelectedValuePath" value in application settings and re-assign its value at the time of load. Of course you have to take care of its validity. The path might not exists at the time of loading.


text:
Q: Question: Howto change a funtion to a class in python I want to create a class with methods, so that I do not have to create multiple functions.
Below is my code, I want to get a class with two methods. Method 1: SQL Query, method 2: sql insert.
Any tipp is greatly appreciated.
Stefan
def dbconnect():
    dbconn = pymysql.connect(host='192.168.1.2', port=3307,  user='username', passwd='password', db='dbname')
    try:
        cur = dbconn.cursor()
        sqlQuery = "select * from data"
        sqlQuerygetlast = "SELECT * FROM data ORDER BY id DESC LIMIT 1"
        sqlQuerygetlast10 = "SELECT * FROM data ORDER BY id DESC LIMIT 10"
        cur.execute(sqlQuerygetlast10)
        rows = cur.fetchall()
        for row in rows:
            print(row)
    except Exception as e:
        print("Exeception occured:{}".format(e))
    finally:
        #dbconn.commit()
        dbconn.close()

My objective is to call the methods from my code, i.e. query a select statement.
Thanks a lot
Stefan

A: I guess you mean that you don't want to create multiple connections?
Then you should implement it as a Context manager:
class DB:
    def __init__(self):
        self.dbconn = None

    def get_last(self, n)
        try:
            cur = self.dbconn.cursor()
            sqlQuerygetlast = "SELECT * FROM data ORDER BY id DESC LIMIT {}".format(n)
            cur.execute(sqlQuerygetlast)
            rows = cur.fetchall()
            for row in rows:
                print(row)
        except Exception as e:
            print("Exeception occured:{}".format(e))
        finally:
            # self.dbconn.commit()

    def some_other_method(self):
        self.dbconn.do_something()

    def __enter__(self):
        self.dbconn = pymysql.connect(
            host='192.168.1.2',
            port=3307,
            user='username',
            passwd='password',
            db='dbname'
        )
        return self

    def __exit__(self, exc_type, exc_value, exc_traceback):
        dbconn.close()
        return True

and use it as follows:
with DB() as db:
    db.get_last(1)
    db.get_last(10)
    db.some_other_method()

This will create only one instance of a database connection and close after it is finished.

A: Writing a class in Python is fairly simple.
Here's an example of how to write the classic Person class and how to use properties and methods.
Specifically, the presentation method is also making use of the name property.
From this example you can move on and build your Database class implementation quite easily:
class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def presentation(self):
    print("Hello my name is " + self.name)

p1 = Person("John", 36)
p1.presentation()

Remember that in all the methods of a class you will have to specify the reserved keyword self as parameter (plus, clearly, any other parameter you might need).


text:
Q: how evaluate function works in keras I am a bit confused about what value I should be expecting from Keras's evaluate function.
Here is the evaluate function definition from Keras documentation:
evaluate(self, x=None, y=None, batch_size=None,
         verbose=1, sample_weight=None, steps=None)

And here is the short description from the same page:

Returns the loss value & metrics values for the model in test mode.

If I have a large cross validation dataset which kind of requires me to call the evaluate function several times, does the evaluate function remember previous calls? Or does it only return, say, the loss value for the given mini-batch each time?

A: The evaluate() method evaluates the model on the whole data you pass to it and therefore the given loss value and the metric(s) value(s) are based on the performance of the model on the whole data.
Further, there is another method called test_on_batch() which tests the model on a single batch of data and returns the corresponding loss value and metric(s) value(s) of the model on the given data batch.
However, I am not sure what you mean by saying "I have a large cross validation data set which kind of requires me to call the evaluate function several times..." (emphasize mine). Do you mean the whole validation data does not fit in memory? If that's the case, and you have stored the validation data in a file on the disk (say a h5py file), then you can define a generator and use evaluate_generator() method to perform evaluation using the generator you have defined.


text:
Q: AWS DMS Propagate Truncate MySQL RDS I'm hoping someone has come across this before and figured out a way to solve it. I have a MSSQL table hosted on prem that I need to keep in sync with Dynamo DB. It's a large database with a lot of tables but I don't need ALL the data off of it, I just need to query some data and that output that query result to DynamoDB. I need CDC on the data as well, meaning if the last query yields different results (update, delete, create) it is also reflected in the DynamoDB table.
I was able to accomplish this by doing:
AWS Batch -> Python script to query data and insert into MySQL table -> AWS DMS for replication -> DynamoDB
The issue with this is since it's a batch job I need to be able to truncate the MySQL table and just load new data in, and have that be reflected on DynamoDb. The issue with that is DMS does NOT support truncate queries. I was wondering if maybe I just looped through all the rows and deleted them if it would work as a pseudo "Truncate" since delete and inserts to the table seem to be replicated perfectly to DynamoDB via DMS.
Is there a better way to do this? Will this work?


text:
Q: Facebook integration, Recommend button on specific product page + show the product image I have a question about how to integrate the facebook plugin, recommendbutton.
I got the code from facebook like button and put it on the page where i want it displayed. But this only creates a like on the current page with a radom picture of the site and text.
I want the button to be associated with the productpicture and description.
Does anyone have a code like this to share?

A: Take a look at http://ogp.me/ for a description of the OG meta tags which help Facebook display your product in a more meaningful way. You can test a URL using the debug tool at https://developers.facebook.com/tools/debug to see whether the OG tags have been added correctly.
If your page is behind a login, you'll need to either have a version of the page that still displays OG tags and basic content when not logged in, or have a rule that shows the correct tags when the User Agent is the Facebook Scraper. See https://developers.facebook.com/docs/reference/plugins/like/#scraperinfo for info on the User Agent string used.

A: you need the opengraph tags for this. see http://developers.facebook.com/docs/reference/plugins/like/ for details.

A: Just add data-href to your Facebook like code:
            <div id="{{ item.product.code }}"
                    class="fb-like"
                    data-share="false"
                    data-href="{{ url }}"
                    data-width="250"
                    data-show-faces="true">
            </div>


text:
Q: reading string from a file in c I've got an input file like this:
1 2 2 Medium
1 2 0 Medium
2 1 0 Medium
2 0 2 Medium

I am using fscanf() to read in the integer values and that is working fine. does anyone have any ideas how to read in the string and place it in a string variable???
int x,y,z;
char* cs;
fscanf(fp3,"%d",&x);
fscanf(fp3,"%d",&y);
fscanf(fp3,"%d",&z);
fscanf(fp3,"%s",&cs);

A: You need already allocated space to store the string. Try something like this:
int x,y,z;
char cs[20];
fscanf(fp3,"%d",&x);
fscanf(fp3,"%d",&y);
fscanf(fp3,"%d",&z);
fscanf(fp3,"%19s",cs);

You can also scan for all the values at once:
fscanf(fp3,"%d %d %d %19s", &x, &y, &z, cs);

N.B: Always use %<length>s in a scanf pattern to prevent buffer overflow.

A: 2 things to say:

*

*It looks nicer when you use one format string

*You should use a loop

Here's some code:
int a,b,c;
char str[256];
while(fscanf(fd, "%d %d %d %s ", &a, &b, &c, str) == 4){
    //get some coffee
}

this is a standard while not End of File loop. Also, str doesn't need & because it already is a pointer and doesn't need to be referenced like a, b or c. The space at the end of the format string, after %s, means it will stop once that one space is read. This way it is not included in the string str.

A: Watch out for two things:

*

*You need to reserve a buffer to copy the string into.

*Also never ever use a plain "%s" scanf pattern. It should be forbidden. Instead insert the length of the buffer, minus 1 between the % and the s. E.g., "%7s" for an 8 byte buffer.


text:
Q: MDRIVEN | ContextAgent in VS 2019 Unable to access Context Agent in VS 2019 with the latest MDriven Framework.
Has it been removed or there is any way to bring it inside VS 2019?

A: The Context Agent was part of the MDriven Framework visual studio plugin until 2019 builds. It was removed as it represents the older strategy of placing handle components on windows forms.
The modern way of working is to declare ViewModels in Modlr and bind to these.
A much more effecient way to track the model usage is to use the ViewModels with CodeGen-box checked and then bind to the generated information structure from the UI controls - thus skipping the handles all together.


text:
Q: Center a text box and button perfectly using bootstrap 5 I have the following html using bootstrap 5:

Let's get started...

    <input id="form-input" style="display: inline-block;" type="text" class="form-control mb-3 w-25" placeholder="Search for a prefix" />

    <button id="form-button" type="submit" class="btn btn-primary btn-lg">Find Numbers</button>

This is the result in a browser:

How can I make sure they are exactly the same height, and if the browser is made too small, the submit button will drop beneath the input

A: Honestly I did not quite understand your goal, so excuse me if my answer is wrong.
You can user screen.width to make the submit button will drop beneath the input.
let width = screen.width;
if(width > // any number you want) {
    document.getElementById('form-input').style = 'display: block; margin-left: X px'
}

And for the same height you can use position: relative; and position: absolute:
div {
    positon: relative;
}

input,
button {
    positon: absolute;
    top: 0;
}

Hope this helps.

A: You need to wrap them with flex parent like this:

Let's get started...

  <input id="form-input" style="display: inline-block;" type="text" class="form-control" placeholder="Search for a prefix" />
  <button id="form-button" type="submit" class="btn btn-primary btn-lg">Find Numbers</button>

and adjust the width for the small screen (I'd suggest using col-lg-* but you are using form-control so it has 100% width):
.form-control {
  width: 25%;
}
@media(max-width: 767px) {
  .form-control {
     width: 80%;
     margin-bottom: 20px;
  }
}


text:
Q: How to get landmarks (points of interest) near a given location using Google Places API I have used Places API to get places such as restaurants and hotels near a given location, and it is working fine. I want to get points of interest or landmarks near the given location as well. What I tried is given below:
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
        location: latlng,
        radius: 1500,
    }, function (results, status) {
        if (status === google.maps.places.PlacesServiceStatus.OK) {
            var type1 = results[i].types[0];
            var type2 = results[i].types[1];
            if (type1 == 'point_of_interest' || type2 == 'point_of_interest') {
                //process place details
            }
        }
    });

Eg: For a landmark search near Champ de Mars in Paris, it should return places such as Eiffel Tower, which is quite nearby. However, it returns only places such as hotels and lodging.
How can I get it to return points of interest near the given location? Any help on solving this would be appreciated.

A: You can use a keyword parameter in places search request. According to the documentation keyword parameter is:

A term to be matched against all available fields, including but not limited to name, type, and address, as well as customer reviews and other third-party content.

So something like keyword: "POI" can make a trick. Please have a look at the following example.
code snippet:

    var map, service;

function initialize() {
    var champdemars = new google.maps.LatLng(48.8556475,2.2986304);
    var mapOptions = {
        zoom:14,
        center: champdemars
    };
    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    service = new google.maps.places.PlacesService(map);
    service.nearbySearch({
        location: champdemars,
        radius: 1500,
        keyword: "POI"
    }, function (results, status) {
        if (status === google.maps.places.PlacesServiceStatus.OK) {
            results.forEach(function (p) {
                var m = new google.maps.Marker({
                   position: p.geometry.location,
                   icon: {
                     url: p.icon,
                     scaledSize: new google.maps.Size(24,24)
                   },
                   title: p.name,
                   map: map
                });
            });
        } else {
            alert(status);
        }
    });
}
html,
body,
#map-canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}

As you can see POIs like Eiffel Tower, The Army Museum or UNESCO now appear on the map.


text:
Q: What is the fastest way to combine 8 uint8_t into a single uintmax_t? I am looking to optimize a piece of code that uses popcnt to compute differences between uint8_ts.  I figure it'd be faster to combine 8 uint8_ts into a single uintmax_t and use popcnt64 instead so that the popcnt operation doesn't have to be called 8x more than necessary.  What is the fastest way to feed 8 uint8_t into popcnt64?  Can I use some kind of casting?  Should I make use of bit manipulation?  I'm not aware of C++'s internal workings so I'm not sure what the fastest way is to make this conversion.

A: Assuming you don't care about endianness – you just want to treat the uint8_ts as a uint64_t and you don't care about the order of the uint8_ts – then you can just use std::memcpy to do the type punning:
std::uint64_t combine(std::array<std::uint8_t, 8> b) {
    static_assert(sizeof(b) == sizeof(std::uint64_t));
    static_assert(std::is_trivially_copyable_v<std::uint64_t>);
    static_assert(std::is_trivially_copyable_v<decltype(b)>);

    std::uint64_t result;
    std::memcpy(&result, b.data(), sizeof(result));
    return result;
}

The generated assembly just returns the argument:
combine(std::array<unsigned char, 8ul>): # @combine(std::array<unsigned char, 8ul>)
  mov rax, rdi
  ret

Using anything else for type punning makes it so you have to worry about strict aliasing rules or alignments of types. It's easy enough to just use std::memcpy and let the compiler deal with it

Note that the easiest way of calling any variant of popcnt from C++ is to use std::bitset::count. So instead of __builtin_popcountll(my_u64) or __popcnt64(my_u64), you could just write std::bitset<64>{my_u64}.count() and you instantly get portable code.


text:
Q: Custom Snort rule prevent me from starting the WAN interface I'm having an issue where when I add a custom rule to my WAN interface(SNORT), I can't start the interface, not even the simplest ping rules work now despite having worked just fine all day.
Trouble started after I started doing some test monitoring of some SMB traffic with the following rule:
alert tcp any any -> $HOME_NET[139, 445] (msg:"Home network SMB triggered"; flow:to_server,established; content:"P|00|S|00|E|00|X|00|E|00|S|00|V|00|C"; nocase; reference:url,xinn.org/Snort-psexec.html; reference:url,doc.emergingthreats.net/2010781; classtype:suspicious-filename-detect; sid:2010781; rev:3; metadata:created_at 2010_07_30, updated_at 2010_07_30;)

Not sure what went wrong, but the rule didn't work, and now my other custom rules don't either(as in they prevent me from starting the interface).
Anyone who knows what has happened?

A: The problem with your rule is in the spacing.

alert tcp any any -> $HOME_NET[139, 445]

is parsed as

*

*SrcIP:  any

*SrcPort: any

*DstIP: $HOME_NET[139,

*DstPort: 445]

which is invalid
you want:
alert tcp any any -> $HOME_NET [139,445]

This will allow the rule to validate.


text:
Q: Delayed effect on showing new rows in table I've made a jsfiddle to make it simpler for me to explain. (http://jsfiddle.net/FPznm/).
What I'm trying to do is that when you click the 'Visa mer' button at the end of the table I want the hidden rows to be faded in with a delay.
It does not work as it currently is and I don't know why. (See the Javascript window on jsfiddle).
The problem is that if I add an .delay() before .fadeIn() the fadeIn() effect disappears but they still gets displayed.
  for (i = 0; i <= increaseBy; i++) {
        hidden.eq(i).delay(i * 20).fadeIn(500);
        hidden.eq(i).removeClass("hidden");
    }

This is the code where the trouble is at. I'm figuring that .eq() is what's making it not work.

A: That's because removeClass is executed faster than fadeIn method, you can remove the class when animation is complete.
hidden.eq(i).delay(i * 20).fadeIn(500, function(){
    hidden.eq(i).removeClass("hidden");
});

http://jsfiddle.net/k28WT/
If you want to select the first 5 elements with class of hidden you can  use :lt selector:
$(document).ready(function() {
    $("td.showMore").on('click', function() {
        $("tr.hidden:lt(5)").each(function(i){
            $(this).delay(i + 200).fadeIn(500, function(){
               $(this).removeClass('hidden')
            })
        })
    });
});

http://jsfiddle.net/vex3R/

A: I have created a fiddle which explains my answer: http://jsfiddle.net/3leven11/FPznm/5/
All you need to do is this:
$(document).ready(function() {
    $("td.showMore").on('click', function() {
        var increaseBy = 5;
        $("tr.hidden").each(function(index, elem) {
            if (index <= increaseBy) {
                $(elem).delay(index * 20).fadeIn(500, function() {$(elem).removeClass('hidden');});
            }
        });
    });
});

A: The problem is that the animation is asynchronous, so you are removing the class instantly
Try this instead..beware that table rows do not animate well
$("td.showMore").on('click', function() {
        var hidden = $("tr.hidden"),
            increaseBy = 5;
        for (i = 0; i <= increaseBy; i++) {
            hidden.eq(i).delay(i * 200).fadeIn(1000, function(){
                   $(this).removeClass("hidden");
            });

        }
    });

EDIT: Also note that your delay of 20 is 20ms which 1/50th of a second, the human eye can't even register that

A: You need to remove this line: hidden.eq(i).removeClass("hidden");
fadeIn is asynchronous: internally it's probably working with setTimeout or setInterval. You've specified to have the fadeIn completed after 500 ms, but are removing the hidden class immediately after (without waiting for the 500 ms to pass)
If you need to change a class or do something else after the fadeIn is done, you can provide a call back to fadeIn, that will be executed after the animation is done. For more details see: http://api.jquery.com/fadeIn/


text:
Q: change brightness of image on hover

    CHANGE AVATAR

.profile_picture{
        width: 60px;
        height: 60px;
        object-fit: cover;
        border-radius: 50%;
        margin-left: 65px;
        filter: brightness(100%);
        cursor: pointer;
}

.profile_picture:hover{
    filter: brightness(70%);
    transition: filter 0.25s ease;
}

.t_overlay{
    position: absolute;
    margin-left: 76px;
    margin-top: -43px;
    font-size: 10px;
    height: 0px;
    width: 0px;
    line-height: 1.2;
    -moz-user-select: none;
  -khtml-user-select: none;
  -webkit-user-select: none;
    cursor: pointer;
    opacity: 1;
    color: white;
}

.t_overlay:hover profile_picture{
    filter: brightness(70%);
}

I have a code that if you hover over an profile picture it decreases brightness of profile picture to 70% percent. "CHANGE AVATAR text is in the middle of profile picture. If I hover over "CHANGE AVATAR" text, brightness of profile picture increases to 100% again but I want it to stay to 70%.

A: See the updated code below. Run the snippet.
I simply added pointer-events: none;
to .t_overlay
Here is documentation for pointer events.

.profile_picture{
        width: 60px;
        height: 60px;
        object-fit: cover;
        border-radius: 50%;
        margin-left: 65px;
        filter: brightness(100%);
        cursor: pointer;
}

.profile_picture:hover{
    filter: brightness(70%);
    transition: filter 0.25s ease;
}

.t_overlay{
    position: absolute;
    margin-left: 76px;
    margin-top: -43px;
    font-size: 10px;
    height: 0px;
    width: 0px;
    line-height: 1.2;
    -moz-user-select: none;
  -khtml-user-select: none;
  -webkit-user-select: none;
    cursor: pointer;
    opacity: 1;
    color: white;
    pointer-events: none;
}

.t_overlay:hover profile_picture{
    filter: brightness(70%);
}

    CHANGE AVATAR


text:
Q: Condition for incompressible flow I have given a set of differential equation (linear),
\begin{align}
\frac{dx}{dt} &= ax+by \\
\frac{dy}{dt} &= cx+dy
\end{align}
where $a,b,c$ and $d$ are constants.
I'm trying to find out the condition so that area  elements remain same
$$dx(t)dy(t)=\text{constant}$$
That is a incompressibility condition of fluid element.
It seems to be Liouville's theorem that lead to conclusion :
$$\frac{\partial\dot{x}}{\partial x}+\frac{\partial \dot{y}}{\partial y}=0$$
$$\Rightarrow a=-d$$
But I used this sketch, It seems it didn't work. Is this condition right?

$\dot{x}$ stands for time derivative of variable $x$.


text:
Q: How do I call a specific field in a model into another model? I am new to django. I wanted to know if it was possible to call a specific field in a model into another model.
The goal is to update a the quantity of a specific product in the database and generate a receipt for it.
Here's the example:
models.py:
class Product(models.Model):
   name = models.CharField(max_length=300, null=True)
   price = models.FloatField(null=True)
   quantity = models.IntegerField(default='0', blank=True, null=True)

class UpdateStock(models.Model):
  date = models.DateTimeField(default=timezone.now)
  wayBill_Number = models.CharField(max_length=300, null=True)
  product_Name = models.ForeignKey(Product.name, null=True, on_delete= models.SET_NULL)
  quantity = models.ForeignKey(Product.quantity, null=True, on_delete= models.SET_NULL)

I just want to select the product and the quantity to update in the database but I am unable to do so.

A: A ForeignKey is supposed to refer to another model, not to one of its fields.
So the first thing you have to do it to edit your UpdateStock model this way :
 class UpdateStock(models.Model):
    date = models.DateTimeField(default=timezone.now)
    wayBill_Number = models.CharField(max_length=300, null=True)
    product = models.ForeignKey('Product', null=True, on_delete=models.SET_NULL) # Here
    quantity = models.IntegerField(default='0', blank=True, null=True) # Here

So you can bound your product to your stock_update when you create it:
stock_update = UpdateStock.objects.create(..., product=your_product_obj, ...)

And you will then be able to access any product's field from this stock_update:
product = stock_update.product
print(product.quantity)
product.quantity = product.quantity + stock_update.quantity
print(product.quantity)
product.save()

But I strongly advise you to read more about many-to-one relationships in the docs.


text:
Q: Change plot style as function of parameter in ParametricPlot The Manipulate below produces a path traversing the upper unit semicircle, going from {1,0} at time 0 to {-1,0} at time 1/2, then traversing the same upper semicircle, but in the reverse direction, going back from {-1,0} at time 1/2 to {1,0} at time 1.
However, one cannot "see" the reverse half of the path, since it lies on top of the same semicircle, but traversed in the reverse direction, of the forward half.
Is it possible to use a PlotStyle, or other directive, to change the style of the curve at time 1/2 so that, for example, the plot from then onward is thicker and a different color?
f[t_ /; 0 <= t <= 1/2] := ReIm[Exp[2 \[Pi] I t]]
f[t_ /; 1/2 < t <= 1] := ReIm[Exp[2 \[Pi] I (1 - t)]]

Manipulate[
 ParametricPlot[f[t], {t, 0, v},
  PlotRange -> {{-1, 1}, {-1, 1}}], {{v, 0.01}, 0.01, 1}]

(I do realize that there's a way to fake the result I want, namely, by changing the function f on the half-interval {1/2, 1} so as to have a slightly greater radius than 1. But I would much prefer to leave the radius unchanged and "merely" change the style of the curve's thickness and/or color on that half-interval.)

A: Clear["Global`*"]

f[t_ /; 0 <= t <= 1/2] := ReIm[Exp[2 \[Pi] I t]]
f[t_ /; 1/2 < t <= 1] := ReIm[Exp[2 \[Pi] I (1 - t)]]

You could use ColorFunction
EDIT:
Manipulate[
 ParametricPlot[f[t], {t, 0, v},
  PlotRange -> {{-1, 1}, {-1, 1}},
  ColorFunction -> (If[#3 < 1/2, Blue, Red] &),
  ColorFunctionScaling -> False],
 {{v, 0.01}, 0.01, 1, 0.01, Appearance -> "Labeled"}]

A: The plot of a single function without singularities will result in a single Line object, which can only a single thickness.  To get two thicknesses, you would need to draw two lines.  This may or may not be acceptable, since it doesn't look like a single function.
Either
Manipulate[
 ParametricPlot[{
   Style[ConditionalExpression[f[t], t <= 1/2], AbsoluteThickness[1], Blue],
   Style[ConditionalExpression[f[t], t >= 1/2], AbsoluteThickness[3], Red]},
  {t, 0, v},
  PlotRange -> {{-1, 1}, {-1, 1}},
  PlotRangePadding -> Scaled[0.01]],
 {{v, 0.01}, 0.01, 1, 0.01, Appearance -> "Labeled"}]

or
Manipulate[
 ParametricPlot[{
   ConditionalExpression[f[t], t <= 1/2],
   ConditionalExpression[f[t], t >= 1/2]},
  {t, 0, v},
  PlotRange -> {{-1, 1}, {-1, 1}},
  PlotStyle -> {
    Directive[AbsoluteThickness[1], Blue],
    Directive[AbsoluteThickness[3], Red]},
  PlotRangePadding -> Scaled[0.01]],
 {{v, 0.01}, 0.01, 1, 0.01, Appearance -> "Labeled"}]

A: You can also use MeshFunctions, Mesh and MeshShading options as follows:
Manipulate[ParametricPlot[f[t], {t, 0, v},
   MeshFunctions -> {#3 &},
   Mesh -> {{1/2}},
   MeshStyle -> None,
   MeshShading -> {Directive[CapForm["Butt"], AbsoluteThickness[7], Blue],
      Directive[CapForm["Butt"], AbsoluteThickness[4],
         Dashing[{Large, Medium}], Red]},
   PlotRange -> {{-1, 1}, {-1, 1}} 1.1],
 {{v, 0.01}, 0.01, 1}]

Use
MeshShading -> {Directive[AbsoluteThickness[1], Blue],
     Directive[AbsoluteThickness[7], Dashing[{Large, Medium}], Opacity[.5, Red]]}

to get

A: f[t_ /; 0 <= t <= 1/2] := ReIm[Exp[2 π I t]]
f[t_ /; 1/2 < t <= 1] := ReIm[Exp[2 π I (1 - t)]]

Manipulate[
 ParametricPlot[f[t], {t, 0, v}, PlotRange -> {{-1, 1}, {-1, 1}},
  ColorFunction -> Function[{t}, If[t > 1/4, Blue, Black]],
  ColorFunctionScaling -> False], {{v, 0.01}, 0.01, 1}]

Manipulate[
 ParametricPlot[f[t], {t, 0, v}, PlotRange -> {{-1, 1}, {-1, 1}},
  PlotStyle -> If[v > 1/4, {Blue, Bold}, {Black, Dashed}]], {{v,
   0.01}, 0.01, 1}]


text:
Q: Trying to calculate forces and torque I am designing (in my mind) an accordian / scissor crane, but have little knowledge of calculating torque, fkg/cm etc.
I've enclosed a sketch. I need to pull the apex of the triangles together to extend, or "repel" apart to shrink the mechanics. My current thinking is two gears on each beam, one fixed, one loose. The latter will 'orbit' the former, (the pivot 'fixed' to the second beam) such that if a motor drives the free running gear, it will force the angle of beams to increase / decrease.
I know the basic fulcrum stuff re a 1.5kg weight at 5mtr needs a counterbalance of 5kg at 1.5mtr to balance. But no idea how to calculate the driving forces a motor would need to turn the cogs / move the beams.
To further complicate things, I believe "lift" has also got to be factored in as the unit will not be horizontal as per picture, but inclined at about 60 degrees with <1.5kg at the far end.
I've no idea how to work out how 'strong' the motor would need to be. That said, I'm also thinking of using a 20:1 worm gear on loose cog, so in theory the torque of the motor would be 20 times greater than the quoted fkg/cm. (I'm looking at running the motor about 5 seconds at a time to move the gears through <180 degrees to go from 1mtr to 5mtr extension
If it can be answered, can it be done in fairly "layman terms" as sin, cosine, tangents, logs and equations are alien to me!
(In case anyone is unsure of a 'scissor' arrangement, it's like a series of "X" with the top ends joined to each other "XXXXX" and if the top and bottom of each diamond is pulled closer together, the unit extends)
)