text:
Q: Is it possible to identify what magnet has crossed over a hall effect sensor? We are currently doing a project with DCC locomotives, involving a micro controller LPC1768.
Now the scenario is that we have a railway and under the railway we have hall effect sensors which the locomotives crosses over. Since we will have two different locomotives running on the track, is it possible to identify which one is currently crossing a particular sensor, since the trains do have their specific addresses in an address byte would it be possible to measure how the magnet(one magnet is in the form of a cylinder and one of a cube, and we are assuming they should affect the voltage or current differently) on each train affects the hall sensor. Another solution we have already thought of is to run the trains and measure where they are based on the magnets it has crossed. But for a nicer implementation a solution like the one ask for would be far easier to implement.

A: Look at RFID tags. They can be microscopically small (and lightweight). And cost only a few pennies for guaranteed unique identification. You could  put a tag in each piece of rolling stock and use inexpensive sensor kit(s) to monitor/record/control the complete makeup of trains.
Ref: http://www.pcrnmra.org/pcr/clinics/RFID-in-Model-Railroading-20130123.pdf

A: Its possible assuming a few things: That the magnets are different (your question wasn't quite clear on that). That your hall effect sensor can pick up the change in magnetic field with out saturation and with sufficient sensitivity.
If the magnets have different field strengths then you could differentiate the magnets by the difference in voltage from the sensor (assuming its not saturation, the voltage output of the sensor is proportional to the magnetic field strength). You could detect the voltage difference with a voltage discrimination circuit built from comparators
If the magnets are like a 'barcode' (like your post might suggest) then it would be more complex. The solution wouldn't be easy to implement, because you would have to monitor the voltage from the hall effect sensor and sample fast enough with an analog to digital converter to see the magnet go by, you would have to develop an algorithm to do this.

A: Single magnets, no.
However, you might try something like placing a pair of magnets in line, with sufficient spacing that a double magnet would produce a double pulse.

A: You need three magnets. Mount one of them under the fist locomotive. Place the other two under the second one at some small distance from each other.
Now count how many magnets were sensed in 2 seconds after sensing the first one. If 0 - it's a locomotive 0. If one - the other one.
If you need more locomotives use more magnets and also use different distances between  them.

A: You are getting into the overall problem of occupancy detection.  There are no easy answers.  Some solutions are:
*

*Light detection. IR or visible light detectors are put under the track in various places.  Either some ambient illumination is assumed, or IR LEDs are put overhead.  Rolling stock on the track is detected by the shadow it casts.
This has the advantage of working with any rolling stock without modification, but is susceptible to noise, changes in ambient illumination, and has problems with steady state levelling.  Accumulated dirt is a never-ending problem. It also only measures occupancy at specific points.

*Current sensing.  This measures the current draw from different sections of track.  Some friends of mine are into model railroading, and I designed them a advanced DCC current sensor.  It worked so well that I even made a product out of it.
Advantages are that it senses whole sections of track regardless of where the rolling stock is.  Problems are that unpowered cars aren't sensed unless you put deliberate resistors across wheel sets.  10 kΩ is sufficient for the OC1.

*Magnetic sensing.  This is probably the least popular from what I can tell.
It doesn't have the problem of adjusting to the ambient level as light detection does, but not all cars have a sufficiently large magnetic signature.  It also requires more circuitry at each point, and is point-based like the light method.

All these methods as usually employed only tell you something is there, not what is there.  The most common method I've seen to know what is where is to track it in clever software.  As long as the software initially knows what's where, it can track it as it moves between sensed segments or points.  There is a module in JMRI that already does this, and I've seen it work.
You could theoretically have each locomotive pulse a magnet with a unique ID, then detect that with the Hall sensors.  However, if I wanted to do that I'd probably use IR pointing down with sensors below the track.  That makes both the transmission and detection circuitry simpler.
With good software tracking, you only need occasional identification.  I'd look into a combination of the two to keep track of where things are.


text:
Q: 1.13 - Checking if player holds item with specific name Let's say that I want to teleport a player who doesn't hold a name tag called "abc" to X Y Z.
All I could come up with was [/data get entity @p SelectedItem.tag.display.Name] and I'm stuck here because I don't know how to compare such data (that is, if it's possible).

A: you would definitely want to work with the /execute command. i myself am having issues working this out considering the weird text formatting they have since converting things that normally would be simple strings into JSON with 1.13, but the gist of it is this;
execute if entity @a[nbt={SelectedItem:{id:"<id>",display{Name:<a bunch of JSON formatting, size varies based on the item you want}}] run tp @a X Y Z

redpajama_set_name: RedPajamaStackExchange


text:
Q: mod_rewrite redirect specific .asp pages back to original server I  need to redirect traffic for a section of a redeveloped site back to the original site with apache mod_rewrite rules. I need to redirect all requests starting with http://www.example.com/page.asp back to the original site http://www.original.com/page.asp with the query string or anything following page.asp intact.
This seems simple enough, however I have had no luck with mod_rewrite generators or documentation on the web. My latest stab at the problem looks like this:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^http://www.example.com$ [NC]
RewriteRule ^page\.asp(.*)$ http://www.original.com/page\.asp$1 [R=301,NC]

I appreciate any insight into correcting this mod_rewrite rule. Other redirects are working fine.

A: I was able to get the rewrite to function properly using:
RewriteRule ^/page(.+)  http://www.original.com/page$1 [R=301,NC,L]

I found this apache doc helpful: Resource Moved to Another Server


text:
Q: Adding new folders to pub directory and accessing? I have added a folder in the pub directory
installdir/myfolder
I placed a pdf in the folder
installdir/myfolder/myfile.pdf
When I try accessing the file via a link Magento states that the file cannot be found or that it is "Not Allowed"
What is the correct method of accessing this file?

A:
What is the correct method of accessing this file?

You can try to give full permissions.
chmod -Rf 777 /var/www/magento207/myfolder/

I have tried it and i able to access PDF.
Hope this helps.


text:
Q: Is comparing version number strings in the format 3.3.0 safe with a less than conditional? I have a version number in a string variable that I have been using to compare if a version is less than it and running some code to amend data, like this:
$version = '3.3.0';

if( $version < '3.1.0' ) {
    echo 'less than 3.1.0'; // my code to amend data would go here
}

if( $version < '3.2.0' ) {
    echo 'less than 3.2.0'; // my code to amend data would go here
}

Is this safe? Is there any scenario where a particular version number in this format would trigger older conditions unexpectedly?


text:
Q: Can't install libapache2-mod-php5 When I try to install libapache2-mod-php5, I get an error:
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help resolve the situation:

The following packages have unmet dependencies:
 libapache2-mod-php5 : Depends: apache2-mpm-prefork (> 2.0.52) but it is not going to be installed or
                                apache2-mpm-itk but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

I have tried apt-get clean,
update and upgrade, as well as -f install, and no change.
Is there a way to fix this, or is there an easy way to manually install the php plugin?

A: How did you install apache - From the repository or from Apache's website, or compiled?
Normally, it would install apache2-mpm-prefork for the traditional non-threaded model; apache2-mpm-itk is the multiuser MPM.  Both can be installed from the repository, and the prefork is normally installed with the apache2 metapackage.  It seems like reinstalling apache2 should do it, or simply installing the missing package directly, although if you're missing one, you may be missing others.
Manually installing the php plugin it is not a solution - it depends on one of these packages, so would not be expected to run correctly without it.  That's what a dependency is.

A: Are you on on a system that has moved to php7?
check out this answer if yes:
Can't install php5 on Ubuntu 16.04


text:
Q: Do we need to use load balancer for traffic rangining from 30000 to 60000? My team has just launched an iphone application with the server backend. The architecture is something like this; user interacts with the iphone app and the iphone app sends the request to the server. server performs some calculation on the request and sends back the response. the server is involved in each interaction of the user. There is no caching has been done on the server, neither there is any session handling..
My question is that, do we need to configure a load balancer for such type of application, if the active user of the application is ranging from 30,000 to 50,000? currently the cloud server has been used and the database and apache server are on the same machine. the size of the cloud server is 2GB. Will it be sufficient if the cloud server has been re-sized from 2GB to something greater 10GB or 15GB instead of using the load balancer?
Another question is that if there are any good tools available for ubuntu which could help in montioring the memory, request/response of the server?
Thanks

A: There are at least two reasons you might need a load balancer:

*

*One web server cannot handle all of the traffic

*You cannot tolerate an outage if one web server fails

You can (and should) answer the first question by performing a load test.  Have a look at the Apache JMeter project for a great load testing tool.
If you cannot tolerate an outage, you need at least two web servers behind a load balancer that can individually handle all of the traffic (or if you have, say, 3 web servers, each should be able to handle about 60% of peak traffic to void the risk of losing a single web server).
Regarding monitoring, you really should ask separate questions separately.  I personally use Zabbix for monitoring.  It is open source (not "crippled community" and "enterprise" like some solutions).  The learning curve is slightly steep (and some things changed with the recent 2.0 rollout that are not well documented) but overall it is a solid solution.  Nagios is also very popular and worth having a look at.


text:
Q: identify new line in regex I would like to perform some regex on the text from MAcbeth
My text is as follows:
Scena Secunda.

Alarum within. Enter King Malcome, Donalbaine, Lenox, with
attendants,
meeting a bleeding Captaine.

  King. What bloody man is that? he can report,
As seemeth by his plight, of the Reuolt
The newest state

My intention is to get the text from Enter to the full-stop.
I am trying this regular expression Enter(.?)*\.
But it is showing no matches. Can anybody fix my regexp?
I am trying it out in this link

A: Since @Tushar has not explained the issue you had with your regex, I decided to explain it.
Your regex - Enter(.?)*\. - matches a word Enter (literally), then optionally matches any character except a newline 0 or more times, as many as possible, up to the last period.
The problem is that your string contains a newline between the Enter and the period. You'd need a regex pattern to match newlines, too. To force . to match newline symbols, you may use DOTALL mode. However, it won't get you the expected result as the * quantifier is greedy (will return the longest possible substring).
So, to get the substring from Enter till the closest period, you can use
Enter([^.]*)

See this regex demo. If you need no capture group, remove it.
And an IDEONE demo:
import re
p = re.compile(r'Enter([^.]*)')
test_str = "Scena Secunda.\n\nAlarum within. Enter King Malcome, Donalbaine, Lenox, with\nattendants,\nmeeting a bleeding Captaine.\n\n  King. What bloody man is that? he can report,\nAs seemeth by his plight, of the Reuolt\nThe newest state"
print(p.findall(test_str)) # if you need the capture group text, or
# print(p.search(test_str).group()) # to get the whole first match, or
# print(re.findall(r'Enter[^.]*', test_str)) # to return all substrings from Enter till the next period


text:
Q: amcharts 4 cursor and mouse positioning not correct I have an angular 7 app that I am working on and don't have any issues with the chart.cursor on any other chart series except LineChart (using grouping). There seems to be an odd gap between the location of mouse and the cursor/data point it is snapping to. The gap seems to be at the bottom and right of the mouse.
The further to the right/bottom of the chart I move, the larger the gap gets, and vice versa, top/left it gets smaller. I cannot replicate this in codepen, but noticed that the data point is not aligned with the dataAxis the more I zoom in.
Is there a way to handle these gaps, or be able to use just the mouse position to interact with the chart without using a cursor? Also, just in case this is useful, it is displayed within a MatDialog.

A: Within the ngAfterViewInit and giving it a small timeout, seemed to correct the issue. I am guessing that the timing of loading the chart within the dialog loading had an offset of where the mouse was when each item was loading and the difference was the gap.


text:
Q: Header position offset not following top margin of container Here I have a header with position: fixed. As it does not go with the normal flow of the window, a margin for the body is set to the height of the header (here 100px). Now, the body starts right after the bottom of the header.
The main div in the body has a margin-top of 50px. But, the header grasps that margin, and it's not shown. If I set a border on the body, then the margin is shown. I don't know what is the relation of that top margin with the border of the body.
This can be solved if I add 50px more to the margin-top of the main div. But I want to know what's happening here.

body {
  background-color: white;
  margin-top: 100px;
  /* border: 1px solid black;  */
}

header {
  background-color: black;
  height: 100px;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  right: 0;
}

main {
  background-color: gray;
  margin-top: 50px;
  width: 100%;
  height: 100vh;
}

A: Adding a border adjusts the display of the layout because the  and the  margins overlap without the border (since it's just whitespace), but with the border rendered, the two margins must be separate. Thus, without the border, the total margin is 100px, and with the border, the total margin is 150px.
See demo below. (I've also added a button to hide the  since it's position is fixed, so it isn't relevant to the situation.

const body = document.querySelector("body");
const header = document.querySelector("header");

const a = document.createElement("div");
const b1 = document.createElement("button");
b1.textContent = "Toggle body border";
b1.addEventListener("click", () => {
  if (body.style.border !== "1px solid red") {
    body.style.border = "1px solid red";
  } else {
    body.style.border = "none";
  }
});
const b2 = document.createElement("button");
b2.textContent = "Toggle body margin";
b2.addEventListener("click", () => {
  if (body.style.marginTop !== "0px") {
    body.style.marginTop = "0px";
  } else {
    body.style.marginTop = "100px";
  }
});
const b3 = document.createElement("button");
b3.textContent = "Toggle header visibility";
b3.addEventListener("click", () => {
  if (header.style.display !== "none") {
    header.style.display = "none";
  } else {
    header.style.display = "block";
  }
});
a.appendChild(b1);
a.appendChild(b2);
a.appendChild(b3);
a.style.position = "fixed";
a.style.top = "0";
a.style.zIndex = "2";

document.body.appendChild(a);
body {
  background-color: white;
  margin-top: 100px;
}

header {
  background-color: black;
  height: 100px;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  right: 0;
}

main {
  background-color: gray;
  margin-top: 50px;
  width: 100%;
  height: 100vh;
}


text:
Q: Zoom on jqplot not working , also unable to plot data points I am using jqplot for plotting a graph .Below is the code :
    $.jqplot.config.enablePlugins = true;
    // For these examples, don't show the to image button.
    $.jqplot._noToImageButton = true;

    var ticks = ["8/25/2008","1/22/2009","6/20/2009","7/20/2009","10/20/2009","6/20/2010","2/20/2011"] ;

  goog = [[56, 60, 79,20,34,67]];

  var plot1 = $.jqplot(id, goog, {
      title: title,
      series: [{
          label: series,
          neighborThreshold: -1
      }],

       axesDefaults: {
          tickRenderer: $.jqplot.CanvasAxisTickRenderer ,
          tickOptions:{
            angle: -30,
            fontSize: '10pt'

          }
      },

      seriesDefaults: {
          showMarker:true,
          pointLabels: { show:false }
        },

      axes: {
          xaxis: {
              renderer: $.jqplot.DateAxisRenderer,
              min:'Sun Aug 24 16:00:00 2008',
              max:'Sun Jan 21,16:00:00 2009',
              numberTicks: 7,
             // tickInterval: '4 months',
             ticks : ticks,

              tickOptions:{formatString:'%#c'},

          },
          yaxis: {
              tickOptions:{formatString:'%.2f'}
          }
      },
      cursor:{
        show: true,
        zoom:true,
        showTooltip:true
      }
  });

  $('.button-reset').click(function() { plot1.resetZoom() });

These are the issues that I am facing

*

*The data points are not plotted , so I get a blank graph .

*On zooming , only Y-Axis changes and X-axis remains the same .

*CanvasAxisTickRenderer is not working so I dont get ticks with specified angle.

*min and max for Xaxis is also not working , the graph itself plots the ticks taking the first and the last value in ticks array.
I am new to jquery so please dont mind for a such long question, any help is highly appreciated .
Thanks in advance.

A: Your data aren't well declared, you need to specify an array of [x,y] values fr each point. Your goog variables became :
goog = [[["8/25/2008",56], ["1/22/2009",60], ["6/20/2009",79],["7/20/2009",20],["10/20/2009",34],["6/20/2010",67],["2/20/2011",42]]];
PS : I have also added a new value in goog in order to have 7 points as 7 ticks.

A: It's not zooming on the x-axis because you have specified the "ticks" option on the x-axis. I'm having the same issue. Seems to me this is a bug.  It should work as expected even when I set the ticks (as an initial "un-zoomed" value).


text:
Q: SUID not working? On Ubuntu 16.04.1:
test.sh script:
#!/bin/bash

IAM=$(whoami)
ID=$(id -u $IAM)
echo "${IAM}"
echo "${ID}"

Andromeda $ ls -al | grep test.sh
-rwsrwxrwx  1 pkaramol pkaramol        71 Δεκ   8 07:52 test.sh

As pkaramol (uid=1000)
Andromeda $ ./test.sh
pkaramol
1000

As testuser (uid=1001)
Andromeda $ su testuser
Password:
testuser@Andromeda:/home/pkaramol/Desktop$ ./test.sh
testuser
1001

Given that the suid has been set, why, in the second run, do we not see pkaramol and 1000 in the output? Isn't the script supposed to be executed with the file owner's id?

A: From man 2 execve, section NOTES:
Linux ignores the set-user-ID and set-group-ID bits on scripts.

Also see:

*

*Allow setuid on shell scripts


text:
Q: Opening a JAR resource as a FileStream I have a project where I want to access a resource in a JAR from another project.  It's not on my classpath, so ClassLoader is not an option.  I tried:

new FileInputStream("C:\\mydir\\my.jar!\\myresource.txt");

and received a FileNotFoundException.
JarInputStream might be a possibility, but I want the flexibility of the input filename being a jar resource or just a file on the system (user decides).  Is there a class that can do this or do I have to build one myself?

A: URLs are your friend
URL.openStream.

A: Fortunately, the desicion with the "!" symbol doesn't work.
Have a look here:
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4730642

A: Try using a URLClassLoader. I've done something similar to this before, and it seems to work (though you may need to muck around with your security policy file, if you're in a secure JVM).

A: try using java.net.JarURLConnection
URL url = new URL("jar:file:C:\mydir\my.jar!\myresource.txt");
JarURLConnection jarConnection = (JarURLConnection)url.openConnection();

A:   private InputStream twistLid(File jar, String resource) throws IOException {
    return new URL("jar:" + jar.toURI() + "!" + resource).openStream();
  }

A: Building on the work of many above, here's an example in groovy, listing the text contained in 'resource.txt' inside a folder named 'reources' at the root level of a jar file
import java.io.*
import java.util.*
import java.util.jar.*

def getJarResourceAsStream(String jarName, String resource) throws IOException {
    def resourceStr = 'jar:' + (new File(jarName)).toURI() + '!' + resource
    return new URL(resourceStr).openStream()
}

def inputStream = getJarResourceAsStream('/some/file/path/myJar.jar', '/resources/resource.txt')

def reader = new InputStreamReader(inputStream)
BufferedReader buffer = new BufferedReader(reader)
String line
while((line = buffer.readLine()) != null) {
    System.out.println(line)
}


text:
Q: Issue with wording of Bounty Notification: The bounty on your question "xyz" expires in the next day I've got a bounty that's about to expire, and SO told me that I had 3 days left on Monday.
Now, it tells me that: "The bounty on your question "xyz" expires in the next day."
This makes no sense grammatically. It should read
The bounty on your question "xyz" expires tomorrow.

A: OK, to fix this critically important and potentially life threatening bug, I changed it to "in the next 24 hours".

A: Actually in the next 24 hours / next day does sound right.

A: I second Josh's suggestion and maybe add that giving number of days and hours left might be better.
e.g. The bounty on your question expires in 1 day and 23 hours and definitely give number of hours left if it's <1 day, plus the meaning of tomorrow depends on the timezone.


text:
Q: Spacing in a table I'm trying to setup a table in html. Below is a screenshot of part of it.

As you can see, there is a horizontal white strip between the image and the cell below, which I cannot get rid of. I have tried the following (bit ott I know - but I'm getting right frustrated!)

            Text

This is based on what I've got - just more simple. Any ideas on how I can get rid of that gap?

A: Add
vertical-align: top;

to the element style of the image. That's because the image is treated as text and so line-height and font-size also take effect.


text:
Q: Snowflake|Airflow|Google Cloud : How to unload data from snowflake tables in csv format and upload to gcs using airflow Is there any way to unload data from Snowflake to csv format or can it be directly stored in csv format in google cloud storage?
We are using composer(airflow) dags to connect to snowflake and unload data from tables into csv files and store them in google cloud storage and later on migrating it further.
What I have tried :
Querying data from snowflake table and getting it in a variable.
What I want to do further:
To convert the data into csv file(as have not run the code yet) and to migrate it to GCS bucket but seems like there is only GCStoGCSoperator in airflow which cannot help in this.
What I am thinking:

*

*If I should use python file with scheduler instead of writing in DAG.

*Doing it through dataflow(beam) and running it on composer.

Code:-
def func(**context):
    dwh_hook = SnowflakeHook(snowflake_conn_id="snowflake_conn")
    result = dwh_hook.get_first("select col1,col2,col3,col4,col5 from table_name where col_name = previous_date_func_here")
    # print(result)

I have not yet tested it as I want to test it with GCS but seems like its not gonna work. What could be the ways?
Is it actually even possible with airflow to do this ?

A: Snowflake supports data unloading using COPY INTO location command:

Unloads data from a table (or query) into one or more files in one of the following locations:

*

*Named internal stage (or table/user stage). The files can then be downloaded from the stage/location using the GET command.

*Named external stage that references an external location (Amazon S3, Google Cloud Storage, or Microsoft Azure).

*External location (Amazon S3, Google Cloud Storage, or Microsoft Azure).

Format Type Options (formatTypeOptions)

*

*TYPE = CSV

*TYPE = JSON

*TYPE = PARQUET

Unloading Data from a Table Directly to Files in an External Location

Google Cloud Storage
Access the referenced GCS bucket using a referenced storage integration named myint:
COPY INTO 'gcs://mybucket/unload/'
FROM mytable
STORAGE_INTEGRATION = myint
FILE_FORMAT = (FORMAT_NAME = my_csv_format);

Related: Configuring an Integration for Google Cloud Storage


text:
Q: Can the "friend" relationship be transferred among C++'s class? suppose class A is the friend of class B, and B is friend of class C, is A the friend of C or C the friend of A, or both, or none ?

A: No, friendship in C++ is not transitive.
From the C++03 standard, 11.4-8:

Friendship is neither inherited nor transitive. Example:

class A {
  friend class B;
  int a;
};

class B {
  friend class C;
};

class C {
  void f(A* p)
  {
    p->a++;
    // error: C is not a friend of A
    // despite being a friend of a friend
  }
};

class D : public B {
  void f(A* p)
  {
    p->a++;
    // error: D is not a friend of A
    // despite being derived from a friend
  }
};

A: None. See the C++FAQ:

Friendship isn't inherited, transitive, or reciprocal

A: C++ class friendship does not propagate in this way, so A class wouldn't be a friend of C class. It's like on Facebook, if one of your friends makes friends with someone, that person doesn't become your friend automatically =)


text:
Q: CCnet devenv.exe error I'm using cruise control .net and visual studio 2005's devenv.exe from the command line in a deployment task...but it's hanging up in devenv.exe immediately after a successful build, but before the rest of the cc process continues.  This whole process was working for over  a year, until I checked in a new web config today that merely included a new arbitrary constant for use in the rest of the program.  Reverging the web config did no good (because, well, why would it?).  I've tried simple fixes such as ending the process tree on devenv.exe on the build server and restarting the build server, all with no success.  Specifically, I'm getting a timeout error.  Doubling the time before timeout did not help at all.  It seems that devenv is hanging up the cc tasks from advancing.  Any suggestions?

A: Just a suggestion, is it possible that you're using some third-party library for which license expired?
I came across such situation once, then it popped-up with some window, which was blocking the whole process.
Have you tried to both run it manually without ccnet and then through ccnet console? Using the same user account that the ccnet normally runs on.


text:
Q: Command only working when put directly in command prompt, not in batch file On my SBS 2011 I have a batch file called wakeup-nas.bat, with the following contents:
wol.exe 5475e0d59ffa

wol.exe is an executable for sending wake on lan packets. It is in the same directory as the batch file.
Strangely the command is only working when I write it directly in the command prompt. When I open the batch file nothing happens, although I see the output from wol.exe that the packet has successfully been sent.
I also have tried to open the batch file "as administrator" with no success either.

A: Try putting the full path to wol.exe. Also try putting an echo statement on your batch file. That might help.

A: Hmmm. I don't really know why, but it's working now with the batch file too, even without "run as administrator".
May have something to do with the network card drivers I updated yesterday.


text:
Q: Recovering OpenOffice files from corrupted OS I tried to upgrade to Ubuntu 13.10 yesterday, and my laptop promptly froze and wouldn't respond to anything other than the power button. When I turned it back on, Ubuntu failed to work period. I can get control of the mouse, but it's just a blank screen, nothing to click on, no keyboard commands are working.
Now, I'm not too worried about this -- a reinstall will probably fix that.  The issue is that I have a brace of about twenty OpenOffice files that would make my boss very grumpy if I lost. Is there any way to recover them?
I've made a boot disk using a USB drive, but even when I boot from the flash drive, I can't see the files that need rescuing.  Is there some way to recover them? Please explain it in simple language for an inexperienced Linux user.

A: If you have a 13.10 Live USB, you should be able to boot from it and do a repair install. During the installation process, if you select this, it will reinstall Ubuntu but keep all your original files that were in the home folder.
If you open the file manager while in a Live USB session, you should see your Ubuntu installation in the shortcut panel on the left. The users' files are in the home folder.
Also, if you have everything backed up to some place like Ubuntu One, it should be no trouble to restore the files.


text:
Q: my jQuery hover code is repeating on hovers Right now I have a problem and I don't know how I can solve it.
The problem is that if I hover the .div multiple times the animation just doesn't stop, but keeps going.
What I want is that the .hidden doesn't continue to fadeIn or fadeOut, if you hover it once or ten times it will only fadeIn or fadeOut once and not as many times as you've actually hovered the .div.
My current code is:

title

hey would you show me

title

hey would you show me

and JavaScript:
$(function() {
   $('.div').hover(function() {
   $(this).find(".hidden").fadeIn(1000);
   }, function() {
   $(this).find(".hidden").fadeOut(500);
   });
});

How can I do this?
I've made an JSFiddle to display my problem.

A: You need to use .stop(clearQueue,jumpToEnd) with the params clearQueue and jumpToEnd as true.
as the clearQueue will remove queued animation as well and
jumpToEnd to complete the current animation immediately
By Default they are set to true .

$(function() {
  $('.div').hover(function() {
    $(this).find(".hidden").stop(true, true).fadeIn(500);
  }, function() {
    $(this).find(".hidden").stop(true, true).fadeOut(500);
  });
});
p.hidden {
  display: none;
}

.div {
  display: block;
  background: green;
  width: 300px;
  height: auto;
}

title

hey would you show me

title

hey would you show me


text:
Q: Dropzone.js autoProcessQueue not working within Vue component I'm using dropzone.Js inside a Vue component and I'm trying to submit the form in which the dropzone is only after submit button is clicked.
HTML:

    Choose a profile picture:

    <form action="#"
     class="dropzone"
     id="dropzone-js"></form>

The print screen:

Vue component script:
 ready(){
  // I´ve tried to implement the autoProcessQueue to false in many ways, but
  // withouth the desired result
  Dropzone.forElement(".dropzone").options.autoProcessQueue = false;
  Dropzone.options.autoProcessQueue = false;

  new Dropzone('#dropzone-js', {
    paramName: "profileImg", // The name that will be used to transfer the file
    maxFilesize: 2, // MB
    maxFiles: 1,
    autoProcessQueue:false,
    autoProcessQueue: false,
    uploadMultiple: false,
    accept: function(file, done) {
            console.log('event',event)

            console.log('accepted dropzone file', file)
            this.form.photo = file
            // done();
    },

    init: function() {
        this.on("addedfile", function(file, event) {
            // this.form.photo = file
            // alert("Added file.");
            console.log('event',event)
        });
    },
    init: function() {
            this.on("maxfilesexceeded", function (file) {
                    alert('Only 1 file allowed')
                    this.removeFile(file);
            });
    }
})
},

I'm still not sure what I'm missing here, but as it's the first time I'm using both, I'm quite lost on usage specifications.

A: I found a work-around, which I would guess is not recommended. If someone knows a better one, please comment.
I had to edit the dropzone.js source code and set the autoProcessQueue = false, like so:

I think the local setting of the dropzone object is not being able to override the global autoProcessQueue config.


text:
Q: Archival lists of most subscribed YouTube accounts? Is there a way to find the top X YouTube accounts by subscriber count for Y year---say, the top 100 accounts in 2015? I don't see anything in the API docs, and while there are services like SocialBlade and VidStatsX, they don't provide archived lists, and the data is not captured on archive.org.

A: The standard Analytics API doesn't provide this functionality. You can get data about views, likes, and dislikes, but you must provide one or more channel IDs.

Required Parameters: ids
Identifies the YouTube channel or content owner for which you are
retrieving YouTube Analytics data.

*

*To request data for a YouTube
channel, set the ids parameter value to either channel==MINE or
channel==CHANNEL_ID, where CHANNEL_ID identifies the currently
authenticated user's YouTube channel.

*To request data for a YouTube
CMS content owner, set the ids parameter value to
contentOwner==OWNER_NAME, where OWNER_NAME is the CMS user ID for the
user.

Use the Try this API section on the reference page to test the possibilities.


text:
Q: Sitecore and TDS and Package Deployment I'm using TDS to create .update packages. I've set the settings for this in TDS properties. This works fine locally. But on my build server (TeamCity) it does not seem to build the update packages. Do I need to add some command line parameters for this? I've tried using the MSBuild runner, and using a script file that calls MSBuild.exe. I've also tried putting my TDS settings in a TdsGlobal.config. It just not create the .update files, or even the directory where they should go.

A: The answer is you need to set the TDS Update Package settings as part of your command line parameters, so:
msbuild.exe /p:GeneratePackage=${generatePackage};PackageAuthor=${packageAuthor};PackagePublisher=${packagePublisher};etc...

These settings are also set in the visual studio solution -> TDS project -> Properties. I dont have time to experiment if I can remove them from visual studio, but I expect that I can.


text:
Q: Is it possible to pipe a file with quotes and special characters to OpenSSL? I am trying to write a bash script that will allow the user to input a password, and then pipe stdin (either via terminal commands or a piped file) to 'openssl enc' to encrypt it line by line using that password, and then finally pipe it out to an external TCP server.
This is what I have so far, and it mostly works:
#!/bin/bash
printf "What is your encryption
password?\n"
read -s password </dev/tty
while read line; do echo "$line" | openssl enc -aes-256-cbc -base64 -pass pass:$password -e; done > >(openssl s_client -quiet -connect localhost:3001)

You run this via cat file | script.sh.
The problem I'm running into is when the file has quotes or special characters in it and breaks the echo.
Is there a way to get around this?

A: Both read and some versions of echo will do some kinds of escape/quote/whitespace/etc processing. You can get read to behave with IFS= read -r -- the IFS= prevents it from trimming leading and trailing whitespace (and since it's a prefix, it won't mess other things up like a general assignment to IFS), and -r tells it not to try to parse escape (backslash) characters. echo is hopeless, so use printf '%s\n' instead.
You also have similar problems with the password variable; use the same read tricks, and then expand it in double-quotes to prevent word-splitting and wildcard expansion from doing weird things. Oh, and I prefer to use read -p prompt rather than printing a separate prompt, and send a newline to /dev/tty afterward so it doesn't just sit there at the prompt.
The pipe and openssl themselves shouldn't be any trouble -- these are both binary-safe interfaces, so no quote or anything parsing there. Mind you, you might have some problems on the decrypt side...
Something like this:
#!/bin/bash
IFS= read -rs -p "What is your encryption password? " password </dev/tty
echo >/dev/tty
while IFS= read -r line; do
    printf '%s\n' "$line" | openssl enc -aes-256-cbc -base64 -pass "pass:$password" -e
done > >(openssl s_client -quiet -connect localhost:3001)


text:
Q: Android disable autocomplete for a certain string I have an AutoCompleteTextView set up right now, but I want to prevent it from auto-completing a certain string (the user has to input it manually to get a result).  Right now it is auto-completing for the entire list, but I was wondering if there is any way to make the auto-completion selective.
Thanks!

A: Although I haven't done this myself, but i think if you provide your own implementation of getFilter method in Adapter you can control if any results will be shown or not. So basically you will define the class
public class AutoCompleteAdapter extends ArrayAdapter<String> implements Filterable

and then override getFilter method
@Override
public Filter getFilter() {
    Filter myFilter = new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
        ......
        }

        @Override
        protected void publishResults(CharSequence contraint, FilterResults results) {
        ....
        }


text:
Q: How can I store HashMap> inside a list? My hashmap stores the string as key and arraylist as the values. Now, I need to embed this into a list. That is, it will be of the following form:
List<HashMap<String, ArrayList<String>>>

These are the declarations I have used:
Map<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
ArrayList<String> arraylist = new ArrayList<String>();
map.put(key,arraylist);
List<String> list = new ArrayList<String>();

Can anyone help me which method and how to use in the list to proceed storing my map into it?

A: Always try to use interface reference in Collection, this adds more flexibility.
What is the problem with the below code?
List<Map<String,List<String>>> list = new ArrayList<Map<String,List<String>>>();//This is the final list you need
Map<String, List<String>> map1 = new HashMap<String, List<String>>();//This is one instance of the  map you want to store in the above list.
List<String> arraylist1 = new ArrayList<String>();
arraylist1.add("Text1");//And so on..
map1.put("key1",arraylist1);
//And so on...
list.add(map1);//In this way you can add.

You can easily do it like the above.

A: Try the following:
List<Map<String, ArrayList<String>>> mapList =
    new ArrayList<Map<String, ArrayList<String>>>();
mapList.add(map);

If your list must be of type List<HashMap<String, ArrayList<String>>>, then declare your map variable as a HashMap and not a Map.

A: First you need to define the List as :
List<Map<String, ArrayList<String>>> list = new ArrayList<>();

To add the Map to the List , use add(E e) method :
list.add(map);

A: First, let me fix a little bit your declaration:
List<Map<String, List<String>>> listOfMapOfList =
    new HashList<Map<String, List<String>>>();

Please pay attention that I used concrete class (HashMap) only once. It is important to use interface where you can to be able to change the implementation later.
Now you want to add element to the list, don't you? But the element is a map, so you have to create it:
Map<String, List<String>> mapOfList = new HashMap<String, List<String>>();

Now you want to populate the map. Fortunately you can use utility that creates lists for you, otherwise you have to create list separately:
mapOfList.put("mykey", Arrays.asList("one", "two", "three"));

OK, now we are ready to add the map into the list:
listOfMapOfList.add(mapOfList);

BUT:
Stop creating complicated collections right now! Think about the future: you will probably have to change the internal map to something else or list to set etc. This will probably cause you to re-write significant parts of your code. Instead define class that contains you data and then add it to one-dimentional collection:
Let's call your class Student (just as example):
public Student {
    private String firstName;
    private String lastName;
    private int studentId;

    private Colectiuon<String> courseworks = Collections.emtpyList();

    //constructors, getters, setters etc
}

Now you can define simple collection:
Collection<Student> students = new ArrayList<Student>();

If in future you want to put your students into map where key is the studentId, do it:
Map<Integer, Student> students = new HashMap<Integer, Student>();

A: class Student{
    //instance variable or data members.

    Map<Integer, List<Object>> mapp = new HashMap<Integer, List<Object>>();
    Scanner s1 = new Scanner(System.in);
    String name = s1.nextLine();
    int regno ;
    int mark1;
    int mark2;
    int total;
    List<Object> list = new ArrayList<Object>();
    mapp.put(regno,list); //what wrong in this part?
    list.add(mark1);
    list.add(mark2);**
    //String mark2=mapp.get(regno)[2];
}


text:
Q: HTML email template not working while sending mail through apex I am trying to send an html email template body in the mail from apex code by using messaging.renderStoredEmailTemplate method but it is sending plain text not html body.
Here is the code :
 EmailTemplate tempID = [SELECT Id,HTMLValue,Name FROM EmailTemplate WHERE DeveloperName =: label.ApprovalProcessEmailTemplate];
            string emailBody= messaging.renderStoredEmailTemplate(tempID.Id,newQuotes.OwnerId,newQuotes.Id).getHtmlBody();
            mail.setHtmlBody(emailBody);
            List<String> users = new List<String>{ userInfo.getUserEmail()};
            mail.setToAddresses(users);

            Messaging.SendEmailResult [] result = Messaging.sendEmail(new list<Messaging.SingleEmailMessage> {mail});

Expected :

Actual :

email is not sending in proper html format.


text:
Q: Django use datetime.date() as input for DateField to achieve past date input I have a simple model where I want to input a past date as the DateField in the model.
import datetime

class BalanceSheet(models.Model):

     ticker = models.ForeignKey(Security, on_delete=models.CASCADE, related_name="balance_sheet")

     date = models.DateField(default=datetime.date)

but I receive the following error when trying to add a record in the admin panel
TypeError at /admin/financials/balancesheet/add/
function missing required argument 'year' (pos 1)
Request Method: GET
Request URL:    http://localhost:8000/admin/financials/balancesheet/add/
Django Version: 3.1
Exception Type: TypeError
Exception Value:
function missing required argument 'year' (pos 1)
Exception Location: /usr/local/lib/python3.7/site-packages/django/db/models/fields/__init__.py, line 831, in get_default
Python Executable:  /usr/local/bin/python
Python Version: 3.7.8
Python Path:
['/code',
 '/usr/local/lib/python37.zip',
 '/usr/local/lib/python3.7',
 '/usr/local/lib/python3.7/lib-dynload',
 '/usr/local/lib/python3.7/site-packages']
Server time:    Sun, 09 Aug 2020 11:40:48 +0000

A: The default you are passing requires an argument, that is why you are getting the error.  if you pass datetime.date.today you can alter the date to a previous date once the record has been created.
Try to replace
 ...
 date = models.DateField(default=datetime.date)

with:
import datetime

...
date = models.DateField(default=datetime.date.today)

Or:
from datetime import datetime

...
date = models.DateField(default=datetime.now)


text:
Q: Replace ID tags so they can be used more often What is the best way to solve this problem? I want the 2nd gives the same "effect" as the 1st.

$("#flip").click(function() {
      $("#panel").slideToggle("slow");
    });
#panel {
     padding-top: 10px;
     padding-bottom: 10px;
     display: none;
    }

    #flip {
    text-decoration: underline
    }

+ Test 1

      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vestibulum, purus imperdiet tincidunt pretium, sem elit auctor nisl, nec viverra quam lacus dignissim risus.

+ Test 2

      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vestibulum, purus imperdiet tincidunt pretium, sem elit auctor nisl, nec viverra quam lacus dignissim risus.

I know it is on the IDs and I can use them only once but I don't know how to solve it.
Hope someone can help me!

A: I've updated your fiddle: http://jsfiddle.net/mj1gpsky/2/
Here is the code:

$(document).ready(function(){
    $(".flip").click(function(e){

      $('#' + $(this).data("open")).slideToggle("slow");
    });
});
.panel {
  padding-top: 10px;
 padding-bottom: 10px;
  display: none;
}

.flip {
  text-decoration: underline
}

+ Test 2

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vestibulum, purus imperdiet tincidunt pretium, sem elit auctor nisl, nec viverra quam lacus dignissim risus.

+ Test 2

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vestibulum, purus imperdiet tincidunt pretium, sem elit auctor nisl, nec viverra quam lacus dignissim risus.

Hope this helps


text:
Q: Don't work Locale ID I develop my project in Delphi 2010 on Windows 7 (Russian localization).
When I started working on Windows 8 (English) and moved my project to Delphi XE3 I saw standard dialogs (like buttons, headers of MessageDlg and system errors) in English (must be in Russian).
Look at Project - Options - Version Info - Language, and saw Locale ID as "English (United States)" in "Debug Configuration - 32-bit Windows platform".
Look other configurations, and saw in three headlines like "All configurations - All platforms" (where all elements disabled)
Locale ID is "Russian (Russia)" and in all subtitles "32-bit Windows platform" Locale ID is "English (United States)".
OK, I changed in all configurations Locale ID to "Russian (Russia)". But It doesn't work - all messages in English. In properties of builded exe-file Language=Russian (Russia).
Tested it on Windows 7, Vista with Russian localization.

A: The Locale ID in the version info has nothing to do with the language used for standard dialogs. You can even have multiple entries in version info for different locales.
The language used for standard dialogs depends on the language setting for the current Windows user. It is the same for all applications started under this user account and is independent of the language used inside the application itself.

A: There's a consts.pas/consts.dcu unit in Delphi source, which contains all the translations of the standard dialogs. You can make a copy of this file and add it to your project. You can make your changes and build your project.
Make sure, that the original consts.pas/consts.dcu is not available (rename/move them).


text:
Q: How to create textinputlayout with bottm shadow How to create TextInputLayout shadow, I have created but the hint is displayed bottom off and then I am editing the edit text then both are text center and also attach shadow login code Please let me know if you any question .
Please sees this image
Thank in advance
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical">

<com.google.android.material.textfield.TextInputLayout
    android:layout_width="match_parent"
    android:layout_marginStart="@dimen/_10sdp"
    android:layout_marginEnd="@dimen/_10sdp"
    android:background="@drawable/shadow_login"
    android:padding="@dimen/_10sdp"
    android:layout_height="wrap_content">

    <androidx.appcompat.widget.AppCompatEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="test"
        android:background="@null" />
</com.google.android.material.textfield.TextInputLayout>

My code output is
My shadow_login code is below
<?xml version="1.0" encoding="utf-8"?>

<item>
    <shape>
        <padding
            android:bottom="1dp"
            android:left="0.5dp"
            android:right="0.5dp"
            android:top="0.5dp" />
        <solid android:color="#00CCCCCC" />
        <corners android:radius="@dimen/_30sdp" />
    </shape>
</item>
<item>
    <shape>
        <padding
            android:bottom="1dp"
            android:left="0.5dp"
            android:right="0.5dp"
            android:top="0.5dp" />

        <solid android:color="#10CCCCCC" />
        <corners android:radius="@dimen/_30sdp" />
    </shape>
</item>
<item>
    <shape>
        <padding
            android:bottom="1dp"
            android:left="0.5dp"
            android:right="0.5dp"
            android:top="0.5dp" />

        <solid android:color="#20CCCCCC" />

        <corners android:radius="@dimen/_30sdp" />
    </shape>
</item>
<item>
    <shape>
        <padding
            android:bottom="1dp"
            android:left="0.5dp"
            android:right="0.5dp"
            android:top="0.5dp" />

        <solid android:color="#30CCCCCC" />

        <corners android:radius="@dimen/_30sdp" />
    </shape>
</item>
<item>
    <shape>
        <padding
            android:bottom="1dp"
            android:left="0.5dp"
            android:right="0.5dp"
            android:top="0.5dp" />

        <solid android:color="#50CCCCCC" />

        <corners android:radius="@dimen/_30sdp" />
    </shape>
</item>

<item>
    <shape>
        <solid android:color="@android:color/white" />
        <corners android:radius="@dimen/_30sdp" />

    </shape>
</item>

A: use margin instead of padding and add elevation to textinputlayout
, and remove background="@null" from edittext
try this
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    >

   <LinearLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:background="@drawable/shadow_login">

        <com.google.android.material.textfield.TextInputLayout
            android:layout_width="match_parent"
            android:layout_marginStart="@dimen/_10sdp"
            android:layout_marginEnd="@dimen/_10sdp"
            android:layout_margin="@dimen/_10sdp"
            android:elevation="8dp"
            android:layout_height="wrap_content">

            <androidx.appcompat.widget.AppCompatEditText
               android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/shadow_login"
                android:hint="test" />
        </com.google.android.material.textfield.TextInputLayout>

    </LinearLayout>

</LinearLayout>

and the background shape must only be :
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <solid android:color="#20CCCCCC" />

    <corners android:radius="@dimen/_30sdp" />

</shape>

A: Use something different.
Don't use the background in the TextInputLayout but wrap the component in a layout with this kind of background (a simple LinearLayout but consider for example also a CardView)
Something like:
<LinearLayout
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:background="@drawable/shadow_login">

    <com.google.android.material.textfield.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="CVV"
        android:paddingTop="4dp"
        android:paddingLeft="4dp"
        android:paddingRight="4dp"
        android:paddingBottom="2dp"
        app:boxStrokeWidth="0dp"
        app:boxStrokeColor="#FFFFFF"
        app:boxBackgroundColor="#FFFFFF"
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
        >

        <com.google.android.material.textfield.TextInputEditText
            ../>

    </com.google.android.material.textfield.TextInputLayout>

If the shadow is not a requirement just use a standard OutlinedBox with rounded corners (with your favorite colors and dimens).
<com.google.android.material.textfield.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="CVV"
    app:shapeAppearanceOverlay="@style/Rounded_ShapeAppearanceOverlay.MaterialComponents.TextInputLayout"
    style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
    >

    <com.google.android.material.textfield.TextInputEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />

</com.google.android.material.textfield.TextInputLayout>

with the shape defined by:
  <style name="Rounded_ShapeAppearanceOverlay.MaterialComponents.TextInputLayout" parent="">
    <item name="cornerFamily">rounded</item>
    <item name="cornerSize">50%</item>
  </style>


text:
Q: Python: How can I check if an item in a list contains a string within an elif statement where two conditions must be met? I'm making a scraper in python that executes a search, then opens each link in the search and makes a list of everything within a strong tag.
Then it append the list to a Dataset. Not all of the pages are the same so I am organizing them according to how many strong tags and in some cases if a particular tag contains one or more words. I need both conditions to be met in order for the contents of the strong tag to go the right column.
The code works but is bulky, and I'm trying to work on making clean code.
    for a in addr:
        driver.get(a)
        print(a)

        WebDriverWait(driver, 60).until(EC.presence_of_element_located((By.ID, "_errorElement_")))
        html = driver.page_source
        soup = BeautifulSoup(html, "html.parser")

        columns = ['Business Name', 'Control Number', 'Business Type', 'Business Status', 'NAICS Code', 'NAICS Sub Code',
                   'Principal Office Address', 'Date of Formation/ Registration Date', 'State of Formation/ Jurisdiction',
                   'Last Registration Year', 'Dissolved Date', 'Registered Agent', 'Registered Agent Address', 'County']

        df = pd.DataFrame(columns=columns)
        strong = []
        for strong_tag in soup.find_all('strong'):
            strong.append(str(strong_tag.text))

        if len(strong) == 14:
            values = [strong[0], strong[1], strong[2], strong[3], strong[4], strong[5], strong[6], strong[7], strong[8],
                      strong[9], strong[10], strong[11], strong[12], strong[13]]
        elif len(strong) == 6:
            values = [strong[0], '', '', 'Name Reservation', '', '', strong[3], strong[1], '', '', '', strong[2], '', '']

        elif len(strong) == 13 and "Active" in str(strong[3]):
            values = [strong[0], strong[1], strong[2], strong[3], strong[4], strong[5], strong[6], strong[7], strong[8],
                      strong[9], '', strong[10], strong[11],strong[12]]
#the above code appears to be correct for 13 length active compliance Domestic LLC( and possibly active owes current year)

The following 5 elif statements are what i'm trying to combine. I'm not sure how to check if an item in a list contains any of the 5 words while also checking the length of the list.
 elif len(strong) == 13 and "Admin" in str(strong[3]):
        values = [strong[0], strong[1], strong[2], strong[3], strong[4], '', strong[5], strong[6], strong[7], strong[8],
                  strong[9], strong[10], strong[11], strong[12]]
    elif len(strong) == 13 and "Abandoned" in str(strong[3]):
        values = [strong[0], strong[1], strong[2], strong[3], strong[4], '', strong[5], strong[6], strong[7], strong[8],
                 strong[9], strong[10], strong[11], strong[12]]
    elif len(strong) == 13 and "Withdrawn" in str(strong[3]):
        values = [strong[0], strong[1], strong[2], strong[3], strong[4], '', strong[5], strong[6], strong[7], strong[8],
                  strong[9], strong[10], strong[11], strong[12]]
    elif len(strong) == 13 and "Dissolved" in str(strong[3]):
        values = [strong[0], strong[1], strong[2], strong[3], strong[4], '', strong[5], strong[6], strong[7], strong[8],
                 strong[9], strong[10], strong[11], strong[12]]
    elif len(strong) == 13 and "Terminated" in str(strong[3]):
        values = [strong[0], strong[1], strong[2], strong[3], strong[4], '', strong[5], strong[6], strong[7], strong[8],
                  strong[9], strong[10], strong[11], strong[12]]

    elif len(strong) == 12:
        values = [strong[0], strong[1], strong[2], strong[3], strong[4], '', strong[5], strong[6], strong[7], strong[8],
                  '', strong[9], strong[10], strong[11]]
    else:
        values = [strong[0], '', '', '', '', '', '', '', '', '', '', '', '', '']
        print("WARNING! New values length...")
    df = df.append(pd.Series(values, index=columns), ignore_index=True)
    df2 = df2.append(df)
driver.close()
driver.switch_to.window(driver.window_handles[0])

A: Just use in the other way around, you want to check if strong[3] is in the array ['Admin', 'Abandoned', ...]:
l = ['Admin', 'Abandoned', 'Withdrawn', 'Dissolved', 'Terminated']
if len(strong) == 13 and strong[3] in l:
    values = strong[:5] + [''] + strong[5:]
elif len(strong) == 12:
    values = strong[:5] + [''] + strong[5:9] + [''] + strong[9:]
else:
    values = [strong[0]] + ['']*12

P.S. And you can also combine elements when assigning to values to make it more concise

A: The inside checks are redundant, I will suggest you to add a length condition outside and when that condition is accomplished, then met the following requirements inside as example:
if len(strong) == 13:
   # All the flow comming here has a list of length 13
   if "Dissolved" in strong[3]:
      # Do whatever
      pass
   elif ...:
      ...
elif len(strong) == 12:
    ...

This way it's more understandable.


text:
Q: Is there any gem for Linux FIFOs in JRuby? Seeing as how C extensions are out in recent releases of JRuby, is there a gem that supports FIFOs in JRuby?  The 'mkfifo' gem depends on C extensions.

A: there's likely no such thing but maybe you can use FFI to get to the native stuff. also on JRuby you should be still able to read named pipes just fine.


text:
Q: Getting RegExp result after being used in if-statement I've seen people do the following:
if (/Firefox\/(\+S)/.test(userAgent)) {
    firefox = RegExp.$1;
}

I know (sorta) what the regexp does, but I'm not really sure how it can be accessed with RegExp.$1.
And as a side note:
if (/Win(?:dows )?([^do]{2})\s?(\d+\.\d+)?/.test(ua)) {
    if (RegExp.$1 == "NT") {
        switch (RegExp.$2) {

What's the difference between $1 and $2?

A:
What's the difference between $1 and $2?

Those are the references to the captured groups (captured by the regexp)
The JavaScript flavor of regex refers to group #1 as $1, and group #2 as $2.
 Win(?:dows )?([^do]{2})\s?(\d+\.\d+)?
     ^         ^            ^
     |         |            |
     |         group#1      group#2
     |
     ignored group (?: means non-capturing)

A: RegExp is a global object that is updated every time a RegExp is run. RexExp.$1 will contain the text matched by the corresponding set of parentheses in the last pattern matched.
For the sidenote: $1 contains is the first part of the regexp between the parentheses, $2 the seconds etc...


text:
Q: Performance using Inline table valued function to encapsulate SQL code The question is: Can inline table valued functions (ITVF) be used to encapsulate and reuse code? Or will this result in performance issues?
I was researching inline table valued functions, which led me to this discussion:
When would you use a table-valued function?
An answer in the discussion states that an inline table valued function "allows the optimizer to treat these functions no differently than the objects they encapsulate giving you optimum performance (assuming that your indexes and statistics are ideal)."
My original problem was that I was trying to reformat different data sources into a standard format and then union them. I tested unioning 6 different ITVF versus performing the unions and transformation all in one query. The execution plan was identical.
Since my background is in oop, I would prefer to split up queries into smaller functions, but before I commit to doing this throughout future projects, I was wondering if using too many ITVFs will eventually cause performance issues.

A: ITVFs are perfect for encapsulating query logic for re-use. I have a dozen or so financial reports that all query the same set of tables for roughly the same information, and by creating a function to provide that data I can be sure that all of my reports are pulling from the same body of data with the same filters and transformations, etc.
That being said, you could also just as easily create a view instead of an ITVF, but ITVFs also provide a way to filter or otherwise transform data based on the parameters sent in. For example, my financial functions could accept a district name as an optional input parameter and only return data for that district. By using the ITVFs this way the optimizer can, over time, optimize the query plan based on the parameters sent in, which helps rather than hindering performance.
I'd recommend that instead of a union on six different ITVFs, just pull all of your tables together into a single ITVF: that way you only have one place to make updates if your table schemas or reporting demands change.

A:
Can inline table valued functions (ITVF) be used to encapsulate and reuse code?

Yes.  And they are superior in this to multi-statement TVFs because with multi-statement TVFs the encapsulation prevents the query optimizer from pushing predicates into the TVF logic, and prevents it from accurately estimating the number of rows returned.

Or will this result in performance issues?

Short answer, not typically.
Longer answer:
There are 4 ways to encapsulate and reuse query logic (whole queries, not just scalar expressions).

*

*Views

*Inline Table Valued Functions

*Multi-Statement Table Valued Functions

*Temporary Tables

*Table Variables

Views and Inline TVFs don't inherently degrade performance, but they add to the complexity of query optimization.
Where the optimizer fails to consistently find low-cost plans you may need to intervene.  A common way you can do that is by forcing spooling (ie materializing) of intermediate results, for instance replacing an Inline TVF with a multi-statement TVF, or by spooling results to a temp table ahead-of-time.
Spooling reduces the complexity of the encapsulating query at the cost of possible optimization of the encapsulated query when run in the context of the larger query.
When spooling results, Temp Tables are typically the best, as SQL Server they can have indexes and statistics that enable SQL Server to accurately assess the cost of the plans that will consume the intermediate results.


text:
Q: Error while creating web application "Specified value is not supported for the parameter" in 2010 I am using SharePoint 2010.While creating a web application i am getting the following error :Specified value is not supported for the parameter.Some times the user credentials are asking for regularly.Please help me.

A: This happens when server is not connected to the domain, at least this was the case for me having the same issue.


text:
Q: Outcome Dependant Columns I'm creating a list to track pieces of work that are currently ongoing and under review - each item can sit in 1 of 4 stages which are
Stage 1
Stage 2
Stage 3
Closed

If the user selects stage 2 from the drop down I want some additional columns to appear that will need to be populated, any ideas?
I'm relatively new to doing this, so if you could keep your answers basic so I can understand it will be much appreciated!!
Thanks

A: You can use jquery to show/hide fields on sharepoint list forms. Using jQuery, you can control the visibility of fields.
For example refer this link.


text:
Q: Assess Most Used Classes of our Managed Package We have a popular managed package on AppExchange. Is there any way for us to assess which of our classes and custom objects are used the most by our clients? Does Salesforce or 3rd parties provide any tools to gather such data systematically without having the need to survey our users?
This information will help us understand which of our features have most use; hence, we need to invest most time to ensure they work flawlessly. Also, it would be great to know which if our classes & features are not used so much; hence, we don't prioritize development there.

A: You can use the Usage Metrics feature as an ISV to identify most used custom objects and visualforce pages:
https://developer.salesforce.com/docs/atlas.en-us.packagingGuide.meta/packagingGuide/usage_metrics_intro.htm

Custom objects — the total number of records existing per organization
  in each custom object. This enables you to track how the usage of that
  custom object is growing with time in any subscriber organization,
  which is a reliable indicator of how much it's being utilized

It is not the most user friendly tool though - but you can install a package to help parse the data. But I ended up needing to parse the data myself with some apex to get more detailed insights.
Not sure how you would track Apex Class usage without adding some internal logging of when a customer accessed a class - but you could then maybe use the subscriber-to-LMO part of feature management to pass that data back every night


text:
Q: Serial execution of package tests I have implemented several packages for a web API, each with their own test cases. When each package is tested using go test ./api/pkgname the tests pass. If I want to run all tests at once with go test ./api/... test cases always fail.
In each test case, I recreate the entire schema using DROP SCHEMA public CASCADE followed by CREATE SCHEMA public and apply all migrations. The test suite reports errors back at random, saying a relation/table does not exist, so I guess each test suite (per package) is run in parallel somehow, thus messing up the DB state.
I tried to pass along some test flags like go test -cpu 1 -parallel 0 ./src/api/... with no success.
Could the problem here be tests running in parallel, and if yes, how can I force serial execution?
Update:
Currently I use this workaround to run the tests, but I still wonder if there's a better solution
find <dir> -type d -exec go test {} \;

A: The go tool is provided to make running unit tests easier using the convention that *_test.go files contain unittests in them. Because it assumes they are unittests it also assumes they are hermetic. It sounds like your tests either aren't unittests or they are but violate the assumptions that a unittest should fulfill.
In the case that you mean for these tests to be unittests then you probably need a mock database for your unittests. A mock, preferrably in memory, of your database will ensure that the unittest is hermetic and can't be interfered with by other unittests.
In the case that you mean for these tests to be integration tests you are probably better off not using the go tool for these tests. What you probably want is to create a seperate test binary whose running you can control and write you integration test scripts in there.
The good news is that creating a mock in Go is insanely easy. Change your code to take an interface with the methods you care about for the databases and then write an in memory implementation of that interface for testing purposes and pass it into your application code that you want to test.

A: As others have pointed out, -parallel doesn't do the job (it only works within packages). However, you can use the flag -p=1 to run through the package tests in series. This is documented here:
http://golang.org/src/cmd/go/testflag.go
but (afaict) not on the command line, go help, etc. I'm not sure it is meant to stick around (although I'd argue that if it is removed, -parallel should be fixed.)

A: Just to clarify, @Jeremy's answer is still the accepted one:
Since my integration tests were only run on one package (api), I removed the separate test binary in the end and created a pattern to separate test types by:

*

*Unit tests use the normal TestX name

*Integration tests use Test_X
I created shell scripts (utest.sh/itest.sh) to run either of those.

*

*For unit tests go test -run="^(Test|Benchmark)[^_](.*)"

*For integration tests go test -run"^(Test|Benchmark)_(.*)"

*Run both using the normal go test


text:
Q: ASP Postback deleting data I am working with Web Forms and I am having some trouble specifically with Drop-downs and the post back function they have. What is happening is I have multiple methods for each drop-down, so when you select a dropdown index, it will go to said method and populate the selections.
The issue is that the way to show these selections is to AutoPostBack (As far as I know) which posts back to the back-end code and runs it again. This creates issues when I try and save data to a Model such as this:
public class List_id_model
{
    public List<int> client_id { get; set; }
    public List<int> pro_id { get; set; }
}

I would have to re-instantiate the object every time I must use it, which then overwrites the data within the model. How do I prevent this from happening?
Here is my aspx code for the dropdown:
 <asp:DropDownList ID="DropDown_Project" runat="server" AutoPostBack="true" AppendDataBoundItems="true" DataTextField="Company_Name" DataValueField="id" Width ="200px" OnSelectedIndexChanged="DropDown_Project_SelectedIndexChanged" >
                        <asp:ListItem Text="---Select---" Value="0" />
                 </asp:DropDownList>

Here is the code behind:
protected void DropDown_Client_SelectedIndexChanged(object sender, EventArgs e)
{
List_id_model client_list = new List_id_model();
client_list.client_id = new List<int>();
client_list.client_id.Add(value);
}

protected void DropDown_Project_SelectedIndexChanged(object sender, EventArgs e)
{

List_id_model client_list = new List_id_model();
client_list.pro = new List<int>();
client_list.pro_id.Add(value);
}

What I want to is somehow avoid re-instantiating the "List_id_model" everytime I need to add to it, since that will dump all the current data.
If you have any questions about my question I will be more than happy to get back to you tomorrow morning when I have more time to figure this out.

A: You should store your data at some persistent storage. In your case you should use ViewState. For example:
public List_id_model Model
{
  get
  {
    List_id_model model = ViewState["List_id_model"] as List_id_model;
    if (model != null)
       return model;
    return new List_id_model();
  }
  set
  {
    ViewState["List_id_model"] = value;
  }
}

protected void DropDown_Client_SelectedIndexChanged(object sender, EventArgs e)
{
    List_id_model client_list = Model;
    if (client_list.client_id == null)
       client_list.client_id = new List<int>();
    client_list.client_id.Add(value);
    Model = client_list;
}

This code is to demonstrate approach, I didn't try it in IDE, so sorry if you find some typos etc.


text:
Q: Can I use my own software with a different license from that one used to make it public? I ask because I found no answer to this, maybe because is too obvious (I think there is no thing like "legally obvious").
Imagine that I make a small library (DLL) or a styling template (CSS) or whatever, and I want to make it public and open source (yay!).
Until now, I used to license these kind of things with GPLv3 if it is a whole project, or LGPLv3 if it is a small part like I said before.
My question is, as owner of my code and binaries, am I forced in some way to use them in the same way I already specified in the license I give them?
For example, using my GPLv3 library in a proprietary program (closed source) with EULA and everything...
Thanks in advance.

A: As long as you are the sole copyright holder, you can do what you want with the software. Why? When someone uses software and doesn't adhere to the license, the copyright holder can sue them for copyright infringement. If you are the only copyright holder, only you can sue yourself. Nobody else.


text:
Q: Difference between IWorkbenchWindow and IWorbenchPage in Eclipse SDK I still don't get what the difference is between the two. The eclipse docs just say that a window can have many pages, but when does that happen? Under what circumstances is the number of pages more than one?

A: You will have multiple pages in a window only if you are running Eclipse 2.0 or earlier. The API is there only to maintain binary backward compatibility with the older releases. Eclipse 3.x doesn't have multiple pages per workbench window.


text:
Q: Display HTML5 controls in System.Windows.Forms.WebBrowser Simple question. I have a WinFomrs app (C#) and there's a WebBrowser control which displays html to the user. The thing is I need to start using some of the css3 capabilities like rounded border for buttons.
I have tried adding the <!DOCTYPE html> node to the html code with no luck.
What should I do? Do I need to change the control? Does anybody know a good alternative?
Edit: The html code I try to show displays correctly in every browser (IE9, Chrome, Firefox)


text:
Q: Split string by space and space as delimiter in Oracle with regexp_substr I had one requirement like one string will be there like "FATALITY, BODY SYS, TEAM BUILDING EVENT.THE EMPLOYEE WAS PARTICIPATING IN A TEAM BUILDING EVENT WHEN HE SUFFERED A HEART ATTACK. THE EVENT WAS FATAL." and I have another LOOK up table to match the certain word in the above string .If any word matches from this this sentence then the matching word should only need to return other wise null valves need to be there. This can be done with regexp_substr but not able to match the pattern.
input string :FATALITY, BODY SYS, TEAM BUILDING EVENT.THE EMPLOYEE WAS PARTICIPATING IN A TEAM BUILDING EVENT WHEN HE SUFFERED A HEART ATTACK. THE EVENT WAS FATAL.
Expected o/p: HEART,FATAL --this heart and fatal will be in lookup table.
Thanks In Advance.

A: How about a simple INSTR function?
SQL> with string (id, col) as
  2    (select 1, 'FATALITY, BODY SYS, TEAM BUILDING EVENT.THE EMPLOYEE WAS PARTICIPATING IN A TEAM BUILDING EVENT WHEN HE SUFFERED A HEART ATTACK. THE EVENT WAS FATAL.' from dual union all
  3     select 2, 'THERE IS ONLY HEART IN HERE' from dual),
  4  lookup (word) as
  5    (select 'HEART' from dual union all
  6     select 'FATAL' from dual
  7    )
  8  select s.id,
  9    listagg(l.word, ', ') within group (order by l.word) result
 10  from string s join lookup l on instr(s.col, l.word) > 0
 11  group by s.id;

        ID RESULT
---------- ----------------------------------------
         1 FATAL, HEART
         2 HEART

SQL>


text:
Q: Run function to update state on component constructor (and later) I'm trying to write a little combat card game as a learning excercise to understand React and in particular, state. In the game I'd like each turn a new hand of cards to be drawn that can be played so I created a function that draws the cards and called it from the constructor:
class App extends Component {
    constructor() {
        super();
        this.state = {
            hero: {
                str: 2,
                currentStr: 2,
                def: 2,
                currentDef: 2,
                health: 100,
                currentHealth: 74,
                moves: 3,
                currentMoves: 3,
                cards: [1, 1, 1, 2, 2, 2],
                draw: 4,
                hand: [],
            },
        };

        this.drawHand = this.drawHand.bind(this);
        this.drawHand();
    }

    drawHand() {
        let draw = [];
        let cards = this.state.hero.cards.slice();
        for (let i = 0; i < this.state.hero.draw; i++) {
            const min = 0;
            const max = cards.length -1;
            const position = Math.floor(Math.random() * (max - min + 1)) + min;
            const item = cards.splice(position, 1);
            draw.push(item[0]);
        }

        draw = draw.sort();

        let hero = {...this.state.hero};
        hero.hand = draw;

        this.setState({
            hero: hero
        });
    }

    render() {
        return (

                {this.state.hero.hand.join(',')}

        );
    };
};

When I create the App component however, I get the error
Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op.

I've tried reading around mounted/unmounted components but I can't seem to figure out what's going on here. I figure I need to call the drawHand method later in the rendering process when App is mounted - is there an event or similar I can use for this please?

A: constructor runs before the Component is mounted in the DOM.
So what you want is to execute the method in the componentDidMount lifecycle method.
like this
class App extends Component {
    constructor() {
        super();
        this.state = {
            hero: {
                str: 2,
                currentStr: 2,
                def: 2,
                currentDef: 2,
                health: 100,
                currentHealth: 74,
                moves: 3,
                currentMoves: 3,
                cards: [1, 1, 1, 2, 2, 2],
                draw: 4,
                hand: [],
            },
        };

        this.drawHand = this.drawHand.bind(this);
    }

    drawHand() {
        let draw = [];
        let cards = this.state.hero.cards.slice();
        for (let i = 0; i < this.state.hero.draw; i++) {
            const min = 0;
            const max = cards.length -1;
            const position = Math.floor(Math.random() * (max - min + 1)) + min;
            const item = cards.splice(position, 1);
            draw.push(item[0]);
        }

        draw = draw.sort();

        let hero = {...this.state.hero};
        hero.hand = draw;

        this.setState({
            hero: hero
        });
    }

    componentDidMount() {
       this.drawHand();
    }

    render() {
        return (

                {this.state.hero.hand.join(',')}

        );
    };
};


text:
Q: how shell pipe handles infinite loop Whenever I need to limit shell command output, I use less to paginate the results:
cat file_with_long_content | less
which works fine and dandy, but what I'm curious about is, less still works even if the output is never ending, consider having the following script in inf.sh file:
while true; do date; done
then I run
sh inf.sh | less
And it's still able to again paginate the results, so is it correct to say that pipe streams the result rather than waiting for the command to finish before outputting the result?

A: Yes, when you run sh inf.sh | less the two commands are run in parallel.  Data written into the pipe by the first process is buffered (by the kernel) until it is read by the second.  If the buffer is full (i.e., if the first command writes to the pipe faster than the second can read) then the next write operation will block until further space is available.  A similar condition occurs when reading from an empty pipe: if the pipe buffer is empty but the input end is still open, a read will block for more data.
See the pipe(7) manual for details.

A: It is correct. Pipes are streams.
You can code your own version of the less tool in very few lines of C code. Take the time to do it, including a short research on files and pipes, and you'll emerge with the understanding to answer your own question and more :).


text:
Q: MySQL : retrieve a large select by chunks I have select with more then

70 milion rows

I'd like to save the selected data into the one large csv file on win2012 R2
Q: How to retrieve the data from MySQL by chunks for better performance ?
because when I try to save one the large select I got

out of memory errors

A: You could try using the LIMIT feature. If you do this:
SELECT * FROM MyTable ORDER BY whatever LIMIT 0,1000

You'll get the first 1,000 rows. The first LIMIT value (0) defines the starting row in the result set. It's zero-indexed, so 0 means "the first row". The second LIMIT value is the maximum number of rows to retrieve. To get the next few sets of 1,000, do this:
SELECT * FROM MyTable ORDER BY whatever LIMIT 1000,1000 -- rows 1,001 - 2,000
SELECT * FROM MyTable ORDER BY whatever LIMIT 2000,1000 -- rows 2,001 - 3,000

And so on. When the SELECT returns no rows, you're done.
This isn't enough on its own though, because any changes done to the table while you're processing your 1K rows at a time will throw off the order. To freeze the results in time, start by querying the results into a temporary table:
CREATE TEMPORARY TABLE MyChunkedResult AS (
  SELECT *
  FROM MyTable
  ORDER BY whatever
);

Side note: it's a good idea to make sure the temporary table doesn't exist beforehand:
DROP TEMPORARY TABLE IF EXISTS MyChunkedResult;

At any rate, once the temporary table is in place, pull the row chunks from there:
SELECT * FROM MyChunkedResult LIMIT 0, 1000;
SELECT * FROM MyChunkedResult LIMIT 1000,1000;
SELECT * FROM MyChunkedResult LIMIT 2000,1000;
.. and so on.

I'll leave it to you to create the logic that will calculate the limit value after each chunk and check for the end of results. I'd also recommend much larger chunks than 1,000 records; it's just a number I picked out of the air.
Finally, it's good form to drop the temporary table when you're done:
DROP TEMPORARY TABLE MyChunkedResult;

A: The LIMIT OFFSET approach slows query down when a size of the data is very large. Another approach is to use something called Keyset pagination. It requires a unique id in your query, which you can use as a bookmark to point to the last row of the previous page. The next page is fetched using the last bookmark. For instance:
SELECT user_id, name, date_created
FROM users
WHERE user_id > 0
ORDER BY user_id ASC
LIMIT 10 000;

If the resultset above returns the last row with user_id as 12345, you can use it to fetch the next page as follows:
SELECT user_id, name, date_created
FROM users
WHERE user_id > 12345
ORDER BY user_id ASC
LIMIT 10 000;

For more details, you may take a look at this page.

A: Another approach for such a large dataset, to avoid the need to chunk the output, would be to query the relevant data into its own new table (not a temporary table) containing just the data you need, and then use mysqldump to handle the export to file.

A: Use an unbuffered result set using MYSQLI_USE_RESULT to be able to read through the database and perform a function such as write output to a CSV file row by row.
In short: It writes to CSV/File while reading from Database.
When using mysqli_query it uses MYSQLI_USE_STORE by default and reads the whole database and gets a result set which causes excess memory usage.
Read this for more info on MYSQLI_USE_RESULT and be careful since you may not being able to perform other tasks/queries on the database while the function is running


text:
Q: Loading more entries from database using jquery or ajax PHP
I want to add a 'Load More' Button at the bottom which will display 10 more entries(questions) from the database whenever the user clicks it.
<?php include('connection.php');

$query = mysqli_query($con,"SELECT * FROM questions LIMIT 10");

$data = array();
while($row = mysqli_fetch_assoc($query))
{
    $data[] = $row;
}

$number=count($data);
$i=0;
while($i<$number) {
echo $i+1;
echo ' . ';
echo $data[$i]['question'].'

';
$i++;

?>

A: You need a example in jquery+php? Check this out: http://demos.9lessons.info/loadmore.php
And here are the tutorial: http://www.9lessons.info/2009/12/twitter-style-load-more-results-with.html

A: You need to pass a paging param (such as ?page=2) and use that as your offset.
e.g.
$offset = $num_per_page * ($page - 1);
Then change the query to include something like:
... LIMIT $offset, $num_per_page
Check the docs here

A: You can set an OFFSET in your query and only load in the new entries

$query = mysqli_query($con,"SELECT * FROM questions LIMIT 10 OFFSET =
  $_POST['offset']");

A: If you just want to know if there is a need to show the "load more", just select 11 records, show 10 of them and show the "load more" button if the result count is 11


text:
Q: Why do django templates render dictionaries so slowly? When I render a moderately complex dictionary (4 levels deep, ~2K data points) using django 1.4's default template system the template rendering step takes over 2800ms.  When I do html-gen directly from python instead it takes ~80ms.  Even using another template library (jinja2) renders the same data (in fact, almost exactly the same template syntax - as jinja2 is nearly a drop-in replacement) in under 300ms.
Interestingly, you don't even have to actually render the dictionary in the template to cause this performance issue in django's template system... all you have to do is pass it as an available variable to a template.  A friend of mine suggested this may mean the system is, "...doing a defensive copy or (more stupidly) a comprehension [which] will take time due to running constructors"
Anyone know why django's default template system takes so long to render dictionaries?
* I'll work on adding requested details below *
I am running in debug mode and have the DebugToolbarMiddleware set as one of my middleware classes.  My settings.py file includes:
TEMPLATE_CONTEXT_PROCESSORS = global_settings.TEMPLATE_CONTEXT_PROCESSORS + (
    'django.core.context_processors.request',
)

and....
# rendering like this
return render(
    request,
    template_name='ltm/search_results.html',
    context_instance=RequestContext(request, {
        'menus': menus,
        'results': result_dict
    })
)

A: It would be great if you could provide us with your template code to better understand what kind of template processing we're dealing with exactly.
Firstly, there are potential differences between how your traversing the contents of the dictionary. dict.items() returns a list of tuples which consumes additional memory and takes time to initially construct, but it's faster to access keys and values than through a generator if you used dict.iteritems().
There's also some overhead involved when you pass in variable names preceded by a dot ., e.g. foo.bar.baz, where Django's template performs what's called a variable lookup, trying to determine whether your accessing a dictionary item by key, an object's attribute or a list item by index. I haven't used Jinja2, so the issue with variable lookups might be completely unrelated, but it is something worth considering if there's a difference between the two.
In either case, since your dealing with a fairly large dictionary, it might help if you could reorganize it's structure in the view to simplify how the data is accessed later in the template.


text:
Q: Word Add-in Get full Document text WITH INDICATOR? There is already a question answering related to this topic: Word Add-in Get full Document text?
However, this method can't extract the indicator/bullet points.
Is there a way we can do this? I expect the text to be exactly the same as we manually select all then copy a Word document.
The reason behind this: I'm building a question bank from a microsoft word document. Several tools offer text extraction, however, it usually ignores the bullet point.
I use keywords like A. B. C. D. etc to detect the choices. However, if the author writing choices using indicator/bullet point, this method fails.

A: You can convert the numbered lists (list paragraphs) to plain text with a simple piece of vba.
See here convert lists to text

A: For each paragraph in the document, you can identify whether it is a list item by calling isListItem.
If it is, you can call listItem to get the item.
The listString property in Word.ListItem class can help you get the list item bullet, number, or picture as a string.
Here is an example that how to extract the bullets in the document.
Word.run(async (context) => {
  var paragraphs = context.document.body.paragraphs;
  paragraphs.load("$none");
  await context.sync();
  for (let i = 0; i < paragraphs.items.length; i++) {
    paragraphs.items[i].load("isListItem");
    paragraphs.items[i].load("text");
    await context.sync();
    if (paragraphs.items[i].isListItem) {
      paragraphs.items[i].load("listItem");
      await context.sync();
      console.log(paragraphs.items[i].listItem.listString + " " + paragraphs.items[i].text);
    } else {
      console.log(paragraphs.items[i].text);
    }
  }
});

The document is printed to the console paragraph by paragraph with all bullets retained.


text:
Q: has_many polymorphic relationship where our _type field is an int? We have an app in Rails 4 (but soon to be Rails 5) that has a polymorphic log class that we inherited from a Django app.
In a traditional polymorphic relation, the objects would have source_type and source_id, which would be things like 'some_class' and 123.
In our little model, we have content_type and content_id which unfortunately map to two ints, where the int in content_type further points to a ContentType model that -- to further complicate things -- dont map to Rails-ey types ('some_type' but rather django-ey 'some type class'.
It's a mess.
Is there any way to override the value used in looking in a polymorphic association (e.g. instead of using 'some_class', use 11) -- but just for the association? There is an answer for a problem somewhat similar to ours, but it is 4 years old and it overrides association_class. We still use some of this strange Django voodoo elsewhere in our codebase, so overrides feel like they'd cause more problems than solve.


text:
Q: Rails 4: Error messages not displaying with Bootstrap classes In my application.html.erb file, I have:

  <% flash.each do | type, message | %>
  <div class="alert <%= flash_class(type) %>">
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
      ×</button>
      <%= message %>

  <% end %>

  <%= yield %>

I have the flash_class as a helper method:
module ApplicationHelper
  def flash_class(type)
    case type
    when :alert
     "alert-error"
    when :notice
     "alert-success"
    else
     ""
    end
  end
end

Though what happens is the class isn't being appended in the HTML. When I create an error, the 'alert-error' class isn't added on:

Any ideas why that might be the case?

A: You might be sending in String for type instead of Symbol in the flash_class method.
An easy fix would be calling type.to_sym in the flash_class helper method.


text:
Q: System of Non-Linear ODE Does anyone have any clue of how to find an analytical solution for the following system:
$$
\frac{dF_1}{dt}=(p+qF_1-rF_2)(1-F_1)
$$
$$
\frac{dF_2}{dt}=vF_1(1-F_2)
$$
$p$, $q$, $r$ and $v$ are constants. $F_1(0)=F_2(0)=0$.

A: here is my attempt at a solution:
split the system of two equations with the eqaution for $F_1$ decoupled from $F_2$ as
$$\frac{dF_1}{dt} = \frac{1-F_1}{F_1}\mbox{ and }\frac{dF_2}{dt} = \frac{\nu(1-F_2)}{p+qF_1 - rF_2}.$$
we can solve $-F_1 + \ln(1-F_1) = t$ for $F_1.$ too bad no explicit solution for $F_1.$
i will see if can go any farther with this.


text:
Q: Converting multiple docx files asynchronously to pdf using headless libreoffice in asp.net core I have put together the following code below to convert some docx files to pdf. Since it is a heavy operation I figured I would do this asynchronously since they document isnt used right away for anything else and is for visual purposes only on my front end which I account for loading in javascript.
My code is as follows:
public static void ConvertToPDF(string PathToItemToConvert, string PathToLibrePortable)
{

        try
        {
            string fileName = Path.GetFileName(PathToItemToConvert);
            string fileDir = Path.GetDirectoryName(PathToItemToConvert);

            var pdfProcess = new Process();
            pdfProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            pdfProcess.StartInfo.FileName = PathToLibrePortable;
            pdfProcess.StartInfo.Arguments =
                String.Format("--norestore --nofirststartwizard --headless --convert-to pdf  \"{0}\""
                                        , fileName);
            pdfProcess.StartInfo.WorkingDirectory = fileDir;
            pdfProcess.StartInfo.RedirectStandardOutput = true;
            pdfProcess.StartInfo.RedirectStandardError = true;
            pdfProcess.StartInfo.UseShellExecute = false;
            pdfProcess.Start();

            string output = pdfProcess.StandardOutput.ReadToEnd();

        }
        catch (Exception ex)
        {
            //log error
        }
}

I use it in the following fashion in an API as follows:
public async Task<ActionResult> ConvertDocs()
{
    await Task.Run(() =>
    {
        MyTools.ConvertToPDF(SomeFilePath, locationOfLibreOfficeSoffice);
    });
    await Task.Run(() =>
    {
        MyTools.ConvertToPDF(AnotherFilePath, locationOfLibreOfficeSoffice);
    });
}

This does not draw any errors but the second pdf is never created. If I comment out the other pdf code the second one will create. Its almost as if libreoffice cannot convert two pdfs at once despite I am starting separate threads with Task.Run(). Is there a way to do this or am I messing up something?


text:
Q: How to instal Window 10 on an External drive for a MacBook Pro 2019 I read several articles and watched several YouTube videos about how to make a bootable Windows 10 on an external SSD using Bootcamp.  However, all of the tutorials are using either an iMac or older MacBook Pro.  I haven't seen one with new MacBook Pro yet.
for example this guide.
Why do all of these tutorials not work on my new MacBook? These ways are expired?
see this question from the Apple Support Communities.

A: This is based on my own experience of installing Windows 10 on an external drive:
Step 1: Download a virtual machine to run Windows on. I used VMWare Fusion and used a 30-day trial. You do not need to do this if you already have a computer with Windows 10
Step 2: Search "windows 10 iso image" and click the first link from Microsoft. Download it.
Step 3: Open the VMWare application and upload the Windows 10 iso image onto it, and run Windows. You do not need to do this if you already have a computer with Windows 10
Step 4: Go on your virtual Windows and download WinToUSB from this: https://www.easyuefi.com/wintousb/.
Step 5: Open the WinToUSB tool and upload the same Windows 10 .iso image onto it, and choose which version to install. Connect your external drive to your Mac, make sure it connects to VMWare, and select it once it shows up on WinToUSB.
Step 6: Wait until the tool installs Windows 10 onto the external drive. While this is running, go to the Bootcamp app and ONLY download the Windows Support Software.
Step 7: Once the WinToUSB tool finishes installing, you can close out of VMWare by shutting down from the virtual Windows. The connected external drive should show up on your mac again, and drag the Windows Support Software folder into the drive.
You should now have an external drive with Windows 10 on it, and the Windows Support Software on it as well. You can boot from it by restarting and holding option and choosing the external drive. Use the Windows Support Software to install the correct Apple Drivers in the external drive when inside the Windows 10 boot.
This was the method that worked for me on an Early 2014 MacBook Air on High Sierra and should work on yours unless something in Bootcamp Assistant changed.

A: WintoUSB is great and a lot of folks recommend this app because it has a free version. However, it seems something wrong when running it on a Windows 7 machine. After selecting the USB drive, it comes to an error "Failed to run system API (0x0005001501B200000)".

Tried multiple times and still the same result.
Then I did a test on another two Windows To Go creator software and managed to install Windows 10 to external SSD via UUByte WintoUSB Pro tool.
The first step is to get a working PC or create a new virtual machine on Mac.
Then download UUByte WintoUSB Pro  (https://www.uubyte.com/win-to-usb-pro.html) and open the software. Follow the screen prompt to import Windows 10 ISO and choose the booting mode. For Mac, it is GPT+ UEFI. Wait for about 10 minutes, and a portable Windows to Go drive is ready.
Now, connect the drive to Mac and press Power + Option key to boot Mac from external USB. You will see Windows 10 setup screen when everything is fine. Follow the steps to install Windows 10 on that external drive.
Finally, activate Windows 10 and download missing drivers to make it working properly on Mac.