text:
Q: Fastest way to sort a large number of arrays in python I am trying to sort a large number of arrays in python. I need to perform the sorting for over 11 million arrays at once.
Also, it would be nice if I could directly get the indices that would sort the array.
That is why, as of now I'm using numpy.argsort() but thats too slow on my machine (takes over an hour to run)
The same operation in R is taking about 15 minutes in the same machine.
Can anyone tell me a faster way to do this in Python?
Thanks
EDIT:
Adding an example
If I have the following dataframe :
agg:

x      y        w        z

1      2        2        5
1      2        6        7
3      4        3        3
5      4        7        8
3      4        2        5
5      9        9        9

I am running the following function and command on it:
def fucntion(group):
    z = group['z'].values
    w = group['w'].values
    func = w[np.argsort(z)[::-1]][:7]  #i need top 7 in case there are many
    return np.array_str(func)[1:-1]

output = agg.groupby(['x,'y']).apply(function).reset_index()

so my output dataframe will look like this:
output:

x   y   w

1   2   6,2
3   4   2,3
5   4   7
5   9   9

A: Well for cases like those where you are interested in partial sorted indices, there's NumPy's argpartition.
You have the troublesome np.argsort in : w[np.argsort(z)[::-1]][:7], which is essentially w[idx], where idx = np.argsort(z)[::-1][:7].
So, idx could be calculated with np.argpartition, like so -
idx = np.argpartition(-z,np.arange(7))[:7]

That -z is needed because by default np.argpartition tries to get sorted indices in ascending order. So, to reverse it, we have negated the elements.
Thus, the proposed change in the original code would be :
func = w[np.argpartition(-z,np.arange(7))[:7]]

Runtime test -
In [162]: z = np.random.randint(0,10000000,(1100000)) # Random int array

In [163]: idx1 = np.argsort(z)[::-1][:7]
     ...: idx2 = np.argpartition(-z,np.arange(7))[:7]
     ...:

In [164]: np.allclose(idx1,idx2) # Verify results
Out[164]: True

In [165]: %timeit np.argsort(z)[::-1][:7]
1 loops, best of 3: 264 ms per loop

In [166]: %timeit np.argpartition(-z,np.arange(7))[:7]
10 loops, best of 3: 36.5 ms per loop

A: The reason python is so much slower than R is that by python does not typecast variables (i.e. int, string, float), so part of each comparison to determine which value is larger is spent determining the variable type.
You can't fix this problem using python alone, but you can include type definitions using cython (ctypes and psyco also can perform the same function, but I prefer cython). An simple example of how this works is on http://docs.cython.org/src/quickstart/cythonize.html
Cython compiles a .c version of your python file, that can be imported instead of the .py to reduce the runtime. All the possible ways to compile using cython are shown on http://docs.cython.org/src/reference/compilation.html

A: Your input and output is a bit confusing. Please provide some sample data.
But look into: http://pandas.pydata.org/pandas-docs/stable/api.html#reshaping-sorting-transposing
Pandas sorting is as optimized as it gets. Focus on the series sort as each column of the DataFrame is more accurately represented as a series.


text:
Q: curl command to print query string parameters in php Is there any command in php curl to print response query string parameters
Below is my php code
      <?php
      session_start();

      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL,"http://192.168.1.220/cgi-bin/handle_login.tcl");
     curl_setopt($ch, CURLOPT_POST, TRUE);
     curl_setopt($ch, CURLOPT_POSTFIELDS,
        "user=admin&pw=admin&submit=Login&sid=' '");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: x-www-form-urlencoded'));

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
     $response = curl_exec($ch);
     echo "$response";
     curl_close ($ch);
  ?>

below is header response
      Request URL:http://localhost:8080/cgi-bin/frameset.tcl?
      sid=3514275041172666092
      Request Method:GET
      Status Code:404 Not Found
      Remote Address:[::1]:8080
      Referrer Policy:no-referrer-when-downgrade

Response Headers
    Accept-Ranges:bytes
    Connection:Keep-Alive
    Content-Language:en
    Content-Type:text/html; charset=utf-8
    Date:Mon, 29 May 2017 06:54:33 GMT
    Keep-Alive:timeout=5, max=99
    Server:Apache/2.4.18 (Win32) OpenSSL/1.0.2e PHP/7.0.4
    Transfer-Encoding:chunked
    Vary:accept-language,accept-charset

Request Headers
  Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,
         */*;q=0.8
  Accept-Encoding:gzip, deflate, sdch, br
  Accept-Language:en-US,en;q=0.8
  Connection:keep-alive
  Cookie:PHPSESSID=hj7kbp4hp0pjq16m1tk7j3goo3; _ga=GA1.1.981975196.1489736033; XDEBUG_TRACE=XDEBUG_ECLIPSE
  DNT:1
  Host:localhost:8080
  Referer:http://localhost:8080/nias/automate.php
  Upgrade-Insecure-Requests:1
  User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36

Query String Parameters
    sid=3514275041172666092 //need to print these value

A: Since output was in string format and the output remains constant eachtime..needed to find the position of the required character in the string and extract the required value..
Below is the code
           $response= curl_exec($ch);//executes the curl
           echo strpos("$response","variable_to_find")."<br/>";//know the position
           $sid = substr($response,position,length);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Domino web server config I am configuring a Domino web server.  I have configured it as follows:

*

*Web server has no connection to admin server.  Connections are initiated by the Admin server.

*Admin server has a connection document, replicating core system dbs and the application.

*Connection document is also configured for mail.  The admin server is the server configured to send mail, so I want the email to be collected from the web server when this connection initiated by the admin server is made, and for the email to simply wait on the web server until this happens.

*Both servers are in the same notes named network.

I have a situation where the email is dead and is not being collected by the admin server as it cannot find a route to deliver the email.  I thought this would be covered by them being in the same notes named network, with the admin server being the only one with config to send mail.
I don't want to have a connection from my web server to the admin server (for security reasons) - can anyone recommend a suitable configuration for this scenario?

A: Mail is always push, there is no possibility to "pull" mail. As long as there is no possibility for the web- server to connect to the admin- server you will not be able to route any mail.
If you really can't open port 1352 inbound, then you need to write a little agent, that "pulls" the mail from a repository database by simply copying it to its own mail.box. We use this szenario in some places since years now, and it works well:
The Web- Server has to be configured to send all mail to a "container"- database. We usually do this by removing the web- server from the domain and give it a own addressbook with two domain- documents:
First of all a "Foreign-Domain- Document".
Basics
Foreign Domain Name: DummyDomain

Mail Information
Gateway server name: WebServer/Domain
Gateway mail file name: mailContainer.box

Then a "SMTP-Domain- Document":
Routing
Internet Domain:    *.*
Should be routed to Domain: DummyDomain

If you need "internal" mails to be routed, then you need another foreign- Domain- document, that points to the same container:
Basics
Foreign Domain Name: YourDomain

Mail Information
Gateway server name: WebServer/Domain
Gateway mail file name: mailContainer.box

Of course "mailContainer.box" needs to be manually created and Admin- Server needs full access to it. But then the agent (running every 5 Minutes) just needs a few lines of code, to cut & paste the documents into the mail.box


text:
Q: Export SSL certificate uploaded in Elastic Loadbalancer(ELB) Is there any way to export/download the uploaded SSL certificate and private keys from ELB ?
Any solution via SDK or console will work.

A: No, there isn't.
The documentation does not appear to explicitly explain this, but there's an intuitive and compelling argument to be made that this design limitation is correct -- that anyone authorized to be in possession of the private key already has a way to obtain it.
If the service allowed it to be retrieved, that would present a substantial security risk.
If all you need is to inspect the certificate or chain, that's easy enough using any web browser, or from the command line with openssl s_client -showcerts -connect hostname:port to an endpoint using the certificate,  so I'm assuming that what you really want here is the private key... which can't be retrieved.


text:
Q: When is it appropriate to use couchDB? I'm currently writing an app with quite a few different data persistence needs at very different layers and I keep wondering... when is it appropriate and when is it not appropriate to use couchDB to satisfy my persistence needs?

A: See:

*

*What are the advantages of CouchDB vs an RDBMS

*Why should I use document based database instead of relational database?

*Pros/cons of document-based databases vs. relational databases

A: After implementing two production systems on top of nonrelational db, I came to conclusion that nonrelational dbs need to step little bit closer to sql to be really "alternative" to it. I understand alternative as "you get same functionality without huge difference in quality, effort or cost."
Short answer: Not that often
Long answer. Main benefit for non relational databases are high availability, schemaless and scalability. All of of this comes with significant price. If your application needs query flexibility (and / or, sort order, ..) and doest have large data or performance requirements you're better off with traditional DB like mysql or better postgres. Main challenge with non-relational database is that if you need new way to combine data (like all posts liked by user in time order) you'll need new document to insert and view to implement the query. Couchdb is document based that is good for flexibility, as you don't need to maintain schema in the database and can just "forget" old data that is missing the new fields. Document databases do not live up to full potential with statically typed languages though as you anyway have to more or less fix the data structure in your code.
Non-relational db requires push architecture. All data for all possible queries ( even rare admin ones ) needs to pushed when you insert or update data. This costs as cpu and disk but you get fast queries. In SQL based db you can just insert the row and pay the price as slow queries. CouchDB builds indexes on the first query, some other databases on insert (MongoDB, Google App Engine)
Couchdb queries are defined as javascript views that are powerful but pretty difficult to write, maintain and debug. View change means that couchdb needs to reindex all documents that is really slow if you have million or more documents. The error messages from couchdb can not be deciphered by usual admin.
Couchdb maintanance needs some manual effort to compact datafiles and indexes, new versions have automatic compaction though but using it requires some care. Compactions need to be scheduled off-peaks etc.. This can scripted pretty easily though. Db dump, backup and such tools are still pretty infant.
In short, it's not worth the effort if you're not going to need the performance or scalability of the couchdb. Personally I think its possible to "emulate" most non relational db performance benefits with sql db, redis and memcache stack. At least as long as the there is not too much data.

A: Do you have a relational requirement ? CouchDb (as you know) doesn't have the relational structure of a normal database.
Is the RESTful nature of CouchDb important for what you're doing ?
Perhaps most importantly, who's going to support this going forward, and will they be capable of handling CouchDb? It's a fairly niche tool, and finding people experienced with it will not be easy.

A: It's really a case-by-case thing, I'd say. CouchDB is simply a type of database, depending on your project it might be a perfect fit or it might be painfully limiting -- just like an RDBMS can be a perfect fit or a nightmare.
More details?


text:
Q: DNS and joining domain Here is my situation. I have a 2012 Active Directory server with DNS installed on it. I also have a sonicwall nsa 240 router which i have acting as the DHCP server. On the sonic wall I set the dns entry to be the following:
primary - 172.16.0.6 (ip of the dns server)
secondary - 4.2.2.1
Everything works and I can even join the domain on client machines. however if i try and go to  sam.sightly.com which is a webserver we host my browser comes back saying that the page cannot be displayed and to check my dns settings. However regular internet browsing works
If i flip the dns entry and go:
primary - 4.2.2.1
secondary - 172.16.0.6
My issue goes away however i can no longer join the domain, and I can go to sam.sightly.com
thanks in advance.

A: What you've done is created a split-brain DNS namespace. This is bad.
First of all, let's establish a few things.

*

*You should have more than 1 Domain Controller.

*You should run DNS on at least two of your Domain Controllers.

*Active Directory clients (your internal domain-joined PCs) should only point to DCs for their DNS.
Why is this happening?
Ok, now that that's out of the way, let's talk about why you're experiencing what you are. You seem to have an internal Active Directory named sightly.com. It sounds like this is also your publicly registered web presence. Domain Controllers have SOA and NS records for the DNS zone that they hold. They are authoritative for this zone. This means that any internal client using them for DNS will assume that your DCs have all of the hosts in the sightly.com zone. If you have a public website called sightly.com that's hosted externally, you'll notice that your internal clients can't get there either unless you have a subdomain like www. configured for it. This is because your Domain Controllers register themselves as sightly.com with same as parent A records in DNS.
So, you can see that there's a problem here since you now have two sets of DNS servers that think they're authoritative for the same sightly.com zone.  You'll never be able to get to an external sightly.com without prepending something like www. unless you run a web service on each DC to redirect traffic externally (don't actually do this, it's bad). You can get to subdomains of sightly.com only if you duplicate the external DNS records on your Domain Controllers' copy of the sightly.com zone.
How can you fix it?

*

*Change your Active Directory domain name to be an unused subdomain of sightly.com. Something like internal.sightly.com or ad.sightly.com. If you've got a lot of machines joined and GPO configured, this might not be the best bet. But, by the sound of it, this isn't the case. Seriously, if it's at all possible - start over and name your AD correctly. I wrote a blog post and a Q&A about naming Active Directory. I strongly encourage you to read them before you do anything else.

*If you can't or won't rename your existing domain (I still think you should), then you'll have to make a duplicate DNS entry on your internal DNS zone for each external resource in sightly.com. So, somewhere in the cloud, you probably have a DNS host that keeps track of the DNS records for sam.sightly.com and every other external resource. You now have to keep duplicate records on your Domain Controller for all of these.

TL;DR
Maintain duplicate records on your internal DNS or rename your AD domain. If I were you, I'd rename if possible.

A: Naturally. Because your internal DNS server is authoritative for the sightly.com DNS namespace. When clients that use the internal DNS server ask for sam.sightly.com, the DNS server can't find a DNS record for that name in its sightly.com DNS zone. What you need to do is to add a DNS record in the internal sightly.com DNS zone for sam (sam.sightly.com) pointing to the external ip address of the sam.sightly.com web server.


text: Q: Why Ubuntu 22.04 is freezing on asus tuf? I have ASUS TUF (Dash F15) and installed Ubuntu 22.04 on it. Sometimes especially after a system boot, without any action it will freeze, can you help me to fix this problem?


text:
Q: How to redirect Site for specific country users? I have a same website in two different languages, with two different domains, one in English and other in Turkish.
Whenever someone accesses my website (www.example.com) I want to redirect that user to www.example.tr if he is accessing that site from TURKEY else to .com if he is accesing my website other that TURKEY
Q: How do i achieve that in asp.net?
Q: What are the options available to achieve this?
Q: Do i have to make changes to IIS or in my CODE?

A: You can use ip geolocation service like "ipstack.com" to find the location of the visitor:
ipstack.com example for the Standard Lookup Endpoint using jQuery.ajax. (First register in free Plan and get your API Access Key)
// set endpoint and your access key
var ip = '134.201.250.155'
var access_key = 'YOUR_ACCESS_KEY';

// get the API result via jQuery.ajax
$.ajax({
    url: 'https://api.ipstack.com/' + ip + '?access_key=' + access_key,
    dataType: 'jsonp',
    success: function(json) {

        // output the "capital" object inside "location"
        alert(json.location.capital);

    }
});

Now based on the answer you received, you can redirect the user to the website you want without any change in IIS.
if (countryCode == "Turkey")
  response.redirect("www.yoursite.tr");
else
  response.redirect("www.yoursite.com");


text:
Q: Can Android Application run without Android Runtime as implied in official android stack? Actually, I always believe the answer is no: an Android application must run over a separate instance of ART (like Java over JVM) to translate and take care of cross-platform needs.
However, I then feel confused about the figure of the android stack that Google puts. The way it draws seems to imply that, System Apps + Java API framework could go to the bottom through Native c/c++ libraries without Android Runtime. But I would like to argue that, if Java needs to call to native space, Android Runtime (JVM/legacy Dalvik) is still needed to interpret the source and make calls to native via JNI. Simply putting Java API Framework over Native Libraries is misleading to me.
Please comment and correct me if anything is logically incomplete or incorrect. Thanks

A: I've been doubted that it is not possible. However, If you decompile an apk to smali, you will see that smali is a more easily read java byte code. Convert smali from an apk to java source code and you have ART's java translation.
You can emulate/replace/recreate the Native/ART implementation and everything below that is self explanatory. It is linux based with hardware attributes that provide input to ART, retrieved by C++ only to be used by java producing the systems applications.


text:
Q: Why does adding content inside of a layout screw up the layout? The following layout 2 column layout will get screwed up by adding the
Hello
... Can anyone give me a clue?

Hello

I could see if the height of the "p" was actually larger than 200px, but it isn't.  So why doesn't it just go inside of its parent and stop messing with my layout?
To fix this, I ended up making the layout column divs relative, and using the absolute position on a child div that would be the container of the "p", but it seems like there is something obvious I am missing to make this situation simpler...

A: Inline-block does leave some whitespace that is undesired most of the time do to spaces in your code. The best solution I think is to float it and use 50% for the width.
div {
  float: right;
  width: 50%;
  height: 200px;
  background:blue;

}
the p tag will go in nicely.
example here on jsfiddle
other solutions and information here http://css-tricks.com/fighting-the-space-between-inline-block-elements/

A: Inline block items are vertically aligned as baseline by default. Add vertical-align:top
Jsfiddle Demo
div {
    font-size:0; /* remove whitespace */
}

