Transform only one axis to log10 scale with ggplot2
The simplest is to just give the 'trans' (formerly 'formatter' argument the name of the log function:
m + geom_boxplot() + scale_y_continuous(trans='log10')
EDIT:
Or if you don't like that, then either of these appears to give different but useful results:
m <- ggplot(diamonds, aes(y = price, x = color), log="y")
m + geom_boxplot()
m <- ggplot(diamonds, aes(y = price, x = color), log10="y")
m + geom_boxplot()
EDIT2 & 3:
Further experiments (after discarding the one that attempted successfully to put "$" signs in front of logged values):
fmtExpLg10 <- function(x) paste(round_any(10^x/1000, 0.01) , "K $", sep="")
ggplot(diamonds, aes(color, log10(price))) +
geom_boxplot() +
scale_y_continuous("Price, log10-scaling", trans = fmtExpLg10)
Note added mid 2017 in comment about package syntax change:
scale_y_continuous(formatter = 'log10') is now scale_y_continuous(trans = 'log10') (ggplot2 v2.2.1)
Python: download a file from an FTP server
If you want to take advantage of recent Python versions' async features, you can use aioftp (from the same family of libraries and developers as the more popular aiohttp library). Here is a code example taken from their client tutorial:
client = aioftp.Client()
await client.connect("ftp.server.com")
await client.login("user", "pass")
await client.download("tmp/test.py", "foo.py", write_into=True)
How to install python3 version of package via pip on Ubuntu?
Old question, but none of the answers satisfies me. One of my systems is running Ubuntu 12.04 LTS and for some reason there's no package python3-pip
or python-pip
for Python 3. So here is what I've done (all commands were executed as root):
Install setuptools
for Python3 in case you haven't.
apt-get install python3-setuptools
or
aptitude install python3-setuptools
With Python 2.4+ you can invoke easy_install
with specific Python version by using python -m easy_install
. So pip
for Python 3 could be installed by:
python3 -m easy_install pip
That's it, you got pip
for Python 3. Now just invoke pip
with the specific version of Python to install package for Python 3. For example, with Python 3.2 installed on my system, I used:
pip-3.2 install [package]
Ruby on Rails: how to render a string as HTML?
@str = "<span class=\"classname\">hello</span>"
If in my view I do
<%raw @str %>
The HTML source code is <span class=\"classname\">hello</span>
where what I really want is <span class="classname">hello</span>
(without the backslashes that were escaping the double >quotes). What's the best way to "unescape" those double quotes?
Solution: use double quotes inside of single quotes (or single inside of double) to avoid escaping with a backslash.
@str = '<span class="classname">hello</span>'
<%raw @str %>
<> And Not In VB.NET
in fact the Is is really good, since to the developpers, you may want to override the operator ==, to compare with the value.
say you have a class A, operator == of A is to compare some of the field of A to the parameter. then you will be in trouble in c# to verify whether the object of A is null with following code,
A a = new A();
...
if (a != null)
it will totally wrong, you always need to use if((object)a != null)
but in vb.net you cannot write in this way, you always need to write
if not a is nothing then
or
if a isnot nothing then
which just as Christian said, vb.net does not 'expected' anything.
How does data binding work in AngularJS?
Here is an example of data binding with AngularJS, using an input field. I will explain later
HTML Code
<div ng-app="myApp" ng-controller="myCtrl" class="formInput">
<input type="text" ng-model="watchInput" Placeholder="type something"/>
<p>{{watchInput}}</p>
</div>
AngularJS Code
myApp = angular.module ("myApp", []);
myApp.controller("myCtrl", ["$scope", function($scope){
//Your Controller code goes here
}]);
As you can see in the example above, AngularJS uses ng-model
to listen and watch what happens on HTML elements, especially on input
fields. When something happens, do something. In our case, ng-model
is bind to our view, using the mustache notation {{}}
. Whatever is typed inside the input field is displayed on the screen instantly. And that's the beauty of data binding, using AngularJS in its simplest form.
Hope this helps.
See a working example here on
Codepen
What is parsing in terms that a new programmer would understand?
I'd explain parsing as the process of turning some kind of data into another kind of data.
In practice, for me this is almost always turning a string, or binary data, into a data structure inside my Program.
For example, turning
":Nick!User@Host PRIVMSG #channel :Hello!"
into (C)
struct irc_line {
char *nick;
char *user;
char *host;
char *command;
char **arguments;
char *message;
} sample = { "Nick", "User", "Host", "PRIVMSG", { "#channel" }, "Hello!" }
Check if a user has scrolled to the bottom
I used @ddanone answear and added Ajax call.
$('#mydiv').on('scroll', function(){
function infiniScroll(this);
});
function infiniScroll(mydiv){
console.log($(mydiv).scrollTop()+' + '+ $(mydiv).height()+' = '+ ($(mydiv).scrollTop() + $(mydiv).height()) +' _ '+ $(mydiv)[0].scrollHeight );
if($(mydiv).scrollTop() + $(mydiv).height() == $(mydiv)[0].scrollHeight){
console.log('bottom found');
if(!$.active){ //if there is no ajax call active ( last ajax call waiting for results ) do again my ajax call
myAjaxCall();
}
}
}
How to check if click event is already bound - JQuery
One more way - mark such buttons with a CSS class and filter:
$('#myButton:not(.bound)').addClass('bound').bind('click', onButtonClicked);
In recent jQuery versions replace bind
with on
:
$('#myButton:not(.bound)').addClass('bound').on('click', onButtonClicked);
nodejs - first argument must be a string or Buffer - when using response.write with http.request
I get this error message and it mentions options.body
I had this originally
request.post({
url: apiServerBaseUrl + '/v1/verify',
body: {
email: req.user.email
}
});
I changed it to this:
request.post({
url: apiServerBaseUrl + '/v1/verify',
body: JSON.stringify({
email: req.user.email
})
});
and it seems to work now without the error message...seems like bug though.
I think this is the more official way to do it:
request.post({
url: apiServerBaseUrl + '/v1/verify',
json: true,
body: {
email: req.user.email
}
});
How to disable an input box using angular.js
Your markup should contain an additional attribute called ng-disabled whose value should be a condition or expression that would evaluate to be either true or false.
<input data-ng-model="userInf.username" class="span12 editEmail"
type="text" placeholder="[email protected]"
pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}"
required
ng-disabled="{condition or expression}"
/>
And in the controller you may have some code that would affect the value of ng-disabled directive.
Should I use scipy.pi, numpy.pi, or math.pi?
>>> import math
>>> import numpy as np
>>> import scipy
>>> math.pi == np.pi == scipy.pi
True
So it doesn't matter, they are all the same value.
The only reason all three modules provide a pi
value is so if you are using just one of the three modules, you can conveniently have access to pi without having to import another module. They're not providing different values for pi.
How to terminate a thread when main program ends?
If you spawn a Thread like so - myThread = Thread(target = function)
- and then do myThread.start(); myThread.join()
. When CTRL-C is initiated, the main thread doesn't exit because it is waiting on that blocking myThread.join()
call. To fix this, simply put in a timeout on the .join() call. The timeout can be as long as you wish. If you want it to wait indefinitely, just put in a really long timeout, like 99999. It's also good practice to do myThread.daemon = True
so all the threads exit when the main thread(non-daemon) exits.
Refresh DataGridView when updating data source
Well, it doesn't get much better than that. Officially, you should use
dataGridView1.DataSource = typeof(List);
dataGridView1.DataSource = itemStates;
It's still a "clear/reset source" kind of solution, but I have yet to find anything else that would reliably refresh the DGV data source.
Entity Framework select distinct name
DBContext.TestAddresses.Select(m => m.NAME).Distinct();
if you have multiple column do like this:
DBContext.TestAddresses.Select(m => new {m.NAME, m.ID}).Distinct();
In this example no duplicate CategoryId and no CategoryName i hope this will help you
How to unescape HTML character entities in Java?
This did the job for me,
import org.apache.commons.lang.StringEscapeUtils;
...
String decodedXML= StringEscapeUtils.unescapeHtml(encodedXML);
or
import org.apache.commons.lang3.StringEscapeUtils;
...
String decodedXML= StringEscapeUtils.unescapeHtml4(encodedXML);
I guess its always better to use the lang3
for obvious reasons.
Hope this helps :)
Only get hash value using md5sum (without filename)
For the sake of completeness a way with sed using regex and capture group:
md5=$(md5sum "${my_iso_file}" | sed -r 's:\\*([^ ]*).*:\1:')
The regulare expression is capturing everything in a group until a space is reached. To get capture group working you need to capture everything in sed.
(More about sed and caputer groups here: https://stackoverflow.com/a/2778096/10926293)
As delimiter in sed i use colons because they are not valid in file paths and i don't have to escape the slashed in the filepath.
how to list all sub directories in a directory
show all directry and sub directories
def dir():
from glob import glob
dir = []
dir = glob("path")
def all_sub_dir(dir):
{
for item in dir:
{
b = "{}\*".format(item)
dir += glob(b)
}
print(dir)
}
Create a Cumulative Sum Column in MySQL
Using a correlated query:
SELECT t.id,
t.count,
(SELECT SUM(x.count)
FROM TABLE x
WHERE x.id <= t.id) AS cumulative_sum
FROM TABLE t
ORDER BY t.id
Using MySQL variables:
SELECT t.id,
t.count,
@running_total := @running_total + t.count AS cumulative_sum
FROM TABLE t
JOIN (SELECT @running_total := 0) r
ORDER BY t.id
Note:
- The
JOIN (SELECT @running_total := 0) r
is a cross join, and allows for variable declaration without requiring a separate SET
command.
- The table alias,
r
, is required by MySQL for any subquery/derived table/inline view
Caveats:
- MySQL specific; not portable to other databases
- The
ORDER BY
is important; it ensures the order matches the OP and can have larger implications for more complicated variable usage (IE: psuedo ROW_NUMBER/RANK functionality, which MySQL lacks)
Cannot obtain value of local or argument as it is not available at this instruction pointer, possibly because it has been optimized away
If you compile with optimizations enabled, then many variables will be removed; for example:
SomeType value = GetValue();
DoSomething(value);
here the local variable value
would typically get removed, keeping the value on the stack instead - a bit like as if you had written:
DoSomething(GetValue());
Also, if a return value isn't used at all, then it will be dropped via "pop" (rather than stored in a local via "stloc", and again; the local will not exist).
Because of this, in such a build the debugger can't get the current value of value
because it doesn't exist - it only exists for the brief instant between GetValue()
and DoSomething(...)
.
So; if you want to debug... don't use a release build! or at least, disable optimizations while you debug.
Wamp Server not goes to green color
I have same issue with IIS, i uninstalled IIS.
Type in run services.msc, I see "wampapache64" service was not running, when I start it using right click it give me error.
I just used these steps.
Click on WAMP icon select Apache -> Service -> Remove Service
Click on Wamp icon select Apache -> Service -> Install Service
Got green Wamp icon :(
Access-Control-Allow-Origin and Angular.js $http
I've had success with express and editing the res.header
. Mine matches yours pretty closely but I have a different Allow-Headers
as noted below:
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
I'm also using Angular and Node/Express, but I don't have the headers called out in the Angular code only the node/express
Black transparent overlay on image hover with only CSS?
You were close. This will work:
.image { position: relative; border: 1px solid black; width: 200px; height: 200px; }
.image img { max-width: 100%; max-height: 100%; }
.overlay { position: absolute; top: 0; left: 0; right:0; bottom:0; display: none; background-color: rgba(0,0,0,0.5); }
.image:hover .overlay { display: block; }
You needed to put the :hover
on image, and make the .overlay
cover the whole image by adding right:0;
and bottom:0
.
jsfiddle: http://jsfiddle.net/Zf5am/569/
pandas how to check dtype for all columns in a dataframe?
To go one step further, I assume you want to do something with these dtypes.
df.dtypes.to_dict()
comes in handy.
my_type = 'float64' #<---
dtypes = dataframe.dtypes.to_dict()
for col_nam, typ in dtypes.items():
if (typ != my_type): #<---
raise ValueError(f"Yikes - `dataframe['{col_name}'].dtype == {typ}` not {my_type}")
You'll find that Pandas did a really good job comparing NumPy classes and user-provided strings. For example: even things like 'double' == dataframe['col_name'].dtype
will succeed when .dtype==np.float64
.
What is the incentive for curl to release the library for free?
I'm Daniel Stenberg.
I made curl
I founded the curl project back in 1998, I wrote the initial curl version and I created libcurl. I've written more than half of all the 24,000 commits done in the source code repository up to this point in time. I'm still the lead developer of the project. To a large extent, curl is my baby.
I shipped the first version of curl as open source since I wanted to "give back" to the open source world that had given me so much code already. I had used so much open source and I wanted to be as cool as the other open source authors.
Thanks to it being open source, literally thousands of people have been able to help us out over the years and have improved the products, the documentation. the web site and just about every other detail around the project. curl and libcurl would never have become the products that they are today were they not open source. The list of contributors now surpass 1900 names and currently the list grows with a few hundred names per year.
Thanks to curl and libcurl being open source and liberally licensed, they were immediately adopted in numerous products and soon shipped by operating systems and Linux distributions everywhere thus getting a reach beyond imagination.
Thanks to them being "everywhere", available and liberally licensed they got adopted and used everywhere and by everyone. It created a defacto transfer library standard.
At an estimated six billion installations world wide, we can safely say that curl is the most widely used internet transfer library in the world. It simply would not have gone there had it not been open source. curl runs in billions of mobile phones, a billion Windows 10 installations, in a half a billion games and several hundred million TVs - and more.
Should I have released it with proprietary license instead and charged users for it? It never occured to me, and it wouldn't have worked because I would never had managed to create this kind of stellar project on my own. And projects and companies wouldn't have used it.
Why do I still work on curl?
Now, why do I and my fellow curl developers still continue to develop curl and give it away for free to the world?
- I can't speak for my fellow project team members. We all participate in this for our own reasons.
- I think it's still the right thing to do. I'm proud of what we've accomplished and I truly want to make the world a better place and I think curl does its little part in this.
- There are still bugs to fix and features to add!
- curl is free but my time is not. I still have a job and someone still has to pay someone for me to get paid every month so that I can put food on the table for my family. I charge customers and companies to help them with curl. You too can get my help for a fee, which then indirectly helps making sure that curl continues to evolve, remain free and the kick-ass product it is.
- curl was my spare time project for twenty years before I started working with it full time. I've had great jobs and worked on awesome projects. I've been in a position of luxury where I could continue to work on curl on my spare time and keep shipping a quality product for free. My work on curl has given me friends, boosted my career and taken me to places I would not have been at otherwise.
- I would not do it differently if I could back and do it again.
Am I proud of what we've done?
Yes. So insanely much.
But I'm not satisfied with this and I'm not just leaning back, happy with what we've done. I keep working on curl every single day, to improve, to fix bugs, to add features and to make sure curl keeps being the number one file transfer solution for the world even going forward.
We do mistakes along the way. We make the wrong decisions and sometimes we implement things in crazy ways. But to win in the end and to conquer the world is about patience and endurance and constantly going back and reconsidering previous decisions and correcting previous mistakes. To continuously iterate, polish off rough edges and gradually improve over time.
Never give in. Never stop. Fix bugs. Add features. Iterate. To the end of time.
For real?
Yeah. For real.
Do I ever get tired? Is it ever done?
Sure I get tired at times. Working on something every day for over twenty years isn't a paved downhill road. Sometimes there are obstacles. During times things are rough. Occasionally people are just as ugly and annoying as people can be.
But curl is my life's project and I have patience. I have thick skin and I don't give up easily. The tough times pass and most days are awesome. I get to hang out with awesome people and the reward is knowing that my code helps driving the Internet revolution everywhere is an ego boost above normal.
curl will never be "done" and so far I think work on curl is pretty much the most fun I can imagine. Yes, I still think so even after twenty years in the driver's seat. And as long as I think it's fun I intend to keep at it.
Returning http 200 OK with error within response body
HTTP Is the Protocol handling the transmission of data over the internet.
If that transmission breaks for whatever reason the HTTP error codes tell you why it can't be sent to you.
The data being transmitted is not handled by HTTP Error codes. Only the method of transmission.
HTTP can't say 'Ok, this answer is gobbledigook, but here it is'. it just says 200 OK
.
i.e : I've completed my job of getting it to you, the rest is up to you.
I know this has been answered already but I put it in words I can understand. sorry for any repetition.
YouTube iframe API: how do I control an iframe player that's already in the HTML?
Thank you Rob W for your answer.
I have been using this within a Cordova application to avoid having to load the API and so that I can easily control iframes which are loaded dynamically.
I always wanted the ability to be able to extract information from the iframe, such as the state (getPlayerState) and the time (getCurrentTime).
Rob W helped highlight how the API works using postMessage, but of course this only sends information in one direction, from our web page into the iframe. Accessing the getters requires us to listen for messages posted back to us from the iframe.
It took me some time to figure out how to tweak Rob W's answer to activate and listen to the messages returned by the iframe. I basically searched through the source code within the YouTube iframe until I found the code responsible for sending and receiving messages.
The key was changing the 'event' to 'listening', this basically gave access to all the methods which were designed to return values.
Below is my solution, please note that I have switched to 'listening' only when getters are requested, you can tweak the condition to include extra methods.
Note further that you can view all messages sent from the iframe by adding a console.log(e) to the window.onmessage. You will notice that once listening is activated you will receive constant updates which include the current time of the video. Calling getters such as getPlayerState will activate these constant updates but will only send a message involving the video state when the state has changed.
function callPlayer(iframe, func, args) {
iframe=document.getElementById(iframe);
var event = "command";
if(func.indexOf('get')>-1){
event = "listening";
}
if ( iframe&&iframe.src.indexOf('youtube.com/embed') !== -1) {
iframe.contentWindow.postMessage( JSON.stringify({
'event': event,
'func': func,
'args': args || []
}), '*');
}
}
window.onmessage = function(e){
var data = JSON.parse(e.data);
data = data.info;
if(data.currentTime){
console.log("The current time is "+data.currentTime);
}
if(data.playerState){
console.log("The player state is "+data.playerState);
}
}
Turn on torch/flash on iPhone
iWasRobbed's answer is great, except there is an AVCaptureSession running in the background all the time. On my iPhone 4s it takes about 12% CPU power according to Instrument so my app took about 1% battery in a minute. In other words if the device is prepared for AV capture it's not cheap.
Using the code below my app requires 0.187% a minute so the battery life is more than 5x longer.
This code works just fine on any device (tested on both 3GS (no flash) and 4s). Tested on 4.3 in simulator as well.
#import <AVFoundation/AVFoundation.h>
- (void) turnTorchOn:(BOOL)on {
Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
if (captureDeviceClass != nil) {
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if ([device hasTorch] && [device hasFlash]){
[device lockForConfiguration:nil];
if (on) {
[device setTorchMode:AVCaptureTorchModeOn];
[device setFlashMode:AVCaptureFlashModeOn];
torchIsOn = YES;
} else {
[device setTorchMode:AVCaptureTorchModeOff];
[device setFlashMode:AVCaptureFlashModeOff];
torchIsOn = NO;
}
[device unlockForConfiguration];
}
}
}
How to convert Nonetype to int or string?
That TypeError
only appears when you try to pass int()
None
(which is the only NoneType
value, as far as I know). I would say that your real goal should not be to convert NoneType
to int
or str
, but to figure out where/why you're getting None
instead of a number as expected, and either fix it or handle the None
properly.
How to hide action bar before activity is created, and then show it again?
you can use this :
getSupportActionBar().hide();
if it doesn't work try this one :
getActionBar().hide();
if above doesn't work try like this :
in your directory = res/values/style.xml , open style.xml -> there is attribute parent
change to parent="Theme.AppCompat.Light.DarkActionBar"
if all of it doesn't work too. i don't know anymore. but for me it works.
Is there a way to @Autowire a bean that requires constructor arguments?
An alternative would be instead of passing the parameters to the constructor you might have them as getter and setters and then in a @PostConstruct initialize the values as you want. In this case Spring will create the bean using the default constructor. An example is below
@Component
public class MyConstructorClass{
String var;
public void setVar(String var){
this.var = var;
}
public void getVar(){
return var;
}
@PostConstruct
public void init(){
setVar("var");
}
...
}
@Service
public class MyBeanService{
//field autowiring
@Autowired
MyConstructorClass myConstructorClass;
....
}
Cannot push to GitHub - keeps saying need merge
The problem with push command is that you your local and remote repository doesn't match. IF you initialize readme by default when creating new repository from git hub, then, master branch is automatically created. However, when you try to push that has no any branch. you cannot push... So, the best practice is to create repo without default readme initialization.
How do you split and unsplit a window/view in Eclipse IDE?
This is possible with the menu items Window>Editor>Toggle Split Editor.
Current shortcut for splitting is:
Azerty keyboard:
- Ctrl + _ for split horizontally, and
- Ctrl + { for split vertically.
Qwerty US keyboard:
- Ctrl + Shift + - (accessing _) for split horizontally, and
- Ctrl + Shift + [ (accessing {) for split vertically.
MacOS - Qwerty US keyboard:
- ⌘ + Shift + - (accessing _) for split horizontally, and
- ⌘ + Shift + [ (accessing {) for split vertically.
On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:
- Alt + ASCII code + Ctrl then release Alt
Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.
Example of vertical split:
PS:
- The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
- The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
- The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.
Java NIO FileChannel versus FileOutputstream performance / usefulness
I tested the performance of FileInputStream vs. FileChannel for decoding base64 encoded files. In my experients I tested rather large file and traditional io was alway a bit faster than nio.
FileChannel might have had an advantage in prior versions of the jvm because of synchonization overhead in several io related classes, but modern jvm are pretty good at removing unneeded locks.
How can I style a PHP echo text?
You cannot style a variable such as $ip['countryName']
You can only style elements like p,div, etc, or classes and ids.
If you want to style $ip['countryName'] there are several ways.
You can echo it within an element:
echo '<p id="style">'.$ip['countryName'].'</p>';
echo '<span id="style">'.$ip['countryName'].'</span>';
echo '<div id="style">'.$ip['countryName'].'</div>';
If you want to style both the variables the same style, then set a class like:
echo '<p class="style">'.$ip['cityName'].'</p>';
echo '<p class="style">'.$ip['countryName'].'</p>';
You could also embed the variables within your actual html rather than echoing them out within the code.
$city = $ip['cityName'];
$country = $ip['countryName'];
?>
<div class="style"><?php echo $city ?></div>
<div class="style"><?php echo $country?></div>
How to fix Error: laravel.log could not be opened?
If chmod does not work, you can try the following:
sudo nano /etc/php/7.x/fpm/pool.d/www.conf
Change the following paramaters:
user = www-data
group = www-data
To:
user = vagrant
group = vagrant
Remember to restart PHP FPM
sudo service php7.x-fpm restart
LINQ to SQL - How to select specific columns and return strongly typed list
Basically you are doing it the right way. However, you should use an instance of the DataContext
for querying (it's not obvious that DataContext
is an instance or the type name from your query):
var result = (from a in new DataContext().Persons
where a.Age > 18
select new Person { Name = a.Name, Age = a.Age }).ToList();
Apparently, the Person
class is your LINQ to SQL generated entity class. You should create your own class if you only want some of the columns:
class PersonInformation {
public string Name {get;set;}
public int Age {get;set;}
}
var result = (from a in new DataContext().Persons
where a.Age > 18
select new PersonInformation { Name = a.Name, Age = a.Age }).ToList();
You can freely swap var
with List<PersonInformation>
here without affecting anything (as this is what the compiler does).
Otherwise, if you are working locally with the query, I suggest considering an anonymous type:
var result = (from a in new DataContext().Persons
where a.Age > 18
select new { a.Name, a.Age }).ToList();
Note that in all of these cases, the result
is statically typed (it's type is known at compile time). The latter type is a List
of a compiler generated anonymous class similar to the PersonInformation
class I wrote above. As of C# 3.0, there's no dynamic typing in the language.
UPDATE:
If you really want to return a List<Person>
(which might or might not be the best thing to do), you can do this:
var result = from a in new DataContext().Persons
where a.Age > 18
select new { a.Name, a.Age };
List<Person> list = result.AsEnumerable()
.Select(o => new Person {
Name = o.Name,
Age = o.Age
}).ToList();
You can merge the above statements too, but I separated them for clarity.
How to build a Horizontal ListView with RecyclerView?
It's for both for Horizontal and for Vertical.
RecyclerView recyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_recycler);
recyclerView = (RecyclerView)findViewById(R.id.recyclerViewId);
RecyclAdapter adapter = new RecyclAdapter();
//Vertical RecyclerView
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
//Horizontal RecyclerView
//recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(),LinearLayoutManager.HORIZONTAL,false));
recyclerView.setAdapter(adapter);
}
How to include file in a bash shell script
Above answers are correct, but if run script in other folder, there will be some problem.
For example, the a.sh
and b.sh
are in same folder,
a include b with . ./b.sh
to include.
When run script out of the folder, for example with xx/xx/xx/a.sh
, file b.sh
will not found: ./b.sh: No such file or directory
.
I use
. $(dirname "$0")/b.sh
how to zip a folder itself using java
I have modified the above solutions and replaced Files.walk
with Files.list
. This also assumes the directory you are zipping only contains file and not any sub directories.
private void zipDirectory(Path dirPath) throws IOException {
String zipFilePathStr = dirPath.toString() + ".zip";
Path zipFilePath = Files.createFile(Paths.get(zipFilePathStr));
try (ZipOutputStream zs = new ZipOutputStream(Files.newOutputStream(zipFilePath))) {
Files.list(dirPath)
.filter(filePath-> !Files.isDirectory(filePath))
.forEach(filePath-> {
ZipEntry zipEntry = new ZipEntry(dirPath.relativize(filePath).toString());
try {
zs.putNextEntry(zipEntry);
Files.copy(filePath, zs);
zs.closeEntry();
}
catch (IOException e) {
System.err.println(e);
}
});
}
}
Docker and securing passwords
My approach seems to work, but is probably naive. Tell me why it is wrong.
ARGs set during docker build are exposed by the history subcommand, so no go there. However, when running a container, environment variables given in the run command are available to the container, but are not part of the image.
So, in the Dockerfile, do setup that does not involve secret data. Set a CMD of something like /root/finish.sh
. In the run command, use environmental variables to send secret data into the container. finish.sh
uses the variables essentially to finish build tasks.
To make managing the secret data easier, put it into a file that is loaded by docker run with the --env-file
switch. Of course, keep the file secret. .gitignore
and such.
For me, finish.sh
runs a Python program. It checks to make sure it hasn't run before, then finishes the setup (e.g., copies the database name into Django's settings.py
).
Copy file or directories recursively in Python
The python shutil.copytree method its a mess. I've done one that works correctly:
def copydirectorykut(src, dst):
os.chdir(dst)
list=os.listdir(src)
nom= src+'.txt'
fitx= open(nom, 'w')
for item in list:
fitx.write("%s\n" % item)
fitx.close()
f = open(nom,'r')
for line in f.readlines():
if "." in line:
shutil.copy(src+'/'+line[:-1],dst+'/'+line[:-1])
else:
if not os.path.exists(dst+'/'+line[:-1]):
os.makedirs(dst+'/'+line[:-1])
copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
f.close()
os.remove(nom)
os.chdir('..')
browser.msie error after update to jQuery 1.9.1
Since $.browser is deprecated, here is an alternative solution:
/**
* Returns the version of Internet Explorer or a -1
* (indicating the use of another browser).
*/
function getInternetExplorerVersion()
{
var rv = -1; // Return value assumes failure.
if (navigator.appName == 'Microsoft Internet Explorer')
{
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat( RegExp.$1 );
}
return rv;
}
function checkVersion()
{
var msg = "You're not using Internet Explorer.";
var ver = getInternetExplorerVersion();
if ( ver > -1 )
{
if ( ver >= 8.0 )
msg = "You're using a recent copy of Internet Explorer."
else
msg = "You should upgrade your copy of Internet Explorer.";
}
alert( msg );
}
Source
However, the reason that its deprecated is because jQuery wants you to use feature detection instead.
An example:
$("p").html("This frame uses the W3C box model: <span>" +
jQuery.support.boxModel + "</span>");
And last but not least, the most reliable way to check IE versions:
// ----------------------------------------------------------
// A short snippet for detecting versions of IE in JavaScript
// without resorting to user-agent sniffing
// ----------------------------------------------------------
// If you're not in IE (or IE version is less than 5) then:
// ie === undefined
// If you're in IE (>=5) then you can determine which version:
// ie === 7; // IE7
// Thus, to detect IE:
// if (ie) {}
// And to detect the version:
// ie === 6 // IE6
// ie > 7 // IE8, IE9 ...
// ie < 9 // Anything less than IE9
// ----------------------------------------------------------
// UPDATE: Now using Live NodeList idea from @jdalton
var ie = (function(){
var undef,
v = 3,
div = document.createElement('div'),
all = div.getElementsByTagName('i');
while (
div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
all[0]
);
return v > 4 ? v : undef;
}());
Show or hide element in React
class FormPage extends React.Component{
constructor(props){
super(props);
this.state = {
hidediv: false
}
}
handleClick = (){
this.setState({
hidediv: true
});
}
render(){
return(
<div>
<div className="date-range" hidden = {this.state.hidediv}>
<input type="submit" value="Search" onClick={this.handleClick} />
</div>
<div id="results" className="search-results" hidden = {!this.state.hidediv}>
Some Results
</div>
</div>
);
}
}
200 PORT command successful. Consider using PASV. 425 Failed to establish connection
You are using the FTP in an active mode.
Setting up the FTP in the active mode can be cumbersome nowadays due to firewalls and NATs.
It's likely because of your local firewall or NAT that the server was not able to connect back to your client to establish data transfer connection.
Or your client is not aware of its external IP address and provides an internal address instead to the server (in PORT
command), which the server is obviously not able to use. But it should not be the case, as vsftpd by default rejects data transfer address not identical to source address of FTP control connection (the port_promiscuous
directive).
See my article Network Configuration for Active Mode.
If possible, you should use a passive mode as it typically requires no additional setup on a client-side. That's also what the server suggested you by "Consider using PASV". The PASV
is an FTP command used to enter the passive mode.
Unfortunately Windows FTP command-line client (the ftp.exe
) does not support passive mode at all. It makes it pretty useless nowadays.
Use any other 3rd party Windows FTP command-line client instead. Most other support the passive mode.
For example WinSCP FTP client defaults to the passive mode and there's a guide available for converting Windows FTP script to WinSCP script.
(I'm the author of WinSCP)
Expression must be a modifiable L-value
lvalue
means "left value" -- it should be assignable. You cannot change the value of text
since it is an array, not a pointer.
Either declare it as char pointer (in this case it's better to declare it as const char*
):
const char *text;
if(number == 2)
text = "awesome";
else
text = "you fail";
Or use strcpy:
char text[60];
if(number == 2)
strcpy(text, "awesome");
else
strcpy(text, "you fail");
Position Absolute + Scrolling
You need to wrap the text in a div
element and include the absolutely positioned element inside of it.
<div class="container">
<div class="inner">
<div class="full-height"></div>
[Your text here]
</div>
</div>
Css:
.inner: { position: relative; height: auto; }
.full-height: { height: 100%; }
Setting the inner div's position to relative
makes the absolutely position elements inside of it base their position and height on it rather than on the .container
div, which has a fixed height. Without the inner, relatively positioned div
, the .full-height
div will always calculate its dimensions and position based on .container
.
_x000D_
_x000D_
* {_x000D_
box-sizing: border-box;_x000D_
}_x000D_
_x000D_
.container {_x000D_
position: relative;_x000D_
border: solid 1px red;_x000D_
height: 256px;_x000D_
width: 256px;_x000D_
overflow: auto;_x000D_
float: left;_x000D_
margin-right: 16px;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
position: relative;_x000D_
height: auto;_x000D_
}_x000D_
_x000D_
.full-height {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
right: 128px;_x000D_
bottom: 0;_x000D_
height: 100%;_x000D_
background: blue;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="full-height">_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="container">_x000D_
<div class="inner">_x000D_
<div class="full-height">_x000D_
</div>_x000D_
_x000D_
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur mollitia maxime facere quae cumque perferendis cum atque quia repellendus rerum eaque quod quibusdam incidunt blanditiis possimus temporibus reiciendis deserunt sequi eveniet necessitatibus_x000D_
maiores quas assumenda voluptate qui odio laboriosam totam repudiandae? Doloremque dignissimos voluptatibus eveniet rem quasi minus ex cumque esse culpa cupiditate cum architecto! Facilis deleniti unde suscipit minima obcaecati vero ea soluta odio_x000D_
cupiditate placeat vitae nesciunt quis alias dolorum nemo sint facere. Deleniti itaque incidunt eligendi qui nemo corporis ducimus beatae consequatur est iusto dolorum consequuntur vero debitis saepe voluptatem impedit sint ea numquam quia voluptate_x000D_
quidem._x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
http://jsfiddle.net/M5cTN/
How can I enable CORS on Django REST Framework
pip install django-cors-headers
and then add it to your installed apps:
INSTALLED_APPS = (
...
'corsheaders',
...
)
You will also need to add a middleware class to listen in on responses:
MIDDLEWARE_CLASSES = (
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
)
CORS_ORIGIN_ALLOW_ALL = True # If this is used then `CORS_ORIGIN_WHITELIST` will not have any effect
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = [
'http://localhost:3030',
] # If this is used, then not need to use `CORS_ORIGIN_ALLOW_ALL = True`
CORS_ORIGIN_REGEX_WHITELIST = [
'http://localhost:3030',
]
more details: https://github.com/ottoyiu/django-cors-headers/#configuration
read the official documentation can resolve almost all problem
Export to csv in jQuery
Hope the following demo can help you out.
_x000D_
_x000D_
$(function() {_x000D_
$("button").on('click', function() {_x000D_
var data = "";_x000D_
var tableData = [];_x000D_
var rows = $("table tr");_x000D_
rows.each(function(index, row) {_x000D_
var rowData = [];_x000D_
$(row).find("th, td").each(function(index, column) {_x000D_
rowData.push(column.innerText);_x000D_
});_x000D_
tableData.push(rowData.join(","));_x000D_
});_x000D_
data += tableData.join("\n");_x000D_
$(document.body).append('<a id="download-link" download="data.csv" href=' + URL.createObjectURL(new Blob([data], {_x000D_
type: "text/csv"_x000D_
})) + '/>');_x000D_
_x000D_
_x000D_
$('#download-link')[0].click();_x000D_
$('#download-link').remove();_x000D_
});_x000D_
});
_x000D_
table {_x000D_
border-collapse: collapse;_x000D_
}_x000D_
_x000D_
td,_x000D_
th {_x000D_
border: 1px solid #aaa;_x000D_
padding: 0.5rem;_x000D_
text-align: left;_x000D_
}_x000D_
_x000D_
td {_x000D_
font-size: 0.875rem;_x000D_
}_x000D_
_x000D_
.btn-group {_x000D_
padding: 1rem 0;_x000D_
}_x000D_
_x000D_
button {_x000D_
background-color: #fff;_x000D_
border: 1px solid #000;_x000D_
margin-top: 0.5rem;_x000D_
border-radius: 3px;_x000D_
padding: 0.5rem 1rem;_x000D_
font-size: 1rem;_x000D_
}_x000D_
_x000D_
button:hover {_x000D_
cursor: pointer;_x000D_
background-color: #000;_x000D_
color: #fff;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div id='PrintDiv'>_x000D_
<table id="mainTable">_x000D_
<tr>_x000D_
<td>Col1</td>_x000D_
<td>Col2</td>_x000D_
<td>Col3</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Val1</td>_x000D_
<td>Val2</td>_x000D_
<td>Val3</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Val11</td>_x000D_
<td>Val22</td>_x000D_
<td>Val33</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Val111</td>_x000D_
<td>Val222</td>_x000D_
<td>Val333</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>_x000D_
_x000D_
<div class="btn-group">_x000D_
<button>csv</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_
How to change Vagrant 'default' machine name?
In case there are many people using your vagrant file - you might want to set name dynamically. Below is the example how to do it using username from your HOST machine as the name of the box and hostname:
require 'etc'
vagrant_name = "yourProjectName-" + Etc.getlogin
Vagrant.configure("2") do |config|
config.vm.box = "ubuntu/xenial64"
config.vm.hostname = vagrant_name
config.vm.provider "virtualbox" do |v|
v.name = vagrant_name
end
end
Angular2 - TypeScript : Increment a number after timeout in AppComponent
This is not valid TypeScript code. You can not have method invocations in the body of a class.
// INVALID CODE
export class AppComponent {
public n: number = 1;
setTimeout(function() {
n = n + 10;
}, 1000);
}
Instead move the setTimeout
call to the constructor
of the class. Additionally, use the arrow function =>
to gain access to this
.
export class AppComponent {
public n: number = 1;
constructor() {
setTimeout(() => {
this.n = this.n + 10;
}, 1000);
}
}
In TypeScript, you can only refer to class properties or methods via this
. That's why the arrow function =>
is important.
Convert integer to binary in C#
This might be helpful if you want a concise function that you can call from your main method, inside your class. You may still need to call int.Parse(toBinary(someint))
if you require a number instead of a string but I find this method work pretty well. Additionally, this can be adjusted to use a for
loop instead of a do
-while
if you'd prefer.
public static string toBinary(int base10)
{
string binary = "";
do {
binary = (base10 % 2) + binary;
base10 /= 2;
}
while (base10 > 0);
return binary;
}
toBinary(10)
returns the string "1010"
.
How does paintComponent work?
Calling object.paintComponent(g)
is an error.
Instead this method is called automatically when the panel is created. The paintComponent()
method can also be called explicitly by the repaint()
method defined in Component
class.
The effect of calling repaint()
is that Swing automatically clears the graphic on the panel and executes the paintComponent
method to redraw the graphics on this panel.
Checking for a null int value from a Java ResultSet
You can call this method using the resultSet and the column name having Number type. It will either return the Integer value, or null. There will be no zeros returned for empty value in the database
private Integer getIntWithNullCheck(ResultSet rset, String columnName) {
try {
Integer value = rset.getInt(columnName);
return rset.wasNull() ? null : value;
} catch (Exception e) {
return null;
}
}
How to disable Python warnings?
If you know what are the useless warnings you usually encounter, you can filter them by message.
import warnings
#ignore by message
warnings.filterwarnings("ignore", message="divide by zero encountered in divide")
#part of the message is also okay
warnings.filterwarnings("ignore", message="divide by zero encountered")
warnings.filterwarnings("ignore", message="invalid value encountered")
Output single character in C
char variable = 'x'; // the variable is a char whose value is lowercase x
printf("<%c>", variable); // print it with angle brackets around the character
Set auto height and width in CSS/HTML for different screen sizes
///UPDATED DEMO 2 WATCH SOLUTION////
I hope that is the solution you're looking for! DEMO1 DEMO2
With that solution the only scrollbar in the page is on your contents section in the middle!
In that section build your structure with a sidebar or whatever you want!
You can do that with that code here:
<div class="navTop">
<h1>Title</h1>
<nav>Dynamic menu</nav>
</div>
<div class="container">
<section>THE CONTENTS GOES HERE</section>
</div>
<footer class="bottomFooter">
Footer
</footer>
With that css:
.navTop{
width:100%;
border:1px solid black;
float:left;
}
.container{
width:100%;
float:left;
overflow:scroll;
}
.bottomFooter{
float:left;
border:1px solid black;
width:100%;
}
And a bit of jquery:
$(document).ready(function() {
function setHeight() {
var top = $('.navTop').outerHeight();
var bottom = $('footer').outerHeight();
var totHeight = $(window).height();
$('section').css({
'height': totHeight - top - bottom + 'px'
});
}
$(window).on('resize', function() { setHeight(); });
setHeight();
});
DEMO 1
If you don't want jquery
<div class="row">
<h1>Title</h1>
<nav>NAV</nav>
</div>
<div class="row container">
<div class="content">
<div class="sidebar">
SIDEBAR
</div>
<div class="contents">
CONTENTS
</div>
</div>
<footer>Footer</footer>
</div>
CSS
*{
margin:0;padding:0;
}
html,body{
height:100%;
width:100%;
}
body{
display:table;
}
.row{
width: 100%;
background: yellow;
display:table-row;
}
.container{
background: pink;
height:100%;
}
.content {
display: block;
overflow:auto;
height:100%;
padding-bottom: 40px;
box-sizing: border-box;
}
footer{
position: fixed;
bottom: 0;
left: 0;
background: yellow;
height: 40px;
line-height: 40px;
width: 100%;
text-align: center;
}
.sidebar{
float:left;
background:green;
height:100%;
width:10%;
}
.contents{
float:left;
background:red;
height:100%;
width:90%;
overflow:auto;
}
DEMO 2
Converting a SimpleXML Object to an Array
Just (array)
is missing in your code before the simplexml object:
...
$xml = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA);
$array = json_decode(json_encode((array)$xml), TRUE);
^^^^^^^
...
TabLayout tab selection
You can set TabLayout position using following functions
public void setTab(){
tabLayout.setScrollPosition(YOUR_SCROLL_INDEX,0,true);
tabLayout.setSelected(true);
}
Connection refused on docker container
In Windows, you also normally need to run command line as administrator.
As standard-user:
docker build -t myimage -f Dockerfile .
Sending build context to Docker daemon 106.8MB
Step 1/1 : FROM mcr.microsoft.com/dotnet/core/runtime:3.0
Get https://mcr.microsoft.com/v2/: dial tcp: lookup mcr.microsoft.com on [::1]:53: read udp [::1]:45540->[::1]:53: read:
>>>connection refused
But as an administrator.
docker build -t myimage -f Dockerfile .
Sending build context to Docker daemon 106.8MB
Step 1/1 : FROM mcr.microsoft.com/dotnet/core/runtime:3.0
3.0: Pulling from dotnet/core/runtime
68ced04f60ab: Pull complete e936bd534ffb: Pull complete caf64655bcbb: Pull complete d1927dbcbcab: Pull complete Digest: sha256:e0c67764f530a9cad29a09816614c0129af8fe3bd550eeb4e44cdaddf8f5aa40
Status: Downloaded newer image for mcr.microsoft.com/dotnet/core/runtime:3.0
---> f059cd71a22a
Successfully built f059cd71a22a
Successfully tagged myimage:latest
Use python requests to download CSV
From a little search, that I understand the file should be opened in universal newline mode, which you cannot directly do with a response content (I guess).
To finish the task, you can either save the downloaded content to a temporary file, or process it in memory.
Save as file:
import requests
import csv
import os
temp_file_name = 'temp_csv.csv'
url = 'http://url.to/file.csv'
download = requests.get(url)
with open(temp_file_name, 'w') as temp_file:
temp_file.writelines(download.content)
with open(temp_file_name, 'rU') as temp_file:
csv_reader = csv.reader(temp_file, dialect=csv.excel_tab)
for line in csv_reader:
print line
# delete the temp file after process
os.remove(temp_file_name)
In memory:
(To be updated)
How do I concatenate text in a query in sql server?
If you are using SQL Server 2005 (or greater) you might want to consider switching to NVARCHAR(MAX) in your table definition; TEXT, NTEXT, and IMAGE data types of SQL Server 2000 will be deprecated in future versions of SQL Server. SQL Server 2005 provides backward compatibility to data types, but you should probably be using VARCHAR(MAX), NVARCHAR(MAX), and VARBINARY(MAX) instead.
How can I merge two commits into one if I already started rebase?
First you should check how many commits you have:
git log
There are two status:
One is that there are only two commits:
For example:
commit A
commit B
(In this case, you can't use git rebase to do) you need to do following.
$ git reset --soft HEAD^1
$ git commit --amend
Another is that there are more than two commits; you want to merge commit C and D.
For example:
commit A
commit B
commit C
commit D
(under this condition, you can use git rebase)
git rebase -i B
And than use "squash" to do. The rest thins is very easy. If you still don't know, please read http://zerodie.github.io/blog/2012/01/19/git-rebase-i/
Fork() function in C
int a = fork();
Creates a duplicate process "clone?", which shares the execution stack. The difference between the parent and the child is the return value of the function.
The child getting 0 returned, and the parent getting the new pid.
Each time the addresses and the values of the stack variables are copied. The execution continues at the point it already got to in the code.
At each fork
, only one value is modified - the return value from fork
.
Using multiple property files (via PropertyPlaceholderConfigurer) in multiple projects/modules
I know that this is an old question, but the ignore-unresolvable
property was not working for me and I didn't know why.
The problem was that I needed an external resource (something like location="file:${CATALINA_HOME}/conf/db-override.properties"
) and the ignore-unresolvable="true"
does not do the job in this case.
What one needs to do for ignoring a missing external resource is:
ignore-resource-not-found="true"
Just in case anyone else bumps into this.
Turn off warnings and errors on PHP and MySQL
Always show errors on a testing server. Never show errors on a production server.
Write a script to determine whether the page is on a local, testing, or live server, and set $state to "local", "testing", or "live". Then:
if( $state == "local" || $state == "testing" )
{
ini_set( "display_errors", "1" );
error_reporting( E_ALL & ~E_NOTICE );
}
else
{
error_reporting( 0 );
}
What is this spring.jpa.open-in-view=true property in Spring Boot?
The OSIV Anti-Pattern
Instead of letting the business layer decide how it’s best to fetch all the associations that are needed by the View layer, OSIV (Open Session in View) forces the Persistence Context to stay open so that the View layer can trigger the Proxy initialization, as illustrated by the following diagram.
- The
OpenSessionInViewFilter
calls the openSession
method of the underlying SessionFactory
and obtains a new Session
.
- The
Session
is bound to the TransactionSynchronizationManager
.
- The
OpenSessionInViewFilter
calls the doFilter
of the javax.servlet.FilterChain
object reference and the request is further processed
- The
DispatcherServlet
is called, and it routes the HTTP request to the underlying PostController
.
- The
PostController
calls the PostService
to get a list of Post
entities.
- The
PostService
opens a new transaction, and the HibernateTransactionManager
reuses the same Session
that was opened by the OpenSessionInViewFilter
.
- The
PostDAO
fetches the list of Post
entities without initializing any lazy association.
- The
PostService
commits the underlying transaction, but the Session
is not closed because it was opened externally.
- The
DispatcherServlet
starts rendering the UI, which, in turn, navigates the lazy associations and triggers their initialization.
- The
OpenSessionInViewFilter
can close the Session
, and the underlying database connection is released as well.
At first glance, this might not look like a terrible thing to do, but, once you view it from a database perspective, a series of flaws start to become more obvious.
The service layer opens and closes a database transaction, but afterward, there is no explicit transaction going on. For this reason, every additional statement issued from the UI rendering phase is executed in auto-commit mode. Auto-commit puts pressure on the database server because each transaction issues a commit at end, which can trigger a transaction log flush to disk. One optimization would be to mark the Connection
as read-only which would allow the database server to avoid writing to the transaction log.
There is no separation of concerns anymore because statements are generated both by the service layer and by the UI rendering process. Writing integration tests that assert the number of statements being generated requires going through all layers (web, service, DAO) while having the application deployed on a web container. Even when using an in-memory database (e.g. HSQLDB) and a lightweight webserver (e.g. Jetty), these integration tests are going to be slower to execute than if layers were separated and the back-end integration tests used the database, while the front-end integration tests were mocking the service layer altogether.
The UI layer is limited to navigating associations which can, in turn, trigger N+1 query problems. Although Hibernate offers @BatchSize
for fetching associations in batches, and FetchMode.SUBSELECT
to cope with this scenario, the annotations are affecting the default fetch plan, so they get applied to every business use case. For this reason, a data access layer query is much more suitable because it can be tailored to the current use case data fetch requirements.
Last but not least, the database connection is held throughout the UI rendering phase which increases connection lease time and limits the overall transaction throughput due to congestion on the database connection pool. The more the connection is held, the more other concurrent requests are going to wait to get a connection from the pool.
Spring Boot and OSIV
Unfortunately, OSIV (Open Session in View) is enabled by default in Spring Boot, and OSIV is really a bad idea from a performance and scalability perspective.
So, make sure that in the application.properties
configuration file, you have the following entry:
spring.jpa.open-in-view=false
This will disable OSIV so that you can handle the LazyInitializationException
the right way.
Starting with version 2.0, Spring Boot issues a warning when OSIV is enabled by default, so you can discover this problem long before it affects a production system.
CURRENT_DATE/CURDATE() not working as default DATE value
declare your date column as NOT NULL, but without a default. Then add this trigger:
USE `ddb`;
DELIMITER $$
CREATE TRIGGER `default_date` BEFORE INSERT ON `dtable` FOR EACH ROW
if ( isnull(new.query_date) ) then
set new.query_date=curdate();
end if;
$$
delimiter ;
How to read/write a boolean when implementing the Parcelable interface?
Short and simple implementation in Kotlin, with nullable support:
Add methods to Parcel
fun Parcel.writeBoolean(flag: Boolean?) {
when(flag) {
true -> writeInt(1)
false -> writeInt(0)
else -> writeInt(-1)
}
}
fun Parcel.readBoolean(): Boolean? {
return when(readInt()) {
1 -> true
0 -> false
else -> null
}
}
And use it:
parcel.writeBoolean(isUserActive)
parcel.readBoolean() // For true, false, null
parcel.readBoolean()!! // For only true and false
how to set the background image fit to browser using html
Try This Code:
It may help you
<html>
<head>
<style>
body
{
background:url('images/top-left.jpg') no-repeat center center fixed;
background-size: cover;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<form action="LoginCheck.jsp"method="post">
</br>Username:<input type="text" name="username">
</br>Password:<input type="password" name="password">
</br>
<input type="submit" value="Submit">
</form>
</center>
</body>
</html>
Dynamically Add C# Properties at Runtime
Have you taken a look at ExpandoObject?
see: http://blogs.msdn.com/b/csharpfaq/archive/2009/10/01/dynamic-in-c-4-0-introducing-the-expandoobject.aspx
From MSDN:
The ExpandoObject class enables you to add and delete members of its instances at run time and also to set and get values of these members. This class supports dynamic binding, which enables you to use standard syntax like sampleObject.sampleMember instead of more complex syntax like sampleObject.GetAttribute("sampleMember").
Allowing you to do cool things like:
dynamic dynObject = new ExpandoObject();
dynObject.SomeDynamicProperty = "Hello!";
dynObject.SomeDynamicAction = (msg) =>
{
Console.WriteLine(msg);
};
dynObject.SomeDynamicAction(dynObject.SomeDynamicProperty);
Based on your actual code you may be more interested in:
public static dynamic GetDynamicObject(Dictionary<string, object> properties)
{
return new MyDynObject(properties);
}
public sealed class MyDynObject : DynamicObject
{
private readonly Dictionary<string, object> _properties;
public MyDynObject(Dictionary<string, object> properties)
{
_properties = properties;
}
public override IEnumerable<string> GetDynamicMemberNames()
{
return _properties.Keys;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (_properties.ContainsKey(binder.Name))
{
result = _properties[binder.Name];
return true;
}
else
{
result = null;
return false;
}
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
if (_properties.ContainsKey(binder.Name))
{
_properties[binder.Name] = value;
return true;
}
else
{
return false;
}
}
}
That way you just need:
var dyn = GetDynamicObject(new Dictionary<string, object>()
{
{"prop1", 12},
});
Console.WriteLine(dyn.prop1);
dyn.prop1 = 150;
Deriving from DynamicObject allows you to come up with your own strategy for handling these dynamic member requests, beware there be monsters here: the compiler will not be able to verify a lot of your dynamic calls and you won't get intellisense, so just keep that in mind.
angular.service vs angular.factory
The clue is in the name
Services and factories are similar to one another. Both will yield a singleton object that can be injected into other objects, and so are often used interchangeably.
They are intended to be used semantically to implement different design patterns.
Services are for implementing a service pattern
A service pattern is one in which your application is broken into logically consistent units of functionality. An example might be an API accessor, or a set of business logic.
This is especially important in Angular because Angular models are typically just JSON objects pulled from a server, and so we need somewhere to put our business logic.
Here is a Github service for example. It knows how to talk to Github. It knows about urls and methods. We can inject it into a controller, and it will generate and return a promise.
(function() {
var base = "https://api.github.com";
angular.module('github', [])
.service('githubService', function( $http ) {
this.getEvents: function() {
var url = [
base,
'/events',
'?callback=JSON_CALLBACK'
].join('');
return $http.jsonp(url);
}
});
)();
Factories implement a factory pattern
Factories, on the other hand are intended to implement a factory pattern. A factory pattern in one in which we use a factory function to generate an object. Typically we might use this for building models. Here is a factory which returns an Author constructor:
angular.module('user', [])
.factory('User', function($resource) {
var url = 'http://simple-api.herokuapp.com/api/v1/authors/:id'
return $resource(url);
})
We would make use of this like so:
angular.module('app', ['user'])
.controller('authorController', function($scope, User) {
$scope.user = new User();
})
Note that factories also return singletons.
Factories can return a constructor
Because a factory simply returns an object, it can return any type of object you like, including a constructor function, as we see above.
Factories return an object; services are newable
Another technical difference is in the way services and factories are composed. A service function will be newed to generate the object. A factory function will be called and will return the object.
- Services are newable constructors.
- Factories are simply called and return an object.
This means that in a service, we append to "this" which, in the context of a constructor, will point to the object under construction.
To illustrate this, here is the same simple object created using a service and a factory:
angular.module('app', [])
.service('helloService', function() {
this.sayHello = function() {
return "Hello!";
}
})
.factory('helloFactory', function() {
return {
sayHello: function() {
return "Hello!";
}
}
});
How to format a URL to get a file from Amazon S3?
Documentation here, and I'll use the Frankfurt region as an example.
There are 2 different URL styles:
But this url does not work:
The message is explicit: The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.
I may be talking about another problem because I'm not getting NoSuchKey
error but I suspect the error message has been made clearer over time.
What does O(log n) mean exactly?
First I recommend you to read following book;
Algorithms (4th Edition)
Here is some functions and their expected complexities. Numbers are indicating statement execution frequencies.
Following Big-O Complexity Chart also taken from bigocheatsheet
Lastly very simple showcase there is shows how it is calculated;
Anatomy of a program’s statement execution frequencies.
Analyzing the running time of a program (example).
What possibilities can cause "Service Unavailable 503" error?
Primarily what that means is that there are too many concurrent requests and further that they exceed the default 1000 queued requests. That is there are 1000 or more queued requests to your website.
This could happen (assuming there are no faults in your app) if there are long running tasks and as a result the Request queue is backed up.
Depending on how the application pool has been set up you may see this kind of thing. Typically, the app pool's Process Model has an item called Maximum Worker Processes. By default this is 1. If you set it to more than 1 (typically up to a max of the number of cores on the hardware) you may not see this happen.
Just to note that unless the site is extremely busy you should not see this. If you do, it's really pointing to long running tasks
How to correctly use the ASP.NET FileUpload control
I have noticed that when intellisence doesn't work for an object there is usually an error somewhere in the class above line you are working on.
The other option is that you didn't instantiated the FileUpload object as an instance variable. make sure the code:
FileUpload fileUpload = new FileUpload();
is not inside a function in your code behind.
pip is not able to install packages correctly: Permission denied error
Set up a virtualenv:
% curl -kLso /tmp/get-pip.py https://bootstrap.pypa.io/get-pip.py
% sudo python /tmp/get-pip.py
These commands install pip into the global site-packages directory.
% sudo pip install virtualenv
and ditto for virtualenv:
% mkdir -p ~/.virtualenvs
I like my virtualenvs under one tree in my home directory called .virtualenvs
% virtualenv ~/.virtualenvs/lxmltest
Creates a virtualenv.
% . ~/.virtualenvs/lxmltest/bin/activate
Removes the need to specify the full path to pip/python in this virtualenv.
% pip install lxml
Alternatively execute ~/.virtualenvs/lxmltest/bin/pip install lxml
if you chose not to follow the previous step. Note, I'm not sure how far along you are, so some of these steps can be safely skipped. Of course, if you mess something up, you can always rm -Rf ~/.virtualenvs/lxmltest
and start again from a new virtualenv.
How to remove responsive features in Twitter Bootstrap 3?
I just figure it out lately on how easy it is to make your bootstrap v3.1.1 being non-responsive. This includes navbars to not to collpase. I don't know if everyone knows this but I'd like to share it.
Two Steps to a Non-responsive Bootsrap v3.1.1
First, create a css file name it as non-responsive.css. Make sure to append it to your themes or link right after the bootstrap css files.
Second, paste this code to your non-responsive.css:
/* Template-specific stuff
*
* Customizations just for the template; these are not necessary for anything
* with disabling the responsiveness.
*/
/* Account for fixed navbar */
body {
min-width: 970px;
padding-top: 70px;
padding-bottom: 30px;
}
/* Finesse the page header spacing */
.page-header {
margin-bottom: 30px;
}
.page-header .lead {
margin-bottom: 10px;
}
/* Non-responsive overrides
*
* Utilitze the following CSS to disable the responsive-ness of the container,
* grid system, and navbar.
*/
/* Reset the container */
.container {
width: 970px;
max-width: none !important;
}
/* Demonstrate the grids */
.col-xs-4 {
padding-top: 15px;
padding-bottom: 15px;
background-color: #eee;
background-color: rgba(86,61,124,.15);
border: 1px solid #ddd;
border: 1px solid rgba(86,61,124,.2);
}
.container .navbar-header,
.container .navbar-collapse {
margin-right: 0;
margin-left: 0;
}
/* Always float the navbar header */
.navbar-header {
float: left;
}
/* Undo the collapsing navbar */
.navbar-collapse {
display: block !important;
height: auto !important;
padding-bottom: 0;
overflow: visible !important;
}
.navbar-toggle {
display: none;
}
.navbar-collapse {
border-top: 0;
}
.navbar-brand {
margin-left: -15px;
}
/* Always apply the floated nav */
.navbar-nav {
float: left;
margin: 0;
}
.navbar-nav > li {
float: left;
}
.navbar-nav > li > a {
padding: 15px;
}
/* Redeclare since we override the float above */
.navbar-nav.navbar-right {
float: right;
}
/* Undo custom dropdowns */
.navbar .navbar-nav .open .dropdown-menu {
position: absolute;
float: left;
background-color: #fff;
border: 1px solid #ccc;
border: 1px solid rgba(0, 0, 0, .15);
border-width: 0 1px 1px;
border-radius: 0 0 4px 4px;
-webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, .175);
box-shadow: 0 6px 12px rgba(0, 0, 0, .175);
}
.navbar-default .navbar-nav .open .dropdown-menu > li > a {
color: #333;
}
.navbar .navbar-nav .open .dropdown-menu > li > a:hover,
.navbar .navbar-nav .open .dropdown-menu > li > a:focus,
.navbar .navbar-nav .open .dropdown-menu > .active > a,
.navbar .navbar-nav .open .dropdown-menu > .active > a:hover,
.navbar .navbar-nav .open .dropdown-menu > .active > a:focus {
color: #fff !important;
background-color: #428bca !important;
}
.navbar .navbar-nav .open .dropdown-menu > .disabled > a,
.navbar .navbar-nav .open .dropdown-menu > .disabled > a:hover,
.navbar .navbar-nav .open .dropdown-menu > .disabled > a:focus {
color: #999 !important;
background-color: transparent !important;
}
That's all and Enjoy..^^
Source: non-responsive.css from the example at getbootstrap.com.
HTML iframe - disable scroll
I tried scrolling="no" in my current browser (Google Chrome Version 60.0.3112.113 (Official Build) (64-bit)) and that didn't work. However, scroll="no" did work. Might be worth trying
<iframe src="<<URL>>" height="800" width="800" sandbox="allow-same-origin allow-scripts allow-forms" scroll="no" style="overflow: hidden"></iframe>
adb command not found
In my case with Android Studio 1.1.0 path was this
/Users/wzbozon/Library/Android/sdk/platform-tools
Add the following to ~/.bash_profile
export PATH=~/Library/Android/sdk/tools:$PATH
export PATH=~/Library/Android/sdk/platform-tools:$PATH
'git status' shows changed files, but 'git diff' doesn't
I used git svn
, and had this problem for one file. Using ls-tree
for each ancestor of the file, I noticed that one had 2 subfolders - Submit
and submit
. Since I was on Windows, they couldn't both be checked out, causing this issue.
The solution was to delete one of them directly from TortoiseSVN
Repo-browser
, then to run git svn fetch
followed by git reset --hard origin/trunk
.
Delete all rows in an HTML table
How about this:
When the page first loads, do this:
var myTable = document.getElementById("myTable");
myTable.oldHTML=myTable.innerHTML;
Then when you want to clear the table:
myTable.innerHTML=myTable.oldHTML;
The result will be your header row(s) if that's all you started with, the performance is dramatically faster than looping.
Explanation of JSONB introduced by PostgreSQL
hstore
is more of a "wide column" storage type, it is a flat (non-nested) dictionary of key-value pairs, always stored in a reasonably efficient binary format (a hash table, hence the name).
json
stores JSON documents as text, performing validation when the documents are stored, and parsing them on output if needed (i.e. accessing individual fields); it should support the entire JSON spec. Since the entire JSON text is stored, its formatting is preserved.
jsonb
takes shortcuts for performance reasons: JSON data is parsed on input and stored in binary format, key orderings in dictionaries are not maintained, and neither are duplicate keys. Accessing individual elements in the JSONB field is fast as it doesn't require parsing the JSON text all the time. On output, JSON data is reconstructed and initial formatting is lost.
IMO, there is no significant reason for not using jsonb
once it is available, if you are working with machine-readable data.
How to make blinking/flashing text with CSS 3
You are first setting opacity: 1;
and then you are ending it on 0
, so it starts from 0%
and ends on 100%
, so instead just set opacity to 0
at 50%
and the rest will take care of itself.
Demo
_x000D_
_x000D_
.blink_me {_x000D_
animation: blinker 1s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes blinker {_x000D_
50% {_x000D_
opacity: 0;_x000D_
}_x000D_
}
_x000D_
<div class="blink_me">BLINK ME</div>
_x000D_
_x000D_
_x000D_
Here, I am setting the animation duration to be 1 second
, and then I am setting the timing
to linear
. That means it will be constant throughout. Last, I am using infinite
. That means it will go on and on.
Note: If this doesn't work for you, use browser prefixes like
-webkit
, -moz
and so on as required for animation
and
@keyframes
. You can refer to my detailed code here
As commented, this won't work on older versions of Internet Explorer, and for that you need to use jQuery or JavaScript...
(function blink() {
$('.blink_me').fadeOut(500).fadeIn(500, blink);
})();
Thanks to Alnitak for suggesting a better approach.
Demo (Blinker using jQuery)
What can be the reasons of connection refused errors?
1.Check your server status.
2.Check the port status.
For example 3306 netstat -nupl|grep 3306
.
3.Check your firewalls.
For example add 3306
vim /etc/sysconfig/iptables
# add
-A INPUT -p tcp -m state --state NEW -m tcp --dport 3306 -j ACCEPT
Remove a JSON attribute
The selected answer would work for as long as you know the key itself that you want to delete but if it should be truly dynamic you would need to use the [] notation instead of the dot notation.
For example:
var keyToDelete = "key1";
var myObj = {"test": {"key1": "value", "key2": "value"}}
//that will not work.
delete myObj.test.keyToDelete
instead you would need to use:
delete myObj.test[keyToDelete];
Substitute the dot notation with [] notation for those values that you want evaluated before being deleted.
How to get a resource id with a known resource name?
in addition to @lonkly solution
- see reflections and field accessibility
- unnecessary variables
method:
/**
* lookup a resource id by field name in static R.class
*
* @author - ceph3us
* @param variableName - name of drawable, e.g R.drawable.<b>image</b>
* @param ? - class of resource, e.g R.drawable.class or R.raw.class
* @return integer id of resource
*/
public static int getResId(String variableName, Class<?> ?)
throws android.content.res.Resources.NotFoundException {
try {
// lookup field in class
java.lang.reflect.Field field = ?.getField(variableName);
// always set access when using reflections
// preventing IllegalAccessException
field.setAccessible(true);
// we can use here also Field.get() and do a cast
// receiver reference is null as it's static field
return field.getInt(null);
} catch (Exception e) {
// rethrow as not found ex
throw new Resources.NotFoundException(e.getMessage());
}
}
Get URL query string parameters
Also if you are looking for current file name along with the query string, you will just need following
basename($_SERVER['REQUEST_URI'])
It would provide you info like following example
file.php?arg1=val&arg2=val
And if you also want full path of file as well starting from root, e.g. /folder/folder2/file.php?arg1=val&arg2=val then just remove basename() function and just use fillowing
$_SERVER['REQUEST_URI']
HTML "overlay" which allows clicks to fall through to elements behind it
Add pointer-events: none;
to the overlay.
Original answer: My suggestion would be that you could capture the click event with the overlay, hide the overlay, then refire the click event, then display the overlay again. I'm not sure if you'd get a flicker effect though.
[Update] Exactly this problem and exactly my solution just appeared in this post: "Forwarding Mouse Events Through Layers". I know its probably a little late for the OP, but for the sake of somebody having this problem in the future, I though I would include it.
How do you use the "WITH" clause in MySQL?
I liked @Brad's answer from this thread, but wanted a way to save the results for further processing (MySql 8):
-- May need to adjust the recursion depth first
SET @@cte_max_recursion_depth = 10000 ; -- permit deeper recursion
-- Some boundaries
set @startDate = '2015-01-01'
, @endDate = '2020-12-31' ;
-- Save it to a table for later use
drop table if exists tmpDates ;
create temporary table tmpDates as -- this has to go _before_ the "with", Duh-oh!
WITH RECURSIVE t as (
select @startDate as dt
UNION
SELECT DATE_ADD(t.dt, INTERVAL 1 DAY) FROM t WHERE DATE_ADD(t.dt, INTERVAL 1 DAY) <= @endDate
)
select * FROM t -- need this to get the "with"'s results as a "result set", into the "create"
;
-- Exists?
select * from tmpDates ;
Which produces:
dt |
----------|
2015-01-01|
2015-01-02|
2015-01-03|
2015-01-04|
2015-01-05|
2015-01-06|
TypeError: can only concatenate list (not "str") to list
That's not how to add an item to a string. This:
newinv=inventory+str(add)
Means you're trying to concatenate a list and a string. To add an item to a list, use the list.append()
method.
inventory.append(add) #adds a new item to inventory
print(inventory) #prints the new inventory
Hope this helps!
What does the function then() mean in JavaScript?
then is a method callback stack which is available after a promise is resolved it is part of library like jQuery but now it is available in native JavaScript and below is the detail explanation how it works
You can do a Promise in native JavaScript : just like there are promises in jQuery, Every promise can be stacked and then can be called with Resolve and Reject callbacks, This is how you can chain asynchronous calls.
I forked and Edited from MSDN Docs on Battery charging status..
What this does is try to find out if user laptop or device is charging battery. then is called and you can do your work post success.
navigator
.getBattery()
.then(function(battery) {
var charging = battery.charging;
alert(charging);
})
.then(function(){alert("YeoMan : SINGH is King !!");});
Another es6 Example
function fetchAsync (url, timeout, onData, onError) {
…
}
let fetchPromised = (url, timeout) => {
return new Promise((resolve, reject) => {
fetchAsync(url, timeout, resolve, reject)
})
}
Promise.all([
fetchPromised("http://backend/foo.txt", 500),
fetchPromised("http://backend/bar.txt", 500),
fetchPromised("http://backend/baz.txt", 500)
]).then((data) => {
let [ foo, bar, baz ] = data
console.log(`success: foo=${foo} bar=${bar} baz=${baz}`)
}, (err) => {
console.log(`error: ${err}`)
})
Definition :: then is a method used to solve Asynchronous callbacks
this is introduced in ES6
Please find the proper documentation here Es6 Promises
Warn user before leaving web page with unsaved changes
Following code works great. You need to reach your form elements' input changes via id attribute:
var somethingChanged=false;
$('#managerForm input').change(function() {
somethingChanged = true;
});
$(window).bind('beforeunload', function(e){
if(somethingChanged)
return "You made some changes and it's not saved?";
else
e=null; // i.e; if form state change show warning box, else don't show it.
});
});
Can a main() method of class be invoked from another class in java
If you want to call the main method of another class you can do it this way assuming I understand the question.
public class MyClass {
public static void main(String[] args) {
System.out.println("main() method of MyClass");
OtherClass obj = new OtherClass();
}
}
class OtherClass {
public OtherClass() {
// Call the main() method of MyClass
String[] arguments = new String[] {"123"};
MyClass.main(arguments);
}
}
passing argument to DialogFragment
as a general way of working with Fragments, as JafarKhQ noted, you should not pass the params in the constructor but with a Bundle
.
the built-in method for that in the Fragment
class is setArguments(Bundle)
and getArguments()
.
basically, what you do is set up a bundle with all your Parcelable
items and send them on.
in turn, your Fragment will get those items in it's onCreate
and do it's magic to them.
the way shown in the DialogFragment
link was one way of doing this in a multi appearing fragment with one specific type of data and works fine most of the time, but you can also do this manually.
node.js + mysql connection pooling
It's a good approach.
If you just want to get a connection add the following code to your module where the pool is in:
var getConnection = function(callback) {
pool.getConnection(function(err, connection) {
callback(err, connection);
});
};
module.exports = getConnection;
You still have to write getConnection every time. But you could save the connection in the module the first time you get it.
Don't forget to end the connection when you are done using it:
connection.release();
Add alternating row color to SQL Server Reporting services report
When using row and column groups both, I had an issue where the colors would alternate between the columns even though it was the same row. I resolved this by using a global variable that alternates only when the row changes:
Public Dim BGColor As String = "#ffffff"
Function AlternateColor() As String
If BGColor = "#cccccc" Then
BGColor = "#ffffff"
Return "#cccccc"
Else
BGColor = "#cccccc"
Return "#ffffff"
End If
End Function
Now, in the first column of the row you want to alternate, set the color expression to:
=Code.AlternateColor()
-
In the remaining columns, set them all to:
=Code.BGColor
This should make the colors alternate only after the first column is drawn.
This may (unverifiably) improve performance, too, since it does not need to do a math computation for each column.
How do you debug MySQL stored procedures?
Debugger for mysql was good but its not free. This is what i use now:
DELIMITER GO$
DROP PROCEDURE IF EXISTS resetLog
GO$
Create Procedure resetLog()
BEGIN
create table if not exists log (ts timestamp default current_timestamp, msg varchar(2048)) engine = myisam;
truncate table log;
END;
GO$
DROP PROCEDURE IF EXISTS doLog
GO$
Create Procedure doLog(in logMsg nvarchar(2048))
BEGIN
insert into log (msg) values(logMsg);
END;
GO$
Usage in stored procedure:
call dolog(concat_ws(': ','@simple_term_taxonomy_id', @simple_term_taxonomy_id));
usage of stored procedure:
call resetLog ();
call stored_proc();
select * from log;
A html space is showing as %2520 instead of %20
For some - possibly valid - reason the url was encoded twice. %25
is the urlencoded %
sign. So the original url looked like:
http://server.com/my path/
Then it got urlencoded once:
http://server.com/my%20path/
and twice:
http://server.com/my%2520path/
So you should do no urlencoding - in your case - as other components seems to to that already for you. Use simply a space
sed edit file in place
The following works fine on my mac
sed -i.bak 's/foo/bar/g' sample
We are replacing foo with bar in sample file. Backup of original file will be saved in sample.bak
For editing inline without backup, use the following command
sed -i'' 's/foo/bar/g' sample
Enabling SSL with XAMPP
Found the answer. In the file xampp\apache\conf\extra\httpd-ssl.conf
, under the comment SSL Virtual Host Context
pages on port 443 meaning https is looked up under different document root.
Simply change the document root to the same one and problem is fixed.
z-index not working with fixed positioning
the behaviour of fixed elements (and absolute elements) as defined in CSS Spec:
They behave as they are detached from document, and placed in the nearest fixed/absolute positioned parent. (not a word by word quote)
This makes zindex calculation a bit complicated, I solved my problem (the same situation) by dynamically creating a container in body element and moving all such elements (which are class-ed as "my-fixed-ones" inside that body-level element)
Why is "using namespace std;" considered bad practice?
This is a bad practice, often known as global namespace pollution. Problems may occur when more than one namespace has the same function name with signature, then it will be ambiguous for the compiler to decide which one to call and this all can be avoided when you are specifying the namespace with your function call like std::cout
. Hope this helps. :)
Set a div width, align div center and text align left
All of these answers should suffice.
However if you don't have a defined width, auto margins will not work.
I have found this nifty little trick to centre some of the more stubborn elements (Particularly images).
.div {
position: absolute;
left: 0;
right: 0;
margin-left: 0;
margin-right: 0;
}
Select DataFrame rows between two dates
Keeping the solution simple and pythonic, I would suggest you to try this.
In case if you are going to do this frequently the best solution would be to first set the date column as index which will convert the column in DateTimeIndex and use the following condition to slice any range of dates.
import pandas as pd
data_frame = data_frame.set_index('date')
df = data_frame[(data_frame.index > '2017-08-10') & (data_frame.index <= '2017-08-15')]
What do Clustered and Non clustered index actually mean?
Clustered Index
Clustered indexes sort and store the data rows in the table or view based on their key values. These are the columns included in the index definition. There can be only one clustered index per table, because the data rows themselves can be sorted in only one order.
The only time the data rows in a table are stored in sorted order is when the table contains a clustered index. When a table has a clustered index, the table is called a clustered table. If a table has no clustered index, its data rows are stored in an unordered structure called a heap.
Nonclustered
Nonclustered indexes have a structure separate from the data rows. A nonclustered index contains the nonclustered index key values and each key value entry has a pointer to the data row that contains the key value.
The pointer from an index row in a nonclustered index to a data row is called a row locator. The structure of the row locator depends on whether the data pages are stored in a heap or a clustered table. For a heap, a row locator is a pointer to the row. For a clustered table, the row locator is the clustered index key.
You can add nonkey columns to the leaf level of the nonclustered index to by-pass existing index key limits, and execute fully covered, indexed, queries. For more information, see Create Indexes with Included Columns. For details about index key limits see Maximum Capacity Specifications for SQL Server.
Reference: https://docs.microsoft.com/en-us/sql/relational-databases/indexes/clustered-and-nonclustered-indexes-described
Editing specific line in text file in Python
If your text contains only one individual:
import re
# creation
with open('pers.txt','wb') as g:
g.write('Dan \n Warrior \n 500 \r\n 1 \r 0 ')
with open('pers.txt','rb') as h:
print 'exact content of pers.txt before treatment:\n',repr(h.read())
with open('pers.txt','rU') as h:
print '\nrU-display of pers.txt before treatment:\n',h.read()
# treatment
def roplo(file_name,what):
patR = re.compile('^([^\r\n]+[\r\n]+)[^\r\n]+')
with open(file_name,'rb+') as f:
ch = f.read()
f.seek(0)
f.write(patR.sub('\\1'+what,ch))
roplo('pers.txt','Mage')
# after treatment
with open('pers.txt','rb') as h:
print '\nexact content of pers.txt after treatment:\n',repr(h.read())
with open('pers.txt','rU') as h:
print '\nrU-display of pers.txt after treatment:\n',h.read()
If your text contains several individuals:
import re
# creation
with open('pers.txt','wb') as g:
g.write('Dan \n Warrior \n 500 \r\n 1 \r 0 \n Jim \n dragonfly\r300\r2\n10\r\nSomo\ncosmonaut\n490\r\n3\r65')
with open('pers.txt','rb') as h:
print 'exact content of pers.txt before treatment:\n',repr(h.read())
with open('pers.txt','rU') as h:
print '\nrU-display of pers.txt before treatment:\n',h.read()
# treatment
def ripli(file_name,who,what):
with open(file_name,'rb+') as f:
ch = f.read()
x,y = re.search('^\s*'+who+'\s*[\r\n]+([^\r\n]+)',ch,re.MULTILINE).span(1)
f.seek(x)
f.write(what+ch[y:])
ripli('pers.txt','Jim','Wizard')
# after treatment
with open('pers.txt','rb') as h:
print 'exact content of pers.txt after treatment:\n',repr(h.read())
with open('pers.txt','rU') as h:
print '\nrU-display of pers.txt after treatment:\n',h.read()
If the “job“ of an individual was of a constant length in the texte, you could change only the portion of texte corresponding to the “job“ the desired individual:
that’s the same idea as senderle’s one.
But according to me, better would be to put the characteristics of individuals in a dictionnary recorded in file with cPickle:
from cPickle import dump, load
with open('cards','wb') as f:
dump({'Dan':['Warrior',500,1,0],'Jim':['dragonfly',300,2,10],'Somo':['cosmonaut',490,3,65]},f)
with open('cards','rb') as g:
id_cards = load(g)
print 'id_cards before change==',id_cards
id_cards['Jim'][0] = 'Wizard'
with open('cards','w') as h:
dump(id_cards,h)
with open('cards') as e:
id_cards = load(e)
print '\nid_cards after change==',id_cards
How to read XML using XPath in Java
If you have a xml like below
<e:Envelope
xmlns:d = "http://www.w3.org/2001/XMLSchema"
xmlns:e = "http://schemas.xmlsoap.org/soap/envelope/"
xmlns:wn0 = "http://systinet.com/xsd/SchemaTypes/"
xmlns:i = "http://www.w3.org/2001/XMLSchema-instance">
<e:Header>
<Friends>
<friend>
<Name>Testabc</Name>
<Age>12121</Age>
<Phone>Testpqr</Phone>
</friend>
</Friends>
</e:Header>
<e:Body>
<n0:ForAnsiHeaderOperResponse xmlns:n0 = "http://systinet.com/wsdl/com/magicsoftware/ibolt/localhost/ForAnsiHeader/ForAnsiHeaderImpl#ForAnsiHeaderOper?KExqYXZhL2xhbmcvU3RyaW5nOylMamF2YS9sYW5nL1N0cmluZzs=">
<response i:type = "d:string">12--abc--pqr</response>
</n0:ForAnsiHeaderOperResponse>
</e:Body>
</e:Envelope>
and wanted to extract the below xml
<e:Header>
<Friends>
<friend>
<Name>Testabc</Name>
<Age>12121</Age>
<Phone>Testpqr</Phone>
</friend>
</Friends>
</e:Header>
The below code helps to achieve the same
public static void main(String[] args) {
File fXmlFile = new File("C://Users//abhijitb//Desktop//Test.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document document;
Node result = null;
try {
document = dbf.newDocumentBuilder().parse(fXmlFile);
XPath xPath = XPathFactory.newInstance().newXPath();
String xpathStr = "//Envelope//Header";
result = (Node) xPath.evaluate(xpathStr, document, XPathConstants.NODE);
System.out.println(nodeToString(result));
} catch (SAXException | IOException | ParserConfigurationException | XPathExpressionException
| TransformerException e) {
e.printStackTrace();
}
}
private static String nodeToString(Node node) throws TransformerException {
StringWriter buf = new StringWriter();
Transformer xform = TransformerFactory.newInstance().newTransformer();
xform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
xform.transform(new DOMSource(node), new StreamResult(buf));
return (buf.toString());
}
Now if you want only the xml like below
<Friends>
<friend>
<Name>Testabc</Name>
<Age>12121</Age>
<Phone>Testpqr</Phone>
</friend>
</Friends>
You need to change the
String xpathStr = "//Envelope//Header";
to String xpathStr = "//Envelope//Header/*";
FFmpeg on Android
For various reasons, Multimedia was and is never easy in terms of achieving the task without compromising on efficiency. ffmpeg is an effort in improving it day by day. It supports different formats of codecs and containers.
Now to answer the question of how to use this library, i would say that it is not so simple to write it here. But i can guide you in following ways.
1) Inside the ffmpeg directory of source code, you have output_example.c or api_example.c. Here, you can see the code where encoding/decoding is done. You will get an idea as to which API's inside ffmpeg you should call. This would be your first step.
2) Dolphin player is a open source project for Android. Currently it is having bugs but developers are working continuously. In that project you have the whole setup ready which you can use to continue your investigation. Here is a link to the project from code.google.com or run the command "git clone https://code.google.com/p/dolphin-player/" in a terminal. You can see two projects named P and P86 . You can use either of them.
Extra tip i would like to offer is that when you are building the ffmpeg code, inside build.sh you need to enable the muxers/demuxers/encoders/decoders of the formats you want to use. Else the corresponding code will not be included in the libraries. It took a lot of time for me to realize this. So thought of sharing it with you.
Few Basics :
When we say a video file, ex : avi, it is combination of both audio and video
Video file = Video + Audio
Video = Codec + Muxer + Demuxer
codec = encoder + Decoder
=> Video = encoder + decoder + Muxer + Demuxer(Mpeg4 + Mpeg4 + avi +avi - Example for avi container)
Audio = Codec + Muxer + Demuxer
codec = encoder + Decoder
=> Audio = encoder + decoder + Muxer + Demuxer(mp2 + mp2 + avi + avi - Example for avi container)
Codec(name is deriverd from a combination of en*co*der/*dec*oder) is just a part of format which defines the algorithms used to encode/decode a frame. AVI is not a codec, it is a container which uses Video codec of Mpeg4 and Audio codec of mp2.
Muxer/demuxer is used to combine/separate the frames from a file used while encoding/decoding.
So if you want to use avi format, you need to enable Video components + Audio components.
Ex, for avi, you need to enable the following.
mpeg4 Encoder, mpeg4 decoder, mp2 encoder, mp2 decoder, avi muxer, avi demuxer.
phewwwwwww...
Programmatically build.sh should contain the following code:
--enable-muxer=avi --enable-demuxer=avi (Generic for both audio/video. generally Specific to a container)
--enable-encoder=mpeg4 --enable-decoder=mpeg4(For video support)
--enable-encoder=mp2 --enable-decoder=mp2 (For Audio support)
Hope i idid not confuse you more after all this...
Thanks, Any assistance needed, please let me know.
How do I use the lines of a file as arguments of a command?
If your shell is bash (amongst others), a shortcut for $(cat afile)
is $(< afile)
, so you'd write:
mycommand "$(< file.txt)"
Documented in the bash man page in the 'Command Substitution' section.
Alterately, have your command read from stdin, so: mycommand < file.txt
Error Importing SSL certificate : Not an X.509 Certificate
This seems like an old thread, but I'll add my experience here. I tried to install a cert as well and got that error. I then opened the cer file with a txt editor, and noticed that there is an extra space (character) at the end of each line. Removing those lines allowed me to import the cert.
Hope this is worth something to someone else.
HTML colspan in CSS
Try adding display: table-cell; width: 1%;
to your table cell element.
_x000D_
_x000D_
.table-cell {_x000D_
display: table-cell;_x000D_
width: 1%;_x000D_
padding: 4px;_x000D_
border: 1px solid #efefef;_x000D_
}
_x000D_
<div class="table">_x000D_
<div class="table-cell">one</div>_x000D_
<div class="table-cell">two</div>_x000D_
<div class="table-cell">three</div>_x000D_
<div class="table-cell">four</div>_x000D_
</div>_x000D_
<div class="table">_x000D_
<div class="table-cell">one</div>_x000D_
<div class="table-cell">two</div>_x000D_
<div class="table-cell">three</div>_x000D_
<div class="table-cell">four</div>_x000D_
</div>_x000D_
<div class="table">_x000D_
<div class="table-cell">one</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
How to remove a build from itunes connect?
Dang this is hard. Here is what I did to reject/delete/replace my ios build before it was released. The app was approved how ever I found found a bug I wanted to fix before releasing
- I set release to "manual" and saved
- I tried to create and app release
- got an error message something like "you can only have one release at a time"
- where the save button was there was not an option to cancel release
- the version of the app is not marked "developer rejected" with a red dot
To replace the bad build I did the following
- if you click on the "+ version or platform" to create a new version you will not be be able to create a new iOS version
- you need to upload a new build
- in your rejected app, select the new build
- save
- submit for review
How can I check which version of Angular I'm using?
For Angular 2+, in any modern browser having developper tools (F12) you can inspect the top level application tag.
For Internet Explorer 11 or Edge you can find information here :
Works for Angular 2+
Chrome browser
Firefox firebug
How can I convert a string to a number in Perl?
In comparisons it makes a difference if a scalar is a number of a string. And it is not always decidable. I can report a case where perl retrieved a float in "scientific" notation and used that same a few lines below in a comparison:
use strict;
....
next unless $line =~ /and your result is:\s*(.*)/;
my $val = $1;
if ($val < 0.001) {
print "this is small\n";
}
And here $val
was not interpreted as numeric for e.g. "2e-77"
retrieved from $line
. Adding 0 (or 0.0 for good ole C programmers) helped.
jQuery $(this) keyword
$(document).ready(function(){
$('.somediv').click(function(){
$(this).addClass('newDiv'); // this means the div which is clicked
}); // so instead of using a selector again $('.somediv');
}); // you use $(this) which much better and neater:=)
Python and SQLite: insert into table
#The Best way is to use `fStrings` (very easy and powerful in python3)
#Format: f'your-string'
#For Example:
mylist=['laks',444,'M']
cursor.execute(f'INSERT INTO mytable VALUES ("{mylist[0]}","{mylist[1]}","{mylist[2]}")')
#THATS ALL!! EASY!!
#You can use it with for loop!
Running Python code in Vim
You can extends for any language with 1 keybinding with augroup command, for example:
augroup rungroup
autocmd!
autocmd BufRead,BufNewFile *.go nnoremap <F5> :exec '!go run' shellescape(@%, 1)<cr>
autocmd BufRead,BufNewFile *.py nnoremap <F5> :exec '!python' shellescape(@%, 1)<cr>
augroup END
How to specify "does not contain" in dplyr filter
Try putting the search condition in a bracket, as shown below. This returns the result of the conditional query inside the bracket. Then test its result to determine if it is negative (i.e. it does not belong to any of the options in the vector), by setting it to FALSE.
SE_CSVLinelist_filtered <- filter(SE_CSVLinelist_clean,
(where_case_travelled_1 %in% c('Outside Canada','Outside province/territory of residence but within Canada')) == FALSE)
Handling errors in Promise.all
if you get to use the q library https://github.com/kriskowal/q
it has q.allSettled() method that can solve this problem
you can handle every promise depending on its state either fullfiled or rejected
so
existingPromiseChain = existingPromiseChain.then(function() {
var arrayOfPromises = state.routes.map(function(route){
return route.handler.promiseHandler();
});
return q.allSettled(arrayOfPromises)
});
existingPromiseChain = existingPromiseChain.then(function(arrayResolved) {
//so here you have all your promises the fulfilled and the rejected ones
// you can check the state of each promise
arrayResolved.forEach(function(item){
if(item.state === 'fulfilled'){ // 'rejected' for rejected promises
//do somthing
} else {
// do something else
}
})
// do stuff with my array of resolved promises, eventually ending with a res.send();
});
Why is printing "B" dramatically slower than printing "#"?
Pure speculation is that you're using a terminal that attempts to do word-wrapping rather than character-wrapping, and treats B
as a word character but #
as a non-word character. So when it reaches the end of a line and searches for a place to break the line, it sees a #
almost immediately and happily breaks there; whereas with the B
, it has to keep searching for longer, and may have more text to wrap (which may be expensive on some terminals, e.g., outputting backspaces, then outputting spaces to overwrite the letters being wrapped).
But that's pure speculation.
How does createOrReplaceTempView work in Spark?
createOrReplaceTempView
creates (or replaces if that view name already exists) a lazily evaluated "view" that you can then use like a hive table in Spark SQL. It does not persist to memory unless you cache the dataset that underpins the view.
scala> val s = Seq(1,2,3).toDF("num")
s: org.apache.spark.sql.DataFrame = [num: int]
scala> s.createOrReplaceTempView("nums")
scala> spark.table("nums")
res22: org.apache.spark.sql.DataFrame = [num: int]
scala> spark.table("nums").cache
res23: org.apache.spark.sql.Dataset[org.apache.spark.sql.Row] = [num: int]
scala> spark.table("nums").count
res24: Long = 3
The data is cached fully only after the .count
call. Here's proof it's been cached:
Related SO: spark createOrReplaceTempView vs createGlobalTempView
Relevant quote (comparing to persistent table): "Unlike the createOrReplaceTempView command, saveAsTable will materialize the contents of the DataFrame and create a pointer to the data in the Hive metastore." from https://spark.apache.org/docs/latest/sql-programming-guide.html#saving-to-persistent-tables
Note : createOrReplaceTempView
was formerly registerTempTable
Contain an image within a div?
You have to style the image like this
#container img{width:100%;}
and the container with hidden overflow:
#container{width:250px; height:250px; overflow:hidden; border:1px solid #000;}
Customizing the template within a Directive
Here's what I ended up using.
I'm very new to AngularJS, so would love to see better / alternative solutions.
angular.module('formComponents', [])
.directive('formInput', function() {
return {
restrict: 'E',
scope: {},
link: function(scope, element, attrs)
{
var type = attrs.type || 'text';
var required = attrs.hasOwnProperty('required') ? "required='required'" : "";
var htmlText = '<div class="control-group">' +
'<label class="control-label" for="' + attrs.formId + '">' + attrs.label + '</label>' +
'<div class="controls">' +
'<input type="' + type + '" class="input-xlarge" id="' + attrs.formId + '" name="' + attrs.formId + '" ' + required + '>' +
'</div>' +
'</div>';
element.html(htmlText);
}
}
})
Example usage:
<form-input label="Application Name" form-id="appName" required/></form-input>
<form-input type="email" label="Email address" form-id="emailAddress" required/></form-input>
<form-input type="password" label="Password" form-id="password" /></form-input>
Xcode couldn't find any provisioning profiles matching
I am now able to successfully build. Not sure exactly which step "fixed" things, but this was the sequence:
- Tried automatic signing again. No go, so reverted to manual.
- After reverting, I had no Eligible Profiles, all were ineligible. Strange.
- I created a new certificate and profile, imported both. This too was "ineligible".
- Removed the iOS platform and re-added it. I had tried this previously without luck.
- After doing this, Xcode on its own defaulted to automatic signing. And this worked! Success!
While I am not sure exactly which parts were necessary, I think the previous certificates were the problem. I hate Xcode :(
Thanks for help.
How to check file input size with jQuery?
<form id="uploadForm" class="disp-inline" role="form" action="" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file">
</form>
<button onclick="checkSize();"></button>
<script>
function checkSize(){
var size = $('#uploadForm')["0"].firstChild.files["0"].size;
console.log(size);
}
</script>
I found this to be the easiest if you don't plan on submitted the form through standard ajax / html5 methods, but of course it works with anything.
NOTES:
var size = $('#uploadForm')["0"]["0"].files["0"].size;
This used to work, but it doesn't in chrome anymore, i just tested the code above and it worked in both ff and chrome (lastest). The second ["0"] is now firstChild.
Copy data from one column to other column (which is in a different table)
A similar question's answer worked more correctly for me than this question's selected answer (by Mark Byers). Using Mark's answer, my updated column got the same value in all the rows (perhaps the value from the first row that matched the join). Using ParveenaArora's answer from the other thread updated the column with the correct values.
Transforming Parveena's solution to use this question' table and column names, the query would be as follows (where I assume the tables are related through tblindiantime.contact_id):
UPDATE tblindiantime
SET CountryName = contacts.BusinessCountry
FROM contacts
WHERE tblindiantime.contact_id = contacts.id;
Import SQL file into mysql
In Linux I navigated to the directory containing the .sql file before starting mysql. The system cursor is now in the same location as the file and you won't need a path. Use source myData.sql where my date is replaced with the name of your file.
cd whatever directory
mysql - p
connect targetDB
source myData.sql
Done
Windows 7 environment variable not working in path
To address this problem, I have used setx command which try to set user level variables.
I used below...
setx JAVA_HOME "C:\Program Files\Java\jdk1.8.0_92"
setx PATH %JAVA_HOME%\bin
NOTE: Windows try to append provided variable value to existing variable value. So no need to give extra %PATH%... something like %JAVA_HOME%\bin;%PATH%
Spring Resttemplate exception handling
Here is my POST method with HTTPS which returns a response body for any type of bad responses.
public String postHTTPSRequest(String url,String requestJson)
{
//SSL Context
CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
//Initiate REST Template
RestTemplate restTemplate = new RestTemplate(requestFactory);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
//Send the Request and get the response.
HttpEntity<String> entity = new HttpEntity<String>(requestJson,headers);
ResponseEntity<String> response;
String stringResponse = "";
try {
response = restTemplate.postForEntity(url, entity, String.class);
stringResponse = response.getBody();
}
catch (HttpClientErrorException e)
{
stringResponse = e.getResponseBodyAsString();
}
return stringResponse;
}
How to send json data in the Http request using NSURLRequest
Since my edit to Mike G's answer to modernize the code was rejected 3 to 2 as
This edit was intended to address the author of the post and makes no
sense as an edit. It should have been written as a comment or an
answer
I'm reposting my edit as a separate answer here. This edit removes the JSONRepresentation
dependency with NSJSONSerialization
as Rob's comment with 15 upvotes suggests.
NSArray *objects = [NSArray arrayWithObjects:[[NSUserDefaults standardUserDefaults]valueForKey:@"StoreNickName"],
[[UIDevice currentDevice] uniqueIdentifier], [dict objectForKey:@"user_question"], nil];
NSArray *keys = [NSArray arrayWithObjects:@"nick_name", @"UDID", @"user_question", nil];
NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSDictionary *jsonDict = [NSDictionary dictionaryWithObject:questionDict forKey:@"question"];
NSLog(@"jsonRequest is %@", jsonRequest);
NSURL *url = [NSURL URLWithString:@"https://xxxxxxx.com/questions"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil]; //TODO handle error
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
receivedData = [[NSMutableData data] retain];
}
The receivedData is then handled by:
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSDictionary *question = [jsonDict objectForKey:@"question"];
How to insert pandas dataframe via mysqldb into database?
Update:
There is now a to_sql
method, which is the preferred way to do this, rather than write_frame
:
df.to_sql(con=con, name='table_name_for_df', if_exists='replace', flavor='mysql')
Also note: the syntax may change in pandas 0.14...
You can set up the connection with MySQLdb:
from pandas.io import sql
import MySQLdb
con = MySQLdb.connect() # may need to add some other options to connect
Setting the flavor
of write_frame
to 'mysql'
means you can write to mysql:
sql.write_frame(df, con=con, name='table_name_for_df',
if_exists='replace', flavor='mysql')
The argument if_exists
tells pandas how to deal if the table already exists:
if_exists: {'fail', 'replace', 'append'}
, default 'fail'
fail
: If table exists, do nothing.
replace
: If table exists, drop it, recreate it, and insert data.
append
: If table exists, insert data. Create if does not exist.
Although the write_frame
docs currently suggest it only works on sqlite, mysql appears to be supported and in fact there is quite a bit of mysql testing in the codebase.
SELECT list is not in GROUP BY clause and contains nonaggregated column
As @Brian Riley already said you should either remove 1 column in your select
select countrylanguage.language ,sum(country.population*countrylanguage.percentage/100)
from countrylanguage
join country on countrylanguage.countrycode = country.code
group by countrylanguage.language
order by sum(country.population*countrylanguage.percentage) desc ;
or add it to your grouping
select countrylanguage.language, country.code, sum(country.population*countrylanguage.percentage/100)
from countrylanguage
join country on countrylanguage.countrycode = country.code
group by countrylanguage.language, country.code
order by sum(country.population*countrylanguage.percentage) desc ;
Change default text in input type="file"?
You can use this approach, it works even if a lot of files inputs.
_x000D_
_x000D_
const fileBlocks = document.querySelectorAll('.file-block')_x000D_
const buttons = document.querySelectorAll('.btn-select-file')_x000D_
_x000D_
;[...buttons].forEach(function (btn) {_x000D_
btn.onclick = function () {_x000D_
btn.parentElement.querySelector('input[type="file"]').click()_x000D_
}_x000D_
})_x000D_
_x000D_
;[...fileBlocks].forEach(function (block) {_x000D_
block.querySelector('input[type="file"]').onchange = function () {_x000D_
const filename = this.files[0].name_x000D_
_x000D_
block.querySelector('.btn-select-file').textContent = 'File selected: ' + filename_x000D_
}_x000D_
})
_x000D_
.btn-select-file {_x000D_
border-radius: 20px;_x000D_
}_x000D_
_x000D_
input[type="file"] {_x000D_
display: none;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="file-block">_x000D_
<button class="btn-select-file">Select Image 1</button>_x000D_
<input type="file">_x000D_
</div>_x000D_
<br>_x000D_
<div class="file-block">_x000D_
<button class="btn-select-file">Select Image 2</button>_x000D_
<input type="file">_x000D_
</div>
_x000D_
_x000D_
_x000D_
How do I escape spaces in path for scp copy in Linux?
works
scp localhost:"f/a\ b\ c" .
scp localhost:'f/a\ b\ c' .
does not work
scp localhost:'f/a b c' .
The reason is that the string is interpreted by the shell before the path is passed to the scp command. So when it gets to the remote the remote is looking for a string with unescaped quotes and it fails
To see this in action, start a shell with the -vx options ie bash -vx
and it will display the interpolated version of the command as it runs it.
Reverting to a specific commit based on commit id with Git?
I think, bwawok's answer is wrong at some point:
if you do
git reset --soft c14809fa
It will make your local files changed to be like they were then, but leave your history etc. the same.
According to manual: git-reset, "git reset --soft"...
does not touch the index file nor the working tree at all (but resets the head to <commit>, just like all modes do). This leaves all your changed files "Changes to be committed", as git status would put it.
So it will "remove" newer commits from the branch. This means, after looking at your old code, you cannot go to the newest commit in this branch again, easily. So it does the opposide as described by bwawok: Local files are not changed (they look exactly as before "git reset --soft"), but the history is modified (branch is truncated after the specified commit).
The command for bwawok's answer might be:
git checkout <commit>
You can use this to peek at old revision: How did my code look yesterday?
(I know, I should put this in comments to this answer, but stackoverflow does not allow me to do so! My reputation is too low.)
Determine SQL Server Database Size
I always liked going after it directly:
SELECT
DB_NAME( dbid ) AS DatabaseName,
CAST( ( SUM( size ) * 8 ) / ( 1024.0 * 1024.0 ) AS decimal( 10, 2 ) ) AS DbSizeGb
FROM
sys.sysaltfiles
GROUP BY
DB_NAME( dbid )
Force IE9 to emulate IE8. Possible?
On the client side you can add and remove websites to be displayed in Compatibility View from Compatibility View Settings window of IE:
Tools-> Compatibility View Settings
How to run a jar file in a linux commandline
For example to execute from terminal (Ubuntu Linux) or even (Windows console) a java file called filex.jar use this command:
java -jar filex.jar
The file will execute in terminal.
'pip install' fails for every package ("Could not find a version that satisfies the requirement")
Support for TLS 1.0 and 1.1 was dropped for PyPI. If your system does not use a more recent version, it could explain your error.
Could you try reinstalling pip system-wide, to update your system dependencies to a newer version of TLS?
This seems to be related to Unable to install Python libraries
See Dominique Barton's answer:
Apparently pip is trying to access PyPI via HTTPS (which is encrypted and fine), but with an old (insecure) SSL version. Your system seems to be out of date. It might help if you update your packages.
On Debian-based systems I'd try:
apt-get update && apt-get upgrade python-pip
On Red Hat Linux-based systems:
yum update python-pip # (or python2-pip, at least on Red Hat Linux 7)
On Mac:
sudo easy_install -U pip
You can also try to update openssl
separately.