div div {
    font-size:1rem; /* reset font-size*/
    vertical-align: top;
}


text:
Q: Is dual booting ubuntu and fedora/openSUSE as easy as popping in a liveCD? I wish to dual boot ubuntu (currently installed) with fedora and/or openSUSE (fedora for vanilla gnome and SUSE for a good KDE experience). I do not know much about dual booting and grub. Do I only have to put in the liveCD and install side by side? Or do I have to partition and stuff? Also, is there an easy way to remove one if I do not want it?
Please note that I do not want them on the same /home partition, I want them to have a different one each. (and also if there is a way that is mostly graphical and user friendly, it would be most appreciated)
EDIT: What if I wanted to install something like arch of mint? how would I do that?

A: You can install each system separately, by booting from their respective live/install CD's and running their installers. Whatever order you install them in, each has the ability to resize partitions created by the others to make room for itself. Alternatively you could partition manually so that dynamic partition resizing is not necessary (making sure that each OS's partitions take up little enough space that there's enough unpartitioned space left over for the subsequent OSes). Another benefit to partitioning manually is that you can make them all use the same swap partition, which would probably not happen if you installed without manual partitioning. (On the other hand, if you want to be able to hibernate one OS and boot into another, then they must have separate swap partitions.)

A: While it is (probably) possible to install two distros side by side, just by popping in CDs and following default options, but it is not a good idea to do it without spending some time thinking about partitioning your hard-drive first.
Let us take the example of installing Ubuntu and Suse together. You would typically want a /boot (< 1gb) ( primary partition) , a (primary or extended) partition (for installing ubuntu swap,/ and /home) and a similar partition for Suse. Then you may want a storage space to be used by ubuntu and suse (but separate from both).
This is one possible example (not the best I guess) and partly inspired by (http://unix.stackexchange.com/questions/6344/different-linux-distros-sharing-the-same-home-folder).
It is probably not a great idea to use same swap and /home for different (linux) distros and  careful planning (and some research) the partition initially will save a lot of pain later.


text:
Q: Discord bot hosting on Glitch.com - Node package issues I am trying to host my discord bot on glitch.com. My bot works fine if launched from my personal terminal, the issue on glitch appears to be packages/node related.
this is my package.json
    {
  "name": "mudbot",
  "version": "1.0.0",
  "description": "MUDbot",
  "main": "bot.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "discord.js": "^13.12.0",
    "env": "^0.0.2",
    "events": "^3.3.0",
    "fs": "^0.0.2",
    "i18next-node-fs-backend": "^2.1.3",
    "node": "^19.0.0",
    "node-events": "^0.0.2",
    "node-fs": "^0.1.7"
  }
}

When I run 'node bot.js' on the glitch terminal, I get this error:
Error: Cannot find module 'node:events'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
at Function.Module._load (internal/modules/cjs/loader.js:562:25)
at Module.require (internal/modules/cjs/loader.js:692:17)
at require (internal/modules/cjs/helpers.js:25:18)
at Object.<anonymous> (/rbd/pnpm-volume/d5c775c7-bd94-4b87-abee-5713ace40ae7/node_modules/discord.js/src/client/BaseClient.js:3:22)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)

I have tried 'npm i', 'npm i discord.js', 'enable-mnpm' over and over but I still get this error. I am not even sure where 'node events' is being used in my code.
EDIT: per the response below, I added "engines": { "node": "16.6.1" }
Into my package.json. Which causes this error:
    $ npm i discord.js
node: /lib/x86_64-linux-gnu/libm.so.6: version `GLIBC_2.27' not found (required by node)
node: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.25' not found (required by node)
node: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.28' not found (required by node)

To which I use 'enable-npm', which then allows me to run it, but if I try to npm anything else, it throws the same error. After 'npm i' and 'npm i discord.js', when I now run 'node .' or 'node bot.js' I get:
   $ node bot.js
-su: /app/node_modules/.bin/node: No such file or directory

A: You probably need to set the Node version you want the container to use, as Glitch's default may not be compatible with what your packages need. See https://help.glitch.com/kb/article/59-can-i-change-the-version-of-node-js-my-project-uses/ and I think setting the Node version to 16.x will stop those errors.


text:
Q: I want to know how to use BackgroundWorker so the app won't freeze I have a winform application that supposed to get data from web requests and when i hit the start button it works but for those seconds of loading it will not respond and freeze.
I am a beginner and i heard that there is the class backgroundWorker but i can't get it to work on my code without giving me an error something like "you need to use it on the thread you created with".
Here is the code of the button click:
WebClient webURL = new WebClient();
        Stream stream = webURL.OpenRead(url);
        htmlDoc.Load(stream);

        HtmlNode chartNode = htmlDoc.DocumentNode.SelectSingleNode("//*[@id='top40']");

        listBoxChart.Items.Clear();
        foreach (var item in GetChart(chartNode))
        {
            listBoxChart.Items.Add(item);
        }

Thanks for the replies!
edit:
OK. Here it is:
"Additional information: This BackgroundWorker is currently busy and cannot run multiple tasks concurrently."
Button click:
void btnGetChart_Click(object sender, EventArgs e)
    {
        listBoxChart.Items.Clear();
        listBoxChart.Items.Add("Please Wait. . .");
        listBoxChart.Items.Clear();
        backgroundWorker1.RunWorkerAsync();
    }

backGroundWorker DoWork: (There is more code of the webrequest above but thats the loop):
foreach (var item in GetChart(chartNode))
{
listBoxChart.Items.Add(item);
}

It also says this:
"Additional information: Cross-thread operation not valid: Control 'listBoxChart' accessed from a thread other than the thread it was created on."

A: The event is used to write all your code is DoWork. You can place all code in that event. Once you call the method RunWorkerAsync the DoWork event will be raised. after completing whole process, finally BackgroundWorker will raise RunWorkerCompleted event. where you can  determine the process has been completed.
there is complete example with description you can find that here


text:
Q: Why the audio is not being played while using MediaPlayer Instance? When I click the play button the song with resource Id R.raw.dance is not being played . When I am using the same way to play audio's in other app,the audios are being played . Here the audio is a bit too long than those in other app . Does that have any effect? What possible mistake I am doing here which results in no audio? How can I rectify it?
public class MainActivity extends AppCompatActivity  {
private MediaPlayer media;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        media=MediaPlayer.create(getApplicationContext(),R.raw.dance);
        Button play=(Button) findViewById(R.id.button);
        play.setOnClickListener(new View.OnClickListener(){

            public void onClick(View v){

                media.start();

            }

        });

        Button pause=(Button) findViewById(R.id.pause);
        play.setOnClickListener(new View.OnClickListener(){

            public void onClick(View v){

                media.pause();

            }

        });

    }

}


text:
Q: rails : polymorphism / abstract / inheritance : case study I'm trying to migrate my project from php to rails. Mow, I'm faced with a pb to witch I had solution with php, but I can't figure out how to make it work with rails.
Here are my tables
ads
  id
  category_id
  title
  text

ad_real_estate_details
  id
  ad_id
  nb_room
  floor

ad_car_details
  id
  ad_id
  color
  brand

Here is what I succeed to do:
class Ad < ActiveRecord::Base
  attr_accessible :category_id :title, :text, :ad_real_estate_details
  has_one :ad_real_estate_details
  accepts_nested_attributes_for :ad_real_estate_details, allow_destroy: true
end

class AdRealEstateDetail < ActiveRecord::Base
  belongs_to :ad
  validates :ad_id, presence: true
end

However, this will not work for other category than real_estate.
So I was thinking of polymorphism, but polymorphism means I should add a reference in my "ad" table to the detail tables, and remove annonce_id from detail tables , what I think is nonsense as some ads can have no detail, and details are non-sense without an ad.
I was also thinking of a abstract class AdDetails, and  AdRealEstateDetail would inherite from it, but this is not possible with rails as all subclasses will share the same table.
Does anyone have a solution for this kind of problem?
thanks

A: You're saying that you want to store different "details" depending on the ad type?
One simple solution would be to serialize the "details" as JSON (or whatever format you like), and store them in a TEXT column.


text:
Q: OkNegotiatedContentResult is taking forever to return the value I have a query that is returning over 10,000 rows of data which is, I realize, a lot of data, but it is taking over two minutes for the UI to present this information. After some debugging, it turns out the pinch point is coming after the API Controller receives the data from the business service, not during the querying process.
Controller snippet:
[HttpGet]
public IHttpActionResult GetData()
{
  try
  {
     var myList = _myService.GetData(); //this takes about 9 seconds

     if (myList.Any())
     {
        return Ok(myList); //this takes two minutes or more
     }

Within the service, the data is being mapped to a user-defined model which consists of 80+ fields (only 10 of which are actually being assigned during method execution):
public class MyModel
{
  public int Id { get; set; }
  public string Name { get; set; }
  public string Address { get; set; }
  public string Nickname { get; set; }
  ...
}

Stepping through the code reveals that the line return Ok(myList); creates a record by record loop-through of MyModel where each of those 80+ fields is put through the get/set process.
So 10,000 rows of data, each one being looped to check 80+ fields (only 10 of which have values), and now we have a process that takes two minutes, far too long for the user to sit through.
I've not worked with return Ok() before, so is there a faster way to do this? What exactly is return Ok() doing with my data?
UPDATED with GetData() Code
public IList<MyModel> GetData()
{
  IList<Person> getPersonList = _dataService.getPersonList();

  IList<MyModel> returnList = new List<MyModel>();

   foreach (var p in getPersonList)
   {
      MyModel m = new MyModel();

      m.Id = p.PersonId;
      m.Name = p.PersonName;
      m.Address = p.PersonAddress;
      etc.
      returnList.Add(m);
    }

  return returnList;
}


text:
Q: How to add Kafka connector to flink through sbt of IntelliJ? I want to add the universal connector to support Kafka 2.3 Below is by SBT configuration
// https://mvnrepository.com/artifact/org.apache.flink/flink-scala
libraryDependencies += "org.apache.flink" %% "flink-scala" % "1.9.1"

// https://mvnrepository.com/artifact/org.apache.flink/flink-streaming-scala
libraryDependencies += "org.apache.flink" %% "flink-streaming-scala" % "1.9.1"

// https://mvnrepository.com/artifact/org.apache.flink/flink-table-api-scala-bridge
libraryDependencies += "org.apache.flink" %% "flink-table-api-scala-bridge" % "1.9.1"

// https://mvnrepository.com/artifact/org.apache.flink/flink-table-planner
libraryDependencies += "org.apache.flink" %% "flink-table-planner" % "1.9.1"

// https://mvnrepository.com/artifact/org.apache.flink/flink-table-common
libraryDependencies += "org.apache.flink" % "flink-table-common" % "1.9.1"

// https://mvnrepository.com/artifact/org.apache.flink/flink-connector-kafka-base
//libraryDependencies += "org.apache.flink" %% "flink-connector-kafka_2.11" % "1.9.1" -- This not working and throwing unable to connect error.

Since I was not able to add the flink-connector-kafka via sbt, I downloaded the jar and put it in
lib(created lib) folder in my sbt project. The sbt project is created via IntelliJ and only I added the lib folder manually.
Now, when I am importing the kafka connector package i.e import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer is working fine.
Now below is my code to consume from Kafka
import java.util.Properties

import org.apache.flink.api.common.serialization.SimpleStringSchema
import org.apache.flink.streaming.api.scala.{DataStream, StreamExecutionEnvironment}
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer
import org.apache.flink.api.scala._

object KafkaFlink {

  def main(args: Array[String]): Unit = {

    val env = StreamExecutionEnvironment.getExecutionEnvironment
    val properties = new Properties()
//    properties.setProperty("bootstrap.servers", "localhost:9092")
//    // only required for Kafka 0.8
//    properties.setProperty("zookeeper.connect", "localhost:2181")
//    properties.setProperty("group.id", "test")
    val properties1 = new Properties()
    properties.setProperty("bootstrap.servers", "localhost:9092")
    properties.setProperty("group.id", "test")
    val topic = "flink-fault-testing"
    val flinkKafkaConsumer = new FlinkKafkaConsumer[String](topic, new SimpleStringSchema(), properties1)

    val value: DataStream[String] = env.addSource(flinkKafkaConsumer)
  }

}

I am unable to compile because I am getting the error
cannot resolve the overloaded method "addSource"
Please provide inputs as to where I am doing wrong.
Also if there is a way to get Universal flink-kafka connector directly via build.sbt of IntelliJ

A: What you want to specify in your SBT config is this
libraryDependencies += "org.apache.flink" %% "flink-connector-kafka" % "1.9.1"

If you leave off the "_2.11" then it should work. That's indicating which scala version to use, and SBT handles scala versioning itself.
Not sure why your code doesn't compile. Looks okay to me.


text:
Q: Insert unicode symbol into label from array I want to insert a unicode symbol for pi, which is \u03c0 into a label and for it to display the symbol. I am loading this in from an array which was read from a txt file. For example if I have a txt file that contains "\u03c0":
string = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil]
array[i] = string;
label.text = array[i];

What am getting is "\u03c0" as an output in the textfield, but I want the symbol. What I am doing wrong?
Edit: it seems that my problems is with string encoding because I am reading in the array from a file. I was using NSUTF8StringEncoding. What should this be changed to to allow unicode?

A: My guess is the contents of your file contains \\u03c0 rather than the actual character. If you have control of the file contents, paste in the actual character, not the sequence, because the editor will save it with the escaping "\". If you don't have control, i suggest writing code to detect this escaping, strip the preceding "\" and then use the result in your format.


text:
Q: Anonymous custom login with a single guid - why not? I wonder if I might ask for opinions on a simple authentication system I'm thinking about for a pet web site project where the overriding requirement is that the system should have no way to tell who the user is, i.e. have no way of identifying or contacting them.
The system does need to distinguish between these anonymous users of course, and prevent users pretending to be other users.
Perhaps in a strict sense it's not an authentication system at all, more like a distinguishing system.
A simple solution would be to assign a Guid to new users, which gets stored in a cookie/local storage/whatever and used to distinguish them.
Then give the user the facility to copy the Guid, and/or generate a URL that they can bookmark or otherwise store locally, which re-supplies the Guid to the site and stores it as a cookie again - to be used if the cookie is deleted or they want to authenticate from another machine - by using the generated URL or pasting the copied Guid into a 'login' page on the site.
This means there can be no 'I forgot my password' facility; if the user loses their credentials, they are forever lost, that's accepted.
Additionally, if the credentials are stolen, or the user's cookies are compromised, then the credential is stolen forever, there is no way for the real user to lock out the thief, that's also accepted.
Clearly the user would need to make damn sure they store this URL/Guid somewhere safe, that's accepted.
As an aside, there could be a feature that allows the user to regenerate the Guid, which might be used if they accidentally broadcast their Guid somehow, but that also means if somebody steals their Guid and uses the regenerate feature before the 'real' user realises, the real user will be locked out forever - maybe best it's unchangeable so at least if the Guid is compromised, the thief cannot lock out the real user - but this is an aside.
Given the requirement for complete anonymity / non-contactability, and accepting that losing the Guid is like losing a dollar bill, you lose it forever, it seems a reasonable and pleasantly simple solution.
This is essentially the same as having a user/password combination with no email address or other contact details, but more secure than user: sally123, password: mydogsname1968 or whatever just by virtue of it being a Guid, not something the user can remember or easily scribble on a post-it note and stick to a monitor.
It also has the advantage that a user who uses the same machine all the time (and doesn't delete cookies) never has to login or think about credentials at all.
The Guid could actually be two Guids stuck together or three of them interleaved byte by byte, whatever - a unique auto-generated chunk of data that reflects how unnecessarily paranoid the developer is feeling.
Can anyone tell me why this wouldn't be a good solution, given the anonymity/non-contactability requirements and the drawbacks accepted above, or perhaps suggest a better solution.
If it makes any difference to anything, it'll be a Net Core 5 / Blazor Web Assembly / MongoDb application, it's a pet project so doesn't have to pass muster with any client requirements or existing systems etc.
Thanks for any advice/help.


text:
Q: How to keep uncommitted changes in a local mercurial repository, while still pushing/pulling? If i'm working on some files that I don't want to commit, I just save them. I then have other files I want to push to the server, however if someone else has made changes to the repository, and I pull them down, it asks me to merge or rebase.. but either of these options will cause me to lose my local changes that I have not committed.
What are other people doing to get around this?  I find the documentation for the shelving extension hard to get my head around.
Note: I'm using Mercurial Eclipse to push and pull files to/from the server.
Any explanation of this would be greatly appreciated! Thanks!

Example:
I'm working on my website in Mercurial Eclipse. I have a new folder and new files that I don't want to commit to the server just yet. I've also modified some existing files and I don't want to make those changes live just yet.
Then something on my website breaks and I need to fix it, it won't let me fix it without rebasing or merging with the most recent tip of the repo and this will cause me to lose all my uncommitted changes.
What should I do with my new folder and files i've edited if I don't want to lose it?  Re-cloning seems tedious.  Copying the files to a new folder seems tedious as well. I'm sure Shelving or MQ will do what I want, I just don't know how to go about it yet.

A: With reference to your example situation, here's what I would do (following Ry4an's strategy to just commit the things you're currently working on, but don't want to publish already):
Supposed you start working in a repository like this one:
$ hg status -A
C f1
C f2
$ hg glog
@  changeset:   1:7f3c6c86a92f
|  tag:         tip
|  summary:     add f2
|
o  changeset:   0:03ca1e6d5b86
   summary:     initial

That is there are 2 files and 2 commits/changesets. You do some work, let's say add a new feature, and then your working copy might look like this:
$ hg status
M f2
? f3
? f4

There are 2 new and 1 modified file. Now you have to fix a bug for which you also need any new changes in a remote repository. Snapshot your current work by committing it and pull the remote changes (in which order you do that does not matter, a pull by default does not touch the state of your working copy):
$ hg commit -A -m "snapshot feature work"
$ hg pull

This may result in a history like this:
o  changeset:   3:2284ba62de07            <-- just pulled in
|  tag:         tip
|  parent:      1:7f3c6c86a92f
|  summary:     edit f1
|
| @  changeset:   2:4a19d371a04f          <-- your interrupted work
|/   summary:     snapshot feature work
|
o  changeset:   1:7f3c6c86a92f
|  summary:     add f2
|
o  changeset:   0:03ca1e6d5b86
   summary:     initial

Now you can update-to/checkout revision 3 and start fixing bugs:
$ hg update 3
.. fix the bug ..
$ hg commit -m "fix a bug"
$ hg glog --limit 3
@  changeset:   4:5d3d947fb4af
|  tag:         tip
|  summary:     fix a bug
|
o  changeset:   3:2284ba62de07
|  parent:      1:7f3c6c86a92f
|  summary:     edit f1
|
| o  changeset:   2:4a19d371a04f
|/   summary:     snapshot feature work
:

Looks good, let's push your fix, i.e. make it live, while don't publishing your intermediate work:
$ hg push -r 4

This pushes all changes leading to revision 4, your bugfix, but no other branches in your local repository. You could also use -r ., which refers to the parent revision of your working copy, i.e. the revision you just committed.
Finally you can go back to your feature work and continue your work:
$ hg update 2
.. work, commit, work, commit ..
.. finally merge with the other branch, e.g. revision 4

These steps are on the command line, but I think it's not to hard to adapt the general concept to corresponding clicks in the Eclipse Mercurial plugin.
Some extra notes:

*

*You may want to bookmark your snapshot commit, so you don't need to work with revision IDs or numbers.

*If you want to publish your feature work in a single commit later, use the collapse extension once you're done.

A: I'm sure someone will help you find a bad workaround, but the best route is to change you goals -- just commit.  Code that hasn't been committed hasn't been written.  If you positively can't abide having frequent commits in your history use Mercurial Queues with a queue repository and commit that.  You can then pop the changesets, push/pull/merge, and the push them back on, and all you valuable work will be committed in the patch queue.


text:
Q: is there a way to have a directive put an object in the injector for its controller? {
  controller: 'myController',
  templateUrl: '/templates/my-template.html',
  restrict: "E",
};

Is there any way that I can add an object in the injector so that it's available inside myController?  I know angular bootstrap does this with it's "resolve" attribute, when it news up a controller, so I would like to know if there's a way to do this here.  And yes, I realize I can make this object available to the controller by setting it on the scope property, but I would like to know if I can do this through the injector rather than scope.

A: There is a way to manually create a controller and supply dependencies with $controller, however in case of passing the object from the link function to the controller in the directive (as seems to be in your case) there is an easier way and one does not need to pollute the scope to achieve that.
All that is needed is to obtain the reference to the already instantiated controller. This is simply done with require of own controller:
.directive("foo", function(){
  return {
    require: "foo",
    controller: function($scope){
      //...
    },
    link: function(scope, element, attrs, fooCtrl){
       fooCtrl.someObj = {a: "aaa"};
    }
  }
});

Unlike the "resolved" value, this object is not available when the controller function runs. This is rarely needed though. If you need, however, to perform some initialization only when the object is available, then you can always expose a this.init = function(){...} function on the controller, and invoke it as needed.

A: You can create a service and inject it in your controller. Let's say the service is called "myObject", you can then define your controller as:
controller: function($scope, myObj) {
  // myObj is accessible in the controller
}


text:
Q: Emacs grep-find on selection It is quite common that when I use grep-find in emacs I want to search for the text I have selected. My current workaround to this is to select the text, then M-x grep-find and paste the selection. How do I make a keybinding that does this automatically?

A: Here's a modified grep-find - if the region is active, search of region
contents. It seems to work on my system:
(defun grep-find (command-args)
  "Run grep via find, with user-specified args COMMAND-ARGS.
Collect output in a buffer.
While find runs asynchronously, you can use the \\[next-error] command
to find the text that grep hits refer to.

This command uses a special history list for its arguments, so you can
easily repeat a find command."
  (interactive
   (progn
     (grep-compute-defaults)
     (if grep-find-command
         (list
          (read-shell-command
           "Run find (like this): "
           (if (region-active-p)
               (let ((str
                      (buffer-substring-no-properties
                       (region-beginning)
                       (region-end))))
                 (cons (replace-regexp-in-string
                        " {}"
                        (concat str " {}")
                        (car grep-find-command))
                       (+ (cdr grep-find-command)
                          (length str))))
             grep-find-command) 'grep-find-history))
       ;; No default was set
       (read-string
        "compile.el: No `grep-find-command' command available. Press RET.")
       (list nil))))
  (when command-args
    (let ((null-device nil))
      (grep command-args))))


text:
Q: Dice roll in C♯ I'm deigning a windows program that allows the user to pick a dice and then show possible outcomes if rolled.
At this point, I can only get possibler outcomes out of 50 no matter what dice is selected. I believe it has to do with an issue in the public RollDice() but cannot be sure.
I am using two classes called FormDice.cs and RollDice.cs
Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace
{
public partial class FormDice : Form
{
    public FormDice()
    {
        InitializeComponent();
        sixRadioButton.Checked = true;

    }
    //declare variables
    int sides;
    int answer;

    //assign clear button
    private void clearButton_Click(object sender, EventArgs e)
    {

        twoRadioButton.Checked = false;
        sixRadioButton.Checked = true;
        tenRadioButton.Checked = false;
        fiftyRadioButton.Checked = false;

    }

    //assign event to roll button
    private void rollButton_Click(object sender, EventArgs e)
    {

        //if statements check which number checked
        if (twoRadioButton.Checked)
        {

            sides = 2;
            RollDice rolldice = new RollDice();
            answer = rolldice.Roll();
        }
        else if (sixRadioButton.Checked)
        {

            sides = 6;
            RollDice rolldice = new RollDice();
            answer = rolldice.Roll();
        }

        else if (tenRadioButton.Checked)
        {

            sides = 10;
            RollDice rolldice = new RollDice();
            answer = rolldice.Roll();
        }

        else if (fiftyRadioButton.Checked)
        {

            sides = 50;
            RollDice rolldice = new RollDice();
            answer = rolldice.Roll();
        }

        else
        {

            RollDice rolldice = new RollDice();
            answer = rolldice.Roll();

        }
        resultsListBox.Items.Add(answer.ToString());
    }

    //exit program
    private void exitToolStripMenuItem_Click(object sender, EventArgs e)
    {
        Application.Exit();
    }
    //about message box
    private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
    {
      MessageBox.Show("Dice Magic Version 1.0\nProgrammer: PaulPresutto",            `enter code here`"Dice Magic", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }

    private void twoRadioButton_CheckedChanged(object sender, EventArgs e)
    {

    }

And my RollDice.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace
{
class RollDice
{
    //variables
    private numberOfSides;
    private Random randomNumberGenerator = new Random();

    public RollDice()
    {

        numberOfSides = 6;
        numberOfSides = 2;
        numberOfSides = 10;
        numberOfSides = 50;

    }

    //constructor
    public RollDice(int sides)
    {
        numberOfSides = sides;
    }

    public int Roll()
    {
        return randomNumberGenerator.Next(1, numberOfSides + 1);

    }

}
}

    private void resultsListBox_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

}
}

A: Change all these in the first code snippet:
sides = 10;
RollDice rolldice = new RollDice();

To call your overloaded ctor that accepts a "sides" value:
sides = 10;
RollDice rolldice = new RollDice(sides);

Since the default ctor overwrites the same variable multiple times, the value of numberOfSides is always 50.
public RollDice()
{
    numberOfSides = 6;
    numberOfSides = 2;
    numberOfSides = 10;
    numberOfSides = 50;  // last value wins out - you'll want to fix this
}

A: You're assigning the number of sides to 6, then 2, then 10, then 50 in your RollDice constructor. So it always ends up being 50.
You already have a constructor that lets you pass in the number of sides. Try using it. For example:
else if (fiftyRadioButton.Checked)
{
    RollDice rolldice = new RollDice(50);
}


text:
Q: Calculating a Grade in a Class Assume that a class has four categories for calculating grades - tests, final exams, projects, and homework.  Assume that tests are $40\%$ of the class grade, final exams are $30\%$ of the class grade, projects are $10\%$ of the class grade, and homework is $20\%$ of the class grade.
Should we multiply each score for each category by its category weights, add these results, then divide by the sum of the weights?  For example: Let's say a students scores are
Tests: $84, 78, 84, 72$
Final exam:  $78$ (just one score)
Projects:  $86$ (just one score)
Homework:  $87$ (just one score)
Should the class grade be
$0.4\cdot 84 + 0.4\cdot 78 + 0.4\cdot 84 + 0.4\cdot 72 + 0.3\cdot 78 + 0.1\cdot 86 + 0.2\cdot 87 = 176.6$ (sum of products)
$0.4 + 0.4 + 0.4 + 0.4 + 0.3 + 0.1 + 0.2 = 2.2$ (sum of the weights for assignments)
Total grade:  $176.6 / 2.2 = 80.27$
Or is there a different approach that should be used to calculate the grade for the course?
Thank you in advance.


text:
Q: Android SDK, Placeing widgets/buttons etc at will? Hey Im new to android developing and I have a quick question. Is there a way to place buttons where I want them on the view? Right now they only seem to be placed where there is specific spots for them. Why cant i drag and place them where ever I want like in the iphone sdk for example?
Is there a way to do so or does this functionality not exist? thanks.

A: Android (eg. similar to Qt) uses a concept of layouts. This is especially useful when you're creating UIs that can be displayed on different devices with different DPIs, different screen resolutions, etc.
So instead placing your buttons at pixel coordinates you put them, independent of device screen resolution, into layouts.
Read more in User Interface documentation. Using Eclipse ADT plugin you can visually create layouts. You can even embed one layout into other, creating eg. LinearLayout in RelativeLayout. This gives much more possibilities of creating screen scalable applications (one app on phone and tablet for example).

A: There is AbsoluteLayout, but that class is deprecated. The recommended strategy is to use a RelativeLayout (you can control the position of views by setting layout margins) or build your own custom layout class.

A: An android UI screen is build for various screen sizes , due to which you can not specify an exact location for the UI component .
Android instead uses the concepts of Layouts where each layout has a different behavior. Here are a few of them.

*

*LinearLayout aligns all children in a single direction — vertically or horizontally, depending on how you define the orientation attribute

*TableLayout positions its children into rows and columns

*RelativeLayout , one of the most used layouts , lets child views specify their position relative to the parent view or to each other (specified by ID).

A: A UI element's position is determined by the layout you choose. See this link.

A: Android uses layouts to design the UI. For example, a vertical linear layout stacks one element on top of the other.
AbsoluteLayout is the most precise, but it's also harder to maintain and can get messy.
I recommend RelativeLayout. It positions UI elements relative to other elements.
If you don't really need that much precision, one more option is nesting layouts within layouts. But doing that too much gets messy and RelativeLayout becomes the better option.


text:
Q: OpenCV - Making a video from existing images I have an array of numpy array images named images. Let's say for the discussion's sake that -
images = [cv2.imread("data/frame" + str(i) + ".jpg") for i in range(15)]

Where data is a directory with frames from a video.
I then try to save them as a video, using the following code:
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
shape = images[0].shape[:2]
vid = cv2.VideoWriter("my_vid.avi", fourcc, 1, shape)
for fg_frame in images:
    vid.write(np.uint8(fg_frame))
vid.release()

But the video that is saved is only 5-6 KB in size and plays nothing. What am I doing wrong?

A: The reason is that the constructor of cv2.VideoWriter takes video size in the 4th argument which is expected to be a tuple of the form (width, height).
The shape member of numpy array stores dimensions as (height, width).
Due to dimension mismatch between VideoWriter and the actual image, no frames are written to the disk.
You have to swap the elements of shape when passing as an argument to VideoWriter. The correct code may look like this:
shape = images[0].shape[:2]
video_size = (shape[1], shape[0])
vid = cv2.VideoWriter("my_vid.avi", fourcc, 1, video_size)

Verified and tested on Ubuntu 14.04 with Python 3 and OpenCV 3.4.


text:
Q: TypeError: unhashable type: 'set' in dropdown plotly python The following code works by itself but I have a "TypeError: unhashable type: 'set'" when it's in my plotly graph. Can you help me out with this ? I never worked with set or frozenset.
Thanks a lot !
code that works be itself :
updatemenus = []
for n, ecole in enumerate(liste_ecole):
  visible = [False]*len(liste_ecole)
  visible[n] = True
  temp_dict = dict(label = str(liste_ecole),
                     method = 'update',
                     args = [{"visible" : visible,
                             {"title"} : "Prévisions des effectifs pour {}".format(liste_ecole)}])
updatemenus.append(temp_dict)

code inside my plotly graph :
fig = go.Figure([
    go.Scatter(
        name='Effectif réel',
        x=df2['date_str'],
        y=df2['reel'],
        mode='markers+lines',
        marker=dict(color="#1e3d59"),
        line=dict(width=1),
        showlegend=True,
        text=df2['jour']
    ),
    go.Scatter(
        name='Prévision algorithme',
        x=df2['date_str'],
        y=df2['output'],
        mode='markers+lines',
        marker=dict(color="#ff6e40", size=4),
        line=dict(width=2),
        showlegend=True,
        text=df2['jour']
    )
])
fig.layout.plot_bgcolor = '#f5f0e1'

updatemenus = []
for n, ecole in enumerate(liste_ecole):
  visible = [False]*len(liste_ecole)
  visible[n] = True
  temp_dict = dict(label = str(liste_ecole),
                     method = 'update',
                     args = [{"visible" : visible,
                             {"title"} : "Prévisions des effectifs pour {}".format(liste_ecole)}]) **#THIS IS WHERE I GOT MY ERROR**
updatemenus.append(temp_dict)

fig.update_layout(
    updatemenus=list([dict(buttons= list_updatemenus)]),
    yaxis_title="Nombre de convives",
    hovermode="x",

    direction="down",
    pad={"r": 10, "t": 10},
    showactive=True,
    x=1.02,
    xanchor="left",
    y=0.75,
    yanchor="top"
    )

fig.update_xaxes(tickformat='%d-%b-%Y')
fig.update_xaxes(rangeslider_visible=True)

fig.show()

A: This error has nothing to do with Plotly. You can't have a set (literal)
as a key in a dict because a set isn't hashable.
In [1]: {
   ...:     "visible" : ...,
   ...:     {"title"} : "Prévisions des effectifs pour {}".format(...)
   ...: }
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-1-24fea1201dd1> in <module>
      1 {
      2     "visible" : ...,
----> 3     {"title"} : "Prévisions des effectifs pour {}".format(...)
      4 }

TypeError: unhashable type: 'set'

In [2]: type({"title"})
Out[2]: set

And you don't need a set there, so just replace {"title"} with "title" (a hashable str).


text:
Q: Firebase - prevent bot mass signup I have a website as well as a hybrid app relying on Firebase to handle everything. On the register process, there is currently nothing preventing a bot from registering infinite user accounts with a simple loop.

*

*Does Firebase has a security system to prevent mass registration from the same IP, for example?

*Is there a way to secure this more?

A: The limits are documented, among other things:

New account creation - 100 accounts/IP address/hour
  Account deletion - 10 accounts/second

You don't have any way to further limit the system.


text:
Q: Error Message need to display in email body in Batchable Apex Job I'm trying to display the error messages of each record in the email body of the Batchable Apex.
Am I correct on iterating errorMessages into String and call it in execute method then display it in emailbody? Please help!
global class LRN_ResetSabaHoursBatchable implements Database.Batchable<sObject>, Database.Stateful {

public Set<Id> contactRecordFailures = new set<Id>();
public boolean isSuccess = true;
public List<String> errorMessages = new List<String>();

global Database.QueryLocator start(Database.BatchableContext bc) {
    return Database.getQueryLocator(
        //COLLECT THE BATCHES OF RECORDS TO BE PASSED TO EXECUTE
        'SELECT Id, SABA_Hours__c, Non_SABA_Hours__c FROM Contact WHERE Non_SABA_Hours__c != NULL'
    );
}
global void execute(Database.BatchableContext bc, List<Contact> scope){
    List<Contact> contToUpdate = new List<Contact>();
    for(Contact contact : scope){
        contact.SABA_Hours__c = 0;
        contact.Non_SABA_Hours__c = 0;
        contToUpdate.add(contact);
    }

    List<Database.SaveResult> updateResults = Database.update(contToUpdate, false);
    for (integer i = 0; i<updateResults.size();i++ ){
        if(!updateResults[i].isSuccess()){
            errorMessages.add(updateResults[i].getErrors()[0].getMessage());
            contactRecordFailures.add(updateResults[i].Id);
            isSuccess = false;
        }
    }

}

  global void finish(Database.BatchableContext bc){
      if(!isSuccess){
          Id job = bc.getJobId();
          AsyncApexJob aaj = [SELECT Id, Status,ExtendedStatus,NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email FROM AsyncApexJob where Id =:BC.getJobId()];
          Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
          String[] toAddresses = new String[] {aaj.CreatedBy.Email};
          mail.setToAddresses(toAddresses);
          mail.setSubject('Failed to Reset Saba Hours');
          mail.setPlainTextBody(aaj.Id + aaj.CreatedBy.Name + errorMessages);
          Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
      }
   }
}

A: you are almost there, you just need to make a few changes on your finish method:
  global void finish(Database.BatchableContext bc){
      // check if you got any errors during the execution (no need of extra boolean variable, you can get rid of it)
      if(!errorMessages.isEmpty()){
          Id job = bc.getJobId();
          AsyncApexJob aaj = [SELECT Id, Status,ExtendedStatus,NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email FROM AsyncApexJob where Id =:BC.getJobId()];
          Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
          String[] toAddresses = new String[] {aaj.CreatedBy.Email};
          mail.setToAddresses(toAddresses);
          mail.setSubject('Failed to Reset Saba Hours');
          // get string with all your errors
          String errorsBody = String.join(errorMessages, ',');
          // format the string as needed, and then
          // use String variable instead of the list one
          mail.setPlainTextBody(aaj.Id + aaj.CreatedBy.Name + errorsBody);
          Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
      }
   }

EDIT: you also need to iterate over all errors on your execute method:
// Iterate through each returned result
for (Database.SaveResult sr : updateResults) {
    if (!sr.isSuccess()) {
        // Operation failed, so get all errors
        for(Database.Error err : sr.getErrors()) {
            errorMessages.add(err.getStatusCode() + ': ' + err.getMessage());
        }
    }

you can read more about here
Hope this helps!


text:
Q: Я хочу чтобы бот запомнил одно значение, другое, а потом сравнил их import telebot
import random

bot = telebot.TeleBot('token')

@bot.message_handler(commands=['roll'])
def roll(messsage):
    zxc = str(random.randrange(100))
    bot.reply_to(message, zxc)

bot.polling()

Даже в голову не приходит, как сделать что-то подобное

A: Пороробуйте после токена объявить к примеру список data = []
В него можно будет помещать и возвращать значения когда это потребуеться из под любой ф-ции.


text:
Q: iOS Swift - Instagram API get response from WebView NSURL Request I am using the following block allow users of my app to authorize with Instagram:
func authorizeInstagram() {

        let myWebView:UIWebView = UIWebView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height))
        myWebView.delegate = self
        myWebView.loadRequest(NSURLRequest(URL: NSURL(string: "https://instagram.com/oauth/authorize/?client_id=xxxxxxxxxxxxxxxxxx&redirect_uri=xxxxxxxxxxx/&response_type=token")!))
        self.view.addSubview(myWebView)
 }

My question is, how can I get the reponse JSON from the webview NSURL request once user has completed auth?

A: in delegate method you can get the request and find it's URL.absoluteString,what code you want will be in the string :
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {

    let str = request.URL?.absoluteString
    print(str)
    return true
}

hope it be helpful :D

A: In the info.plist file you register the app under URL Types. Put the identifier as your bundle id, the URL Scheme as your redirect, and editor as the role.
When the user is done completing the auth in the app delegate will called back in the method:
func application(application: UIApplication,
  openURL url: NSURL,
  sourceApplication: String?,
  annotation: AnyObject?) -> Bool

Inside that you can parse through the response. Here an example in C#, don't have it in swift but shouldn't be to hard to translate. Hope that helps!
if (url.Scheme == "youappscheme")
{
    var queryParams = url.Query.Split('&');
    // grab the one you want
    return true;
}


text:
Q: How to pass endValue to horizontal annotation in chart.js? I am drawing a line chart with chart.js and I can't figure out how to pass endValue to the horizontal annotation.
I've tried passing any possible value and even changing axis but it doesn't work.
annotation: {
    drawTime: 'afterDatasetsDraw',
    annotations: [{
       type: 'line',
       mode: 'horizontal',
       scaleID: 'y-axis-0',
       value: 0.5,
       endValue: 1,
       borderColor: 'green',
       borderWidth: 4
    },

As you can see the line starts at value 0.5 and I want to go only till the next label.
Any help is incredibly helpfull.


text:
Q: iterating from 0 to 100 and printing the sum of all evens and the sum of all odds as array I am trying to iterate from 0 to 100 and trying to print the sum of even numbers and odd numbers as array, like this [2550, 2500].
let m=0;

for(let i=0;i<=100;i++) {
  m = m + i;
}

console.log(Array.from(String(m)));

but this code is returning  ['2', '5', '0', '0']
Can anyone please show me how can I print both the sums as array?
Also if someone could help me with the code for putting this code into other conditional statement so that I can get both, the sum of odd numbers and sum of even numbers. I am facing issue deciding which one to use here, else if, if else....

A: You just need to check the reminder of the number(i), if it's zero then it is even else it's odd.
let m=0,k=0;
for(let i=0;i<=100;i++)
{
if(i%2==0)m+=i
    else k+=i;
}

then console.log([m,k]);

A: Your code is calculating the sum of all the numbers in the range of 0-100.
m will have the sum of range(0-100) that is 5050.
for(let i=0;i<=100;i++) {
  m = m + i;
}

This line will split the digits of variable m and make an array of it.
console.log(Array.from(String(m)));

['5','0','5','0']

You can have two variables for even_sum and odd_sum and then check if i is odd then add it to odd_sum else add it to even_sum.
let even_sum=0;
let odd_sum=0;

for(let i=0;i<=100;i++) {
    if (i%2==0)
        even_sum+=i;
    else
        odd_sum+=i;
}

To return the values as array, you can do -
console.log([even_sum,odd_sum])

A: As you tagged the question with math I think the mathematics of triangular numbers should be mentioned here:

function sumOddEven(n) {
    const floor = Math.floor(n / 2);
    const ceil = Math.ceil(n / 2);
    return [ceil * ceil, floor * (1 + floor)];
}

console.log(sumOddEven(100))

Without function:

const n = 100; // Example
const floor = Math.floor(n / 2);
const ceil = Math.ceil(n / 2);
const arr = [ceil * ceil, floor * (1 + floor)];
console.log(arr)

A: Use an array to sum each parity individually.

m=[0,0];
for (i=0;i<101;i++)
m[i%2]+=i;
console.log(m);


text:
Q: Directory.GetFiles() returning deleted/phantom file over network I have a process, completely separate from the process calling GetFiles(), that takes the file Big.xml and breaks it down into little_1.xml, little_2.xml... etc.
Once it has finished a separate app gets the files:
string[] files = Directory.GetFiles(dir, *.xml);

In the 'files' list is the Big.xml file as well as all the little_x.xml files.
Even File.Exists("Big.xml") returns true, it doesn't error until opening Big.xml is attempted.
Is this likely to be a network issue, Directory.GetFiles() is static so presumably nothing is cached here, the code all looks good - has anyone experienced this before?


text:
Q: How to show the image by the the image name in Xcode 5 I want to see the image when I click on it is name, while i press command button :
[UIImage imageNamed:@"Background.png"]

but I get "symbol not found"... How can I do that?
edit:
this what Xcode show me when I press on "@"Background.png" ...

A: Are you command-clicking on @"Background.png"? That will not work in the current version of Xcode. It can't take you to the source image - Command-clicking works only for symbols such as variables and classes. It's a good idea for a feature, though, so you should probably file a feedback. However, you may want to look at the KSImageNamed-Xcode plugin, which you can install via Alcatraz.


text:
Q: Django Rest Framework custom ListSerializer only returning dictionary keys, not values I am using a custom ListSerializer to reformat a JSON response and it generates the proper format when I log from inside the serializer, but when it is returned to the ViewSet, the response becomes a list of the dictionary keys rather than including the entire dictionary with both keys and values.
I have made a simplified example of the problem with hard-coded JSON to illustrate what I believe to be the crux of the issue.
views.py
class ElementViewSet(viewsets.ViewSet):

    ...

    @detail_route(methods=['get'])
    def elements(self, request, pk=None):
        elements = ElementFilterSet(params)
        serializer = serializers.ElementSerializer(elements, many=True)
        return Response(serializer.data)

serializers.py
class ElementListSerializer(serializers.ListSerializer):

    def to_representation(self, obj):
        result = {"home": {"label_color": "#123456","label_text": "young"},"speak": { "label_color": "","label_text": "Hello"}}
        return result

class ElementSerializer(serializers.ModelSerializer):
    class Meta:
        model = Element
        list_serializer_class = ElementListSerializer

    def to_representation(self, obj):
        result = super(ElementSerializer, self).to_representation(obj)
        return result

The response I get is a list of dictionary keys:
[
    "speak",
    "home"
]

rather than what I want, which is the entire dictionary (in this case, simply the hard-coded JSON result):
{
   "home": {
       "label_color": "#123456",
       "label_text": "young"
   },
   "speak": {
       "label_color": "",
       "label_text": "Hello"
   }
}

I am new to customizing serializers and using list_serializer_class; I likely simply don't understand how they work, but this behavior does seem unexpected to me.

A: According to docs definition: The ListSerializer class provides the behavior for serializing and validating multiple objects at once.
You don't typically need ListSerializers, if the data you pass could be represented as serializer data.
Suggested solution is to use nested serializers, if you dont get the key values from a model instance:
class ElementListSerializer(serializers.BaseSerializer):

    def to_representation(self, obj):
        return {
            'home': {"label_color": "#123456",
                     "label_text": "young"},
            'speak': {
                    "label_color": "",
                    "label_text": "Hello"}
        }

class ElementSerializer(serializers.ModelSerializer):

    element_list = ElementListSerializer()

    class Meta:
        model = Element

    def create(self, validated_data):
        data = validated_data.pop('element_list')
        return data

A: The problem is in property data on ListSerializer which returns ReturnList instead of ReturnDict.
To fix your code, you have to change data property:
from rest_framework import serializers

class ElementListSerializer(serializers.ListSerializer):

    def to_representation(self, obj):
        result = {"home": {"label_color": "#123456","label_text": "young"},"speak": { "label_color": "","label_text": "Hello"}}
        return result

    @property
    def data(self):
        ret = serializers.BaseSerializer.data.fget(self)
        return serializers.ReturnDict(ret, serializer=self)

class ElementSerializer(serializers.ModelSerializer):
    class Meta:
        model = Element
        list_serializer_class = ElementListSerializer

    def to_representation(self, obj):
        result = super(ElementSerializer, self).to_representation(obj)
        return result

You can also create a more generic solution. It will automatically convert list of dicts with same structure to one dict where keys will be from specified field from child's dict.
class ListToDictSerializer(serializers.ListSerializer):
    def to_representation(self, data):
        return {
            item[self.child.Meta.dict_serializer_key]: self.child.to_representation(item)
            for item in data
        }

    @property
    def data(self):
        ret = drf_serializers.BaseSerializer.data.fget(self)
        return serializers.ReturnDict(ret, serializer=self)

class MyModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Model
        list_serializer_class = ListToDictSerializer
        dict_serializer_key = 'id'


text:
Q: How can I apply multiple TextDecorations? All the examples I've seen for setting Underline, Overline, or Strikethrough all look something like this:
// setting underline
textRange.ApplyPropertyValue(Inline.TextDecorationsProperty,
                             TextDecorations.Underline);

// clearing underline
textRange.ApplyPropertyValue(Inline.TextDecorationsProperty, null );

This seems overly simplistic to me; the TextDecorationsProperty returns a collection of decorations - you can have Overline, Underline and Strikethrough all applied at the same time; setting them like this wipes out the entire collection.
This is what I have for toggling them by TextDecorationLocation:
var textRange = new TextRange(tb.Selection.Start, tb.Selection.End);
var tdp = textRange.GetPropertyValue(Inline.TextDecorationsProperty);
var textDecorations = tdp.Equals(DependencyProperty.UnsetValue)
                      ? new TextDecorationCollection()
                      : tdp as TextDecorationCollection
                        ?? new TextDecorationCollection();

var strikethroughs = textDecorations.Where(d => d.Location == TextDecorationLocation.Strikethrough)
                                    .ToList();
if (strikethroughs.Any())
{
   foreach (var strike in strikethroughs)
   {
      textDecorations.Remove(strike);
   }
}
else
{
   textDecorations.Add(TextDecorations.Strikethrough);
}

textRange.ApplyPropertyValue(Inline.TextDecorationsProperty, textDecorations);

Is this a good way to go about this, or am I making it overly complicated?

A: If you are trying to toggle decorations on and off whilst allowing them to be combined you could do the following:
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <StackPanel Grid.Row="0" Orientation="Horizontal">
        <Button Content="Underline" Click="Underline" />
        <Button Content="Strikethrough"  Click="Strikethrough" />
        <Button Content="Baseline" Click="Baseline" />
        <Button Content="Overline"  Click="Overline" />
    </StackPanel>
    <RichTextBox x:Name="tb" Grid.Row="1" />
</Grid>

and then in the code
        private void Underline(object sender, RoutedEventArgs e)
    {
        this.SetDecorations(new TextRange(this.tb.Selection.Start, this.tb.Selection.End), TextDecorations.Underline);
    }

    private void Strikethrough(object sender, RoutedEventArgs e)
    {
        this.SetDecorations(new TextRange(this.tb.Selection.Start, this.tb.Selection.End), TextDecorations.Strikethrough);
    }

    private void Baseline(object sender, RoutedEventArgs e)
    {
        this.SetDecorations(new TextRange(this.tb.Selection.Start, this.tb.Selection.End), TextDecorations.Baseline);
    }

    private void Overline(object sender, RoutedEventArgs e)
    {
        this.SetDecorations(new TextRange(this.tb.Selection.Start, this.tb.Selection.End), TextDecorations.OverLine);
    }

    private void SetDecorations(TextRange textRange, TextDecorationCollection decoration)
    {
        var decorations = textRange.GetPropertyValue(Inline.TextDecorationsProperty) as TextDecorationCollection
                          ?? new TextDecorationCollection();

        decorations = decorations.Contains(decoration.First())
                          ? new TextDecorationCollection(decorations.Except(decoration))
                          : new TextDecorationCollection(decorations.Union(decoration));

        textRange.ApplyPropertyValue(Inline.TextDecorationsProperty, decorations);
    }

This code uses the existing decoration set and then either unions or set excepts the current decoration based on whether it is already attached - allowing the decoration to be toggled on/off.


text:
Q: getInitialProps doesn't render on client side I'm trying to fetch data from my API server to use in my page, but I need SSR for SEO purposes.
So what I want here is:
Server Side Rendering: When a search engine visits a page.
Client Side Rendering: When user navigates different pages.
It should be noted that I use next/link for all of my links like so:
<Link href="/products/1/slug-goes-here">
    Product A
</Link

I have tried following methods (NOT AT THE SAME TIME) but either way, they just request the API server only on server side and never on client side.
Note: It takes way too long to respond, at least 15 seconds.
MyPage.getInitialProps = async (context) => {
    const data = (await getData({ id: context.query.id })).data;

    return { data };
}

// OR

export const getServerSideProps = async (context) => {
    const data = (await getData({ id: context.query.id })).data;

    return { props: data };
}

A: I just updated next from 12.0.4 to 13.1.2 and the first thing that happened was Internal Server Error caused by using  inside next/link.
So I removed  from every <Link> in my App and now everything works as expected.
It should be noted that in version 13.1.2 there is no need to use  inside <Link> to make the link visible to search engines.


text:
Q: How to check if user is logged in and display the user name I want to check if the user is currently logged in. If the current user is logged in I wanna display hello with a user name. How can I do that!?

A: {% if currentUser %}
{{ currentUser.friendlyName }}
     {% endif %}


text:
Q: Bit value process in Spark & Postgresql When I try write Spark SQL with bit(), it result in an error.
Code
val tpos_dfr = sqlContext.sql("SELECT idcustomer, quantity, CASE WHEN quantity < 0 THEN 1::bit(1) ELSE 0::bit(1) END as isthisreturn FROM pointofsale WHERE iddataloadmanager = 10 and quantity <> 0")

Error

Exception in thread "main" org.apache.spark.sql.catalyst.parser.ParseException:
  extraneous input 'quantity' expecting {, ',', 'FROM', 'WHERE', GROUP', 'ORDER', 'HAVING', 'LIMIT', 'LATERAL', 'WINDOW', 'UNION', 'EXCEPT', 'INTERSECT', 'SORT', 'CLUSTER', 'DISTRIBUTE'}(line 1, pos 122)

A: You could use a boolean expression, and use the resulting boolean value instead of a bit, so try
SELECT
    idcustomer,
    quantity,
    quantity < 0 as isthisreturn
  FROM
    pointofsale
  WHERE
    iddataloadmanager = 10 and quantity <> 0

then a boolean data type should appear, if you call printSchema() on the data frame.


text:
Q: IPTables - Allow only traffic from specific ranges I am trying to block all traffic to a webserver except from some defined subnets. I've checked numerous posts and believed I had iptables set correctly but for some reason the site is still accessible outside the subnets i've defined in the ruleset. Is anyone able to shed some light on what I may have done wrong? I've established that removing rule 3 stops the site from being reachable at all. The site itself sits in 10.10.0.0/16.
Chain INPUT (policy DROP 0 packets, 0 bytes)
num   pkts bytes target     prot opt in     out     source               destination
1        0     0 ACCEPT     all  --  any    any     10.10.0.0/16         anywhere
2        0     0 ACCEPT     all  --  any    any     172.30.0.0/16        anywhere
3        0     0 ACCEPT     all  --  lo     any     anywhere             anywhere

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
num   pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
num   pkts bytes target     prot opt in     out     source               destination
1        0     0 ACCEPT     all  --  any    lo      anywhere             anywhere

The goal will be to add various whitelisted public IPs and lockdown the site so that it is only accessible to some.
Rules were added as follows:
iptables -I INPUT -i lo -j ACCEPT
iptables -I OUTPUT -o lo -j ACCEPT
iptables -I INPUT -s 10.10.0.0/16 -j ACCEPT
iptables -I INPUT -s 172.30.0.0/16 -j ACCEPT
iptables -P INPUT DROP

A: The rule order matters in iptables. By using iptables -A you are appending rules at the end of the ruleset. But iptables -I inserts a rule on top of the ruleset, unless you specify a line number (you haven't). As a result rules are not evaluated in the intended order.
Here is a sample configuration that should work, based on this post. Flush your rules before to avoid duplication.
iptables -P FORWARD DROP
iptables -A INPUT -m state --state INVALID -j DROP
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -s 10.10.0.0/16 -j ACCEPT
iptables -A INPUT -s 172.30.0.0/16 -j ACCEPT
# add some more whitelisting rules here
iptables -P INPUT DROP # Drop everything we don't accept

The third rule is important:
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT

otherwise your server will not get replies to the connections that it initiated, take for example DNS requests.
On a side note, iptables works for IPv4 but not IPv6, so if your server is IPv6-enabled you may have clients connecting using IPv6. This is possible if they are connecting by hostname instead of IP address, and that the hostname resolves to a valid IPv6 address on your server. You'd probably be aware though, but many people are still not aware that iptables does filter IPv6 traffic (and attacks).
I would then also add similar ip6tables rules if appropriate for your setup.


text:
Q: the_excerpt() in content.php and get_template_part() in single.php everybody. So I'm creating a blog theme and have put the_excerpt() in content.php
My index.php displays different post excerpts for the different kind of posts-formats. I have content-gallery.php, content-audio.php, etc and in each of them I have the_excerpt() instead of the_content(). If I put the_content() and there is a lot of text before the read-more tag, it breaks the layout, because the design is made for little snippets for each post.
Does that mean that I can't use get_template_part( 'content', get_post_format() ) in single.php, because it will return an excerpt and not the whole content?
In the content.php, I could put:
if( is_singular() ) {
    the_content();
}

Or create subpages of single.php like single-gallery.php.
What is the correct way of arranging the hierarchy when using the_excerpt() in content-{post-type}.php?

A: the_content() does not grab the PHP file content.php, it simply displays a Post's content. Likewise, the_excerpt() grabs the excerpt of a post.
get_template_part simply finds a file within your theme named whatever you put in, with an optional suffix.
get_template_part( 'content' ); // content.php
get_template_part( 'content', 'my_page' ); // content-my_page.php

in order for make different displays for Gallery, Aside, etc. do this in single.php
get_template_part( 'content', get_post_format() );

It will point to content-gallery.php, content-aside.php, etc. with a fallback of content.php if the file specified is not defined.
Edit:
All you need to do here is restructure your content-{post-format}.php files. Inside those, use the_content(), and create excerpt-{post-format}.php files where you can then use the_excerpt().
Then your call in index.php would be get_template_part( 'excerpt', get_post_format() ), where inside your single.php it would be get_template_part( 'content', get_post_format() )


text:
Q: C++98, but clang-tidy says use nullptr? I am using Clion and my project is set to C++98, but clang-tidy has suggestions to use nullptr instead of NULL.
Is there a clang-tidy setting somewhere in the IDE or is it something else?

A: I don't know CLion specifically but that message is related to the modernize-use-nullptr check which is intended for upgrading old code to use C++11 features. (in this case avoiding inadvertently using the NULL macro in assignment to non-pointer variables since it expands to 0)
Disable that check if you want to keep your code in C++98.


text:
Q: std::shared_ptr deep copy object Can't find much on that for C++11 but only on boost.
Consider the following class:
class State
{
   std::shared_ptr<Graph> _graph;

 public:

    State( const State & state )
    {
        // This is assignment, and thus points to same object
        this->_graph = std::make_shared<Graph>( state._graph );

        // Deep copy state._graph to this->_graph ?
        this->_graph = std::shared_ptr<Graph>( new Graph( *( state._graph.get() ) ) );

        // Or use make_shared?
        this->_graph = std::make_shared<Graph>( Graph( *( state._graph.get() ) ) );
    }
};

Suppose class Graph does have a copy constructor:
Graph( const Graph & graph )

I do not want to have this->_graph point/share the same object!
Instead, I want this->_graph to deep copy the object from state._graph, into my own this->_graph duplicate.
Is the way above the correct way of going about this?
Documentation of std::make_shared notes that:

Moreover, f(shared_ptr(new int(42)), g()) can lead to memory leak
  if g throws an exception. This problem doesn't exist if make_shared is
  used.

Is there another way of going about this, safer or more reliable?

A: If you want to make a copy of the Graph object when you make a copy of the object, you can always define your copy constructor and assignment operator to do just that:
State::State(const State& rhs) : _graph(std::make_shared(*rhs._graph)) {
   // Handled by initializer list
}
State::State(State&& rhs) : _graph(std::move(rhs._graph)) {
   // Handled by initializer list
}
State& State::operator= (State rhs) {
    std::swap(*this, rhs);
    return *this;
}

Hope this helps!


text:
Q: After restoring a backup of my SQL db to Azure, all of my indexes are disabled I was experiencing terrible performance after restoring a .BACPAC to Azure. I finally checked my indexes in sys.indexes and they all have is_disabled = 1. My coworker restored the same .BACPAC and did not have this issue. I have a couple questions:

*

*What could have caused this?

*Is it safe to simply enable them? Or might they be disabled for a reason (like being disabled while being rebuilt)?

The only schema changes I made to the db since restoring it were adding a column to an unrelated table and adding a new index to a table which previously did not have an index (this index is the only one still enabled). Thanks!


text:
Q: Объединение строк DataGrid Как можно сделать такую таблицу?

Пробовал так:
    <DataGrid ItemsSource="{Binding Employees}" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Header="ФИО" Width="150" Binding="{Binding Name}"/>
            <DataGridTemplateColumn Header="Организация" Width="*">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <DataGrid ItemsSource="{Binding }" HeadersVisibility="None" Margin="-2" AutoGenerateColumns="False">

                        </DataGrid>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>

Но столкнулся с проблемой привязки данных во вложенной таблице.

A: У DataGrid, как впрочем и у любого ItemsControl, все элементы автоматически привязываются к элементы коллекции. Поэтому, если хотите такую вложенность, то создавайте коллекцию из ViewModel, где будут лежать другие коллекции.
public ObservavbleCollection<SubVM> Employees;

Это коллекция, к которой байндится основная DataGrid,после этого у элемента DataGrid значение DataContext становится автоматом равным SubVM. Остаётся лишь в нем создать ещё одни коллекции.
class SubVM
{
   public string Name { get; set; } // На него байндится первый столбец с ФИО
   public ObservableCollection<string> Org { get; set; } // Коллекция названий организаций.
   public ObservableCollection<int> Time { get; set; }  //Коллекция времени работы
}

После этого у вложенной таблицы организаций ItemsSource="{Binding Org}"
UPD:
Значит вы что-то делаете не так. Вот мой код, основанный на вашем, в XAML.
<DataGrid ItemsSource="{Binding}" AutoGenerateColumns="False">
      <DataGrid.Columns>
          <DataGridTextColumn Header="ФИО" Width="150" Binding="{Binding Name}"/>

          <DataGridTemplateColumn Header="Организация" Width="*">
              <DataGridTemplateColumn.CellTemplate>
                  <DataTemplate>
                      <DataGrid ItemsSource="{Binding Org}" Margin="-2" AutoGenerateColumns="False" HeadersVisibility="None" CanUserAddRows="False">
                          <DataGrid.Columns>
                              <DataGridTextColumn Width="*" Header="Org" Binding="{Binding}"/>
                          </DataGrid.Columns>
                      </DataGrid>
                  </DataTemplate>
              </DataGridTemplateColumn.CellTemplate>
          </DataGridTemplateColumn>

          <DataGridTemplateColumn Header="Время" Width="*">
              <DataGridTemplateColumn.CellTemplate>
                  <DataTemplate>
                      <DataGrid ItemsSource="{Binding Time}" Margin="-2" AutoGenerateColumns="False" HeadersVisibility="None" CanUserAddRows="False">
                          <DataGrid.Columns>
                              <DataGridTextColumn Width="*" Header="Time" Binding="{Binding}"/>
                          </DataGrid.Columns>
                      </DataGrid>
                  </DataTemplate>
              </DataGridTemplateColumn.CellTemplate>
          </DataGridTemplateColumn>
      </DataGrid.Columns>
  </DataGrid>

Для теста я в конструкторе MainWindow после InitializeComponent() добавляю в коллекцию пару элементов и напрямую выставляю DataContext у окна.
SubVM subVM = new SubVM();
subVM.Name = "111";
subVM.Org.Add("Org1");
subVM.Org.Add("Org2");
subVM.Time.Add(3);
subVM.Time.Add(4);

Employees.Add(subVM);

subVM = new SubVM();
subVM.Name = "222";
subVM.Org.Add("Org2");
subVM.Org.Add("Org3");
subVM.Time.Add(5);
subVM.Time.Add(6);

Employees.Add(subVM);

DataContext = Employees;

Получилось вот так:


text:
Q: Outlook JS Add-in: EWS Calls using Ajax and Callback Token The Office JS API has a 1 Mb limit on callbacks, and one of the requirements I have is to forward an existing email, designated as spam by the user, as an attachment to a 3rd party. I have extensive code to handle mail operations, using makeEwsRequestAsync, and for this case SOAP that works fine to return the MIME content to create and send the email, but not when the callback return is larger than 1 Mb.
To get around the 1 Mb limitation, it was suggested to others to make the EWS call directly, using a callback token, an item Id, and the EWS URL. I can easily get these components, and I have SOAP that works for the usual makeEwsRequestAsync method.
What I don't have is how to make the call to EWS call with the elements I have.
As an example, I used the following to get the EWS URL and item Id:
    _mailbox = Office.context.mailbox;
    _ewsUrl = _mailbox.ewsUrl;

    var item = _mailbox.item;
    _itemId = item.itemId;

I use this to get the callback token:
    mailViaEws.Authenticate = function Start() {
        getCallbackToken(setCallbackToken);
    };

    function getCallbackToken(callback) {
        var options = {
            isRest: false
        };
        Office.context.mailbox.getCallbackTokenAsync(options, callback);
    }

    function setCallbackToken(asyncResult) {
        if (asyncResult.status === "succeeded") {
            _callbackToken = asyncResult.value;
        } else {
            app.showNotification(_appName, asyncResult.error.message);
        }
    }

The SOAP is as follows, with a helper method to wrap the SOAP:
        var soapToCreateItem =
            '<soap:Body>' +
            '   <m:CreateItem MessageDisposition="SendAndSaveCopy"' +
            '       xmlns="http://schemas.microsoft.com/exchange/services/2006/messages" ' +
            '       xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">' +
            '       <m:Items>' +
            '        <t:Message>' +
            '           <t:Subject>' + _subject + '</t:Subject>' +
            '           <t:Body BodyType="Text">' + _bodyText + '</t:Body>' +
            '           <t:ToRecipients>' + _adddressesSoap + '</t:ToRecipients>' +
            '        </t:Message>' +
            '       </m:Items>' +
            '    </m:CreateItem>' +
            '  </soap:Body>';

        var soapToCreateItemData = getSoapBoadyEnvelope(soapToCreateItem);

I've search extensively, and although I've found code that use an intermediate service to call the EWS Managed API in C#, I am trying to make the call directly to EWS. Any help would be greatly appreciated.

A: Your Mailbox (_mailbox = Office.context.mailbox;) object has a method makeEwsRequestAsync that you can use to make SOAP call to the EWS.
Note, that you don't need to provide access token explicitly.
Here is more information.

A: The Callback token you get from getCallbackTokenAsync is only good for 5 minutes and is only good for the GetAttachment and GetItem EWS operations this is documented in https://learn.microsoft.com/en-us/office/dev/add-ins/reference/objectmodel/requirement-set-1.5/office.context.mailbox so your CreateItem request won't work in this context. Does the message need to come from the user if it just SPAM reporting? it would be easy just to do the send part using a Service Account with EWS or even just send it via SMTP.


text:
Q: How clean old segments from compacted log in Kafka 0.8.2 I know that in new Kafka versions we have new retention policy option - compaction of log which delete old version of messages with same keys. But after long time we will get too many compacted log segments with old messages. How can we clean this compacted log automatically?
UDPATE:
I should clarify that we need compact log and way to clean up old messages this in those time.
I found discussion for same problem here http://grokbase.com/t/kafka/users/14bv6gaz0t/kafka-0-8-2-log-cleaner
but not found how we can manually issue thomstone markers for message and have not any idea this.

A: This question is quite old, but I thought I'd give the latest update on the matter. There is a feature (https://issues.apache.org/jira/browse/KAFKA-4015) which is already resolved and is scheduled for the 0.10.1.0 release.

A: The only other way to lower the size of your Kafka Log would be through the log retention configuration settings.
log.retention.{ms,minutes,hours}
log.retention.bytes

Also note that if both log.retention.hours and log.retention.bytes are both set we delete a segment when either limit is exceeded.

Those two dictate when logs are deleted in Kafka. The log.retention.bytes defaults to -1, and I'm pretty sure leaving it to -1 allows only the time config to solely determine when a log gets deleted.
Log retention and compaction work separately from each other. Using retention, logs can be deleted after a certain time or size even with log compaction on. So if you theoretically have a 100Mb log limit, and set the your log.retention.bytes=104857600 (100Mb). Kafka will compact your log until it reaches 100Mb in size, and then will delete the necessary messages (oldest first) until the log is under 100Mb in size.
EDIT:
It turns out that log retention and compaction are mutually exclusive based on this link provided by mechanikos. Though it seems odd that Kafka is designed so a log will grow indefinitely with no capability of ever deleting old log messages.


text:
Q: Shared info.plist between several targets using GCC preprocessor macros for maintaining specific fields In many of my apps I have 3 different build configurations (debug, release, sandbox). One experiences this is needed needed when working with different environments and in app purchase.
Often there are only small changes like CFBundleIdentifier. Is it possible to use GCC preprocessor macros for keeping the variation within different build configurations and at the same time only use one plist?

A: For simple changes it is often not even necessary to use the C preprocessor. In these cases it is often sufficient to define a custom build setting and use the value of this setting in the Info.plist file. Build settings are expanded in Info.plist by default.
Example:
In Xcode in the project view select "Build Settings" and use the + button to add a "User-Defined Setting". Name the setting for example MY_BUNDLE_IDENTIFIER and type a value, for example MyApp.agens.no.
The open the Info.plist file, select the "Bundle identifier" key and set its value to ${MY_BUNDLE_IDENTIFIER}.
If you change the MY_BUNDLE_IDENTIFIER build setting in another configuration or target, the product will be built using the new bundle identifier.