I think the "meaning" of void* in this case is a generic handle. It is not a pointer to a value, it is the value itself. (This just happens to be how void* is used by C and C++ programmers.)
If it is holding an integer value, it had better be within integer range!
Here is easy rendering to integer:
int x = (char*)p - (char*)0;
It should only give a warning.
Regardless of the benefits, I would suggest that you always compile your program for the system's default word size (32-bit or 64-bit), since if you compile a library as a 32-bit binary and provide it on a 64-bit system, you will force anyone who wants to link with your library to provide their library (and any other library dependencies) as a 32-bit binary, when the 64-bit version is the default available. This can be quite a nuisance for everyone. When in doubt, provide both versions of your library.
As to the practical benefits of 64-bit... the most obvious is that you get a bigger address space, so if mmap a file, you can address more of it at once (and load larger files into memory). Another benefit is that, assuming the compiler does a good job of optimizing, many of your arithmetic operations can be parallelized (for example, placing two pairs of 32-bit numbers in two registers and performing two adds in single add operation), and big number computations will run more quickly. That said, the whole 64-bit vs 32-bit thing won't help you with asymptotic complexity at all, so if you are looking to optimize your code, you should probably be looking at the algorithms rather than the constant factors like this.
EDIT:
Please disregard my statement about the parallelized addition. This is not performed by an ordinary add statement... I was confusing that with some of the vectorized/SSE instructions. A more accurate benefit, aside from the larger address space, is that there are more general purpose registers, which means more local variables can be maintained in the CPU register file, which is much faster to access, than if you place the variables in the program stack (which usually means going out to the L1 cache).
That message isn't actually an error - it's just a warning that the file in question isn't of the right architecture (e.g. 32-bit vs 64-bit, wrong CPU architecture). The linker will keep looking for a library of the right type.
Of course, if you're also getting an error along the lines of can't find lPI-Http
then you have a problem :-)
It's hard to suggest what the exact remedy will be without knowing the details of your build system and makefiles, but here are a couple of shots in the dark:
CFLAGS
rather than
CTAGS
- are you sure this is
correct? (What you have may be correct - this will depend on your build system!)LDFLAGS
If that doesn't help - can you post the full error output, plus the actual command (e.g. gcc foo.c -m32 -Dxxx
etc) that was being executed?
In my case, I am using a tiny .exe that reloads the referenced DLLs via Reflection. So I just do these steps which saves my day:
From project properties on solution explorer, at build tab, I choose target platfrom x86
Under Windows 7 in the "Control Panel" under "Programs | Programs and Features" the 64-bit variants of JRE & JDK are listed with "64-bit" in parentheses (e.g. "Java SE Development Kit 7 Update 65 (64-Bit)"), while for the 32-bit variants the variant is not mentioned in parentheses (e.g. just "Java SE Development Kit 8 Update 60").
Add a paramter as below in you in configuration while creating the exe
I hope it helps.
thanks...
/jav
Just try this code:
start "" "C:\Users\DiPesh\Desktop\vbscript\welcome.vbs"
and save as .bat, it works for me
I tried both the 32-bit and 64-bit installers of both Oracle and IBM Java on Windows, and the presence of C:\Windows\SysWOW64\java.exe seems to be a reliable way to determine that 32-bit Java is available. I haven't tested older versions of these installers, but this at least looks like it should be a reliable way to test, for the most recent versions of Java.
One way is to setup a chroot environment. Debian has a number of tools for that, for example debootstrap
I had the same problem. I tried lot of ways but at last solution was simple. Solution: Open IIS, In Application Pools, right click on the .net framework that is being used. Go to settings and change 'Enable 32-Bit Applications' to 'True'.
In the launcher script you can force it, it permits to keep the same script and same launcher for both architecture
:: For 32 bits architecture, this line is sufficent (32bits is the only cscript available)
set CSCRIPT="cscript.exe"
:: Detect windows 64bits and use the expected cscript (SysWOW64 contains 32bits executable)
if exist "C:\Windows\SysWOW64\cscript.exe" set CSCRIPT="C:\Windows\SysWOW64\cscript.exe"
%CSCRIPT% yourscript.vbs
Upgrade to version 1.6 of FPDF.
A good example where to subscribe a setInterval(), and use a clearInterval() to stop the forever loop:
function myTimer() {
console.log(' each 1 second...');
}
var myVar = setInterval(myTimer, 1000);
call this line to stop the loop:
clearInterval(myVar);
You can just use the pipe on its own:
"string1|string2"
for example:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|string2", "blah"));
Output:
blah, blah, string3
The main reason to use parentheses is to limit the scope of the alternatives:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(1|2)", "blah"));
has the same output. but if you just do this:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|2", "blah"));
you get:
blah, stringblah, string3
because you've said "string1" or "2".
If you don't want to capture that part of the expression use ?:
:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(?:1|2)", "blah"));
I use this technique for pagination. I do not fetch all the rows. For example, if my page needs to display the top 100 rows I fetch only the 100 with where clause. The output of the SQL should have a unique key.
The table has the following:
ID, KeyId, Rank
The same rank will be assigned for more than one KeyId.
SQL is select top 2 * from Table1 where Rank >= @Rank and ID > @Id
For the first time I pass 0 for both. The second time pass 1 & 14. 3rd time pass 2 and 6....
The value of the 10th record Rank & Id is passed to the next
11 21 1
14 22 1
7 11 1
6 19 2
12 31 2
13 18 2
This will have the least stress on the system
The reliable solution is catching the ObjectDisposedException.
The solution to write your overridden implementation of the Dispose method doesn't work, since there is a race condition between the thread calling Dispose method and the one accessing to the object: after having checked the hypothetic IsDisposed property , the object could be really disposed, throwing the exception all the same.
Another approach could be exposing a hypothetic event Disposed (like this), which is used to notify about the disposing object to every object interested, but this could be difficoult to plan depending on the software design.
I don't think there is a SAP parameter for that kind of result. Though the code below will deliver.
LOOP AT intTab.
AT END OF value.
result = sy-tabix.
write result.
ENDAT.
ENDLOOP.
You can use the by()
function:
by(dataFrame, seq_len(nrow(dataFrame)), function(row) dostuff)
But iterating over the rows directly like this is rarely what you want to; you should try to vectorize instead. Can I ask what the actual work in the loop is doing?
I looked into the options pattern sample and saw this:
public class Startup
{
public Startup(IConfiguration config)
{
// Configuration from appsettings.json has already been loaded by
// CreateDefaultBuilder on WebHost in Program.cs. Use DI to load
// the configuration into the Configuration property.
Configuration = config;
}
...
}
When adding Iconfiguration in the constructor of my class, I could access the configuration options through DI.
Example:
public class MyClass{
private Iconfiguration _config;
public MyClass(Iconfiguration config){
_config = config;
}
... // access _config["myAppSetting"] anywhere in this class
}
Try adding the -f
option to show the function names :
addr2line -f -e a.out 0x4005BDC
Old question but throwing my solution into the ring for completeness. I needed this when I needed a specific find but a different create if it doesn't exist.
def self.find_by_or_create_with(args, attributes) # READ CAREFULLY! args for finding, attributes for creating!
obj = self.find_or_initialize_by(args)
return obj if obj.persisted?
return obj if obj.update_attributes(attributes)
end
followers_df.reset_index()
followers_df.reindex(index=range(0,20))
Navigate your file location just press Shift
button and click file name. Click tab Open command window here
and write in your command prompt python file_name.py
My solution works only if you need retrieve only one column, however for my needs was the best solution found in terms of performance (it use only one single query!):
SELECT SUBSTRING_INDEX(GROUP_CONCAT(column_x ORDER BY column_y),',',1) AS xyz,
column_z
FROM table_name
GROUP BY column_z;
It use GROUP_CONCAT in order to create an ordered concat list and then I substring to only the first one.
Since JsonSerializer is deprecated in .Net 4.0+ I used http://www.newtonsoft.com/json to solve this issue.
NuGet- > Install-Package Newtonsoft.Json
If anyone's reading images or other binary files from a zip file hosted at a remote server, you can use following snippet to download and create zip object using the jszip library.
// this function just get the public url of zip file.
let url = await getStorageUrl(path)
console.log('public url is', url)
//get the zip file to client
axios.get(url, { responseType: 'arraybuffer' }).then((res) => {
console.log('zip download status ', res.status)
//load contents into jszip and create an object
jszip.loadAsync(new Blob([res.data], { type: 'application/zip' })).then((zip) => {
const zipObj = zip
$.each(zip.files, function (index, zipEntry) {
console.log('filename', zipEntry.name)
})
})
Now using the zipObj you can access the files and create a src url for it.
var fname = 'myImage.jpg'
zipObj.file(fname).async('blob').then((blob) => {
var blobUrl = URL.createObjectURL(blob)
i find that this works for me
db.getCollection('collectionName').findOne({"fieldName" : {$ne: null}})
Another option would be to use the chromestorage API. This allows storage of user data with optional syncing across sessions.
One downside is that it is asynchronous.
First, you should know now the android.support.v4.app.ActionBarDrawerToggle
is deprecated.
You must replace that with android.support.v7.app.ActionBarDrawerToggle
.
Here is my example and I use the new Toolbar
to replace the ActionBar
.
MainActivity.java
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(
this, mDrawerLayout, mToolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close
);
mDrawerLayout.setDrawerListener(mDrawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle.syncState();
}
styles.xml
<style name="AppTheme" parent="Theme.AppCompat.Light">
<item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
</style>
<style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
<item name="spinBars">true</item>
<item name="color">@android:color/white</item>
</style>
You can read the documents on AndroidDocument#DrawerArrowToggle_spinBars
This attribute is the key to implement the menu-to-arrow animation.
public static int DrawerArrowToggle_spinBars
Whether bars should rotate or not during transition
Must be a boolean value, either "true" or "false".
So, you set this: <item name="spinBars">true</item>
.
Then the animation can be presented.
Hope this can help you.
I got this solution. Does this help you ?
text = """df1:
2013-11-24 Banana 22.1 Yellow
2013-11-24 Orange 8.6 Orange
2013-11-24 Apple 7.6 Green
2013-11-24 Celery 10.2 Green
df2:
2013-11-24 Banana 22.1 Yellow
2013-11-24 Orange 8.6 Orange
2013-11-24 Apple 7.6 Green
2013-11-24 Celery 10.2 Green
2013-11-25 Apple 22.1 Red
2013-11-25 Orange 8.6 Orange
argetz45
2013-11-24 Banana 22.1 Yellow
2013-11-24 Orange 118.6 Orange
2013-11-24 Apple 74.6 Green
2013-11-24 Celery 10.2 Green
2013-11-25 Nuts 45.8 Brown
2013-11-25 Apple 22.1 Red
2013-11-25 Orange 8.6 Orange
2013-11-26 Pear 102.54 Pale"""
.
from collections import OrderedDict
import re
r = re.compile('([a-zA-Z\d]+).*\n'
'(20\d\d-[01]\d-[0123]\d.+\n?'
'(.+\n?)*)'
'(?=[ \n]*\Z'
'|'
'\n+[a-zA-Z\d]+.*\n'
'20\d\d-[01]\d-[0123]\d)')
r2 = re.compile('((20\d\d-[01]\d-[0123]\d) +([^\d.]+)(?<! )[^\n]+)')
d = OrderedDict()
bef = []
for m in r.finditer(text):
li = []
for x in r2.findall(m.group(2)):
if not any(x[1:3]==elbef for elbef in bef):
bef.append(x[1:3])
li.append(x[0])
d[m.group(1)] = li
for name,lu in d.iteritems():
print '%s\n%s\n' % (name,'\n'.join(lu))
result
df1
2013-11-24 Banana 22.1 Yellow
2013-11-24 Orange 8.6 Orange
2013-11-24 Apple 7.6 Green
2013-11-24 Celery 10.2 Green
df2
2013-11-25 Apple 22.1 Red
2013-11-25 Orange 8.6 Orange
argetz45
2013-11-25 Nuts 45.8 Brown
2013-11-26 Pear 102.54 Pale
object.setForeground(Color.green);
*any colour you wish *object being declared earlier
If you want to merge changes in SubBranch to MainBranch
git checkout MainBranch
git merge SubBranch
As far as I know, and I cant verify it now, you cannot stop remote services with the Stop-Service cmdlet or with .Net, it is not supported.
Yes it works, but it stopes the service on your local machine, not on the remote computer.
Now, if the above is correct, without remoting or wmi enabled, you could set a scheduled job on the remote system, using AT, that runs Stop-Service locally.
Are you sure you should be using POST not PUT?
POST is usually used with application/x-www-urlencoded
formats. If you are using a REST API, you should maybe be using PUT? If you are uploading a file you probably need to use multipart/form-data
. Not always, but usually, that is the right thing to do..
Also you don't seem to be using the credentials to log in - you need to use the Credentials property of the HttpWebRequest object to send the username and password.
Thanks for bringing this to the attention of the community and apologies for the issues you’ve been having. This issue stems from having a copy of the expired WWDR Intermediate certificate in both your System and Login keychains. To resolve the issue, you should first download and install the new WWDR intermediate certificate (by double-clicking on the file). Next, in the Keychain Access application, select the System keychain. Make sure to select “Show Expired Certificates” in the View menu and then delete the expired version of the Apple Worldwide Developer Relations Certificate Authority Intermediate certificate (expired on February 14, 2016). Your certificates should now appear as valid in Keychain Access and be available to Xcode for submissions to the App Store.
As noted in a comment below, the expired certificate also needs to be removed from the login
section, as well:
To all that cannot get it working despite the instructions... There are two expired WWDR certs. One is in login keychain, and the other one is in the System. You have to delete both of them in order to make things working
?legend
will tell you:
Arguments
x
, y
the x
and y
co-ordinates to be used to position the legend. They can be specified by keyword or in any way which is accepted by xy.coords
: See ‘Details’.
Details:
Arguments x
, y
, legend are interpreted in a non-standard way to allow the coordinates to be specified via one or two arguments. If legend is missing and y
is not numeric, it is assumed that the second argument is intended to be legend and that the first argument specifies the coordinates.
The coordinates can be specified in any way which is accepted by xy.coords
. If this gives the coordinates of one point, it is used as the top-left coordinate of the rectangle containing the legend. If it gives the coordinates of two points, these specify opposite corners of the rectangle (either pair of corners, in any order).
The location may also be specified by setting x
to a single keyword from the list bottomright
, bottom
, bottomleft
, left
, topleft
, top
, topright
, right
and center
. This places the legend on the inside of the plot frame at the given location. Partial argument matching is used. The optional inset argument specifies how far the legend is inset from the plot margins. If a single value is given, it is used for both margins; if two values are given, the first is used for x- distance, the second for y-distance.
The equivalent is the ? operator:
var value: NSNumber? = myQuestionableObject?.importantMethod()
importantMethod will only be called if myQuestionableObject exists and implements it.
The one way found is to use the geoXML3 library which is suitable for usage along with KML processor Version 3 of the Google Maps JavaScript API.
You've got two common situations. The first is that you want random numbers and aren't too fussed about the quality or execution speed. In that case, use the following macro
#define uniform() (rand()/(RAND_MAX + 1.0))
that gives you p in the range 0 to 1 - epsilon (unless RAND_MAX is bigger than the precision of a double, but worry about that when you come to it).
int x = (int) (uniform() * N);
Now gives a random integer on 0 to N -1.
If you need other distributions, you have to transform p. Or sometimes it's easier to call uniform() several times.
If you want repeatable behaviour, seed with a constant, otherwise seed with a call to time().
Now if you are bothered about quality or run time performance, rewrite uniform(). But otherwise don't touch the code. Always keep uniform() on 0 to 1 minus epsilon. Now you can wrap the C++ random number library to create a better uniform(), but that's a sort of medium-level option. If you are bothered about the characteristics of the RNG, then it's also worth investing a bit of time to understand how the underlying methods work, then provide one. So you've got complete control of the code, and you can guarantee that with the same seed, the sequence will always be exactly the same, regardless of platform or which version of C++ you are linking to.
The easiest way would be to select Relativelayout from the Pallete, and then use it.
Based on what @user225312 said, you can use .zfill() to add paddng to numbers converted to strings.
My approach is to leave number as a number until the moment you want to convert it into string:
>>> num = 11
>>> padding = 3
>>> print(str(num).zfill(padding))
011
I know this thread is ancient, but after assigning the innerHTML, ExecWB worked for me:
.ExecWB 17, 0_x000D_
'Select all contents in browser_x000D_
.ExecWB 12, 2_x000D_
'Copy them
_x000D_
And then just paste the contents into Excel. Since these methods are prone to runtime errors, but work fine after one or two tries in debug mode, you might have to tell Excel to try again if it runs into an error. I solved this by adding this error handler to the sub, and it works fine:
Sub ApplyHTML()_x000D_
On Error GoTo ErrorHandler_x000D_
..._x000D_
Exit Sub_x000D_
_x000D_
ErrorHandler:_x000D_
Resume _x000D_
'I.e. re-run the line of code that caused the error_x000D_
Exit Sub_x000D_
_x000D_
End Sub
_x000D_
For Objective-C users
Just Use this code
[vc setModalPresentationStyle: UIModalPresentationFullScreen];
Or if you want to add it particular in iOS 13.0 then use
if (@available(iOS 13.0, *)) {
[vc setModalPresentationStyle: UIModalPresentationFullScreen];
} else {
// Fallback on earlier versions
}
Probably your code works but it is rebound somewhere after you clear it. Make sure that this it not the case. It will be more helpful if you provide some code. Where are you setting your data source? Where are you data binding? Where are you clearing the list?
Adding on to the one mentioned by @abarnert
a better one is to catch the exception
import subprocess
try:
py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'],stderr= subprocess.STDOUT)
#print('py2 said:', py2output)
print "here"
except subprocess.CalledProcessError as e:
print "Calledprocerr"
this stderr= subprocess.STDOUT is for making sure you dont get the filenotfound error in stderr- which cant be usually caught in filenotfoundexception, else you would end up getting
python: can't open file 'py2.py': [Errno 2] No such file or directory
Infact a better solution to this might be to check, whether the file/scripts exist and then to run the file/script
LinkedHashMap
is precisely what you're looking for.
It is exactly like HashMap
, except that when you iterate over it, it presents the items in the insertion order.
Easiest way is to provide the process id.
gdb -p `pidof your_running_program_name`
Please get the full list of option in man gdb
command.
In case there are multiple process for the same program running, then the following command will list the processes.
ps -C program -o pid h
<number>
Then the output process id (number) can be used as argument to gdb.
gdb -p <process id>
If you are using lodash and don't want to modify either array, you can use the function _.xor(). It compares the two arrays as sets and returns the set that contains their difference. If the length of this difference is zero, the two arrays are essentially equal:
var a = [1, 2, 3];
var b = [3, 2, 1];
var c = new Array(1, 2, 3);
_.xor(a, b).length === 0
true
_.xor(b, c).length === 0
true
Install NSSM and run the .bat file as a windows service. Works as expected
This is the code that's working for me, in Swift:
override func viewDidLoad()
{
super.viewDidLoad()
...
if tableView.respondsToSelector("setSeparatorInset:") {
tableView.separatorInset = UIEdgeInsetsZero
}
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell,forRowAtIndexPath indexPath: NSIndexPath)
{
if cell.respondsToSelector("setSeparatorInset:") {
cell.separatorInset.left = CGFloat(0.0)
}
if tableView.respondsToSelector("setLayoutMargins:") {
tableView.layoutMargins = UIEdgeInsetsZero
}
if cell.respondsToSelector("setLayoutMargins:") {
cell.layoutMargins.left = CGFloat(0.0)
}
}
This seems the cleanest to me (for now), as all the cell/tableView edge/margin adjustments are done in the tableView:willDisplayCell:forRowAtIndexPath:
method, without cramming unneccessary code into tableView:cellForRowAtIndexPath:
.
Btw, I'm only setting the cell's left separatorInset/layoutMargins, because in this case I don't want to screw up my constraints that I have set up in my cell.
Code updated to Swift 2.2 :
override func viewDidLoad() {
super.viewDidLoad()
if tableView.respondsToSelector(Selector("setSeparatorInset:")) {
tableView.separatorInset = UIEdgeInsetsZero
}
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell,forRowAtIndexPath indexPath: NSIndexPath) {
if cell.respondsToSelector(Selector("setSeparatorInset:")) {
cell.separatorInset.left = CGFloat(0.0)
}
if tableView.respondsToSelector(Selector("setLayoutMargins:")) {
tableView.layoutMargins = UIEdgeInsetsZero
}
if cell.respondsToSelector(Selector("setLayoutMargins:")) {
cell.layoutMargins.left = CGFloat(0.0)
}
}
you need to use backslash before ". like \"
From the doc here you can see that
A character preceded by a backslash ( \ ) is an escape sequence and has special meaning to the compiler.
and " (double quote) is a escacpe sequence
When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. For example, if you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes. To print the sentence
She said "Hello!" to me.
you would write
System.out.println("She said \"Hello!\" to me.");
Angular ui-router supports nested views. I haven't used it yet but looks very promising.
From the first link on google;
function call_func(_0x41dcx2) {
var _0x41dcx3 = eval('(' + _0x41dcx2 + ')');
var _0x41dcx4 = document['createElement']('div');
var _0x41dcx5 = _0x41dcx3['id'];
var _0x41dcx6 = _0x41dcx3['Student_name'];
var _0x41dcx7 = _0x41dcx3['student_dob'];
var _0x41dcx8 = '<b>ID:</b>';
_0x41dcx8 += '<a href="/learningyii/index.php?r=student/view& id=' + _0x41dcx5 + '">' + _0x41dcx5 + '</a>';
_0x41dcx8 += '<br/>';
_0x41dcx8 += '<b>Student Name:</b>';
_0x41dcx8 += _0x41dcx6;
_0x41dcx8 += '<br/>';
_0x41dcx8 += '<b>Student DOB:</b>';
_0x41dcx8 += _0x41dcx7;
_0x41dcx8 += '<br/>';
_0x41dcx4['innerHTML'] = _0x41dcx8;
_0x41dcx4['setAttribute']('class', 'view');
$('#StudentGridViewId')['find']('.items')['prepend'](_0x41dcx4);
};
It won't get you all the way back to source, and that's not really possible, but it'll get you out of a hole.
Given a dataframe like this:
RPT_Date STK_ID STK_Name sales
0 1980-01-01 0 Arthur 0
1 1980-01-02 1 Beate 4
2 1980-01-03 2 Cecil 2
3 1980-01-04 3 Dana 8
4 1980-01-05 4 Eric 4
5 1980-01-06 5 Fidel 5
6 1980-01-07 6 George 4
7 1980-01-08 7 Hans 7
8 1980-01-09 8 Ingrid 7
9 1980-01-10 9 Jones 4
There are multiple ways of selecting or slicing the data.
The most obvious is the .isin
feature. You can create a mask that gives you a series of True
/False
statements, which can be applied to a dataframe like this:
mask = df['STK_ID'].isin([4, 2, 6])
mask
0 False
1 False
2 True
3 False
4 True
5 False
6 True
7 False
8 False
9 False
Name: STK_ID, dtype: bool
df[mask]
RPT_Date STK_ID STK_Name sales
2 1980-01-03 2 Cecil 2
4 1980-01-05 4 Eric 4
6 1980-01-07 6 George 4
Masking is the ad-hoc solution to the problem, but does not always perform well in terms of speed and memory.
By setting the index to the STK_ID
column, we can use the pandas builtin slicing object .loc
df.set_index('STK_ID', inplace=True)
RPT_Date STK_Name sales
STK_ID
0 1980-01-01 Arthur 0
1 1980-01-02 Beate 4
2 1980-01-03 Cecil 2
3 1980-01-04 Dana 8
4 1980-01-05 Eric 4
5 1980-01-06 Fidel 5
6 1980-01-07 George 4
7 1980-01-08 Hans 7
8 1980-01-09 Ingrid 7
9 1980-01-10 Jones 4
df.loc[[4, 2, 6]]
RPT_Date STK_Name sales
STK_ID
4 1980-01-05 Eric 4
2 1980-01-03 Cecil 2
6 1980-01-07 George 4
This is the fast way of doing it, even if the indexing can take a little while, it saves time if you want to do multiple queries like this.
This can also be done by merging dataframes. This would fit more for a scenario where you have a lot more data than in these examples.
stkid_df = pd.DataFrame({"STK_ID": [4,2,6]})
df.merge(stkid_df, on='STK_ID')
STK_ID RPT_Date STK_Name sales
0 2 1980-01-03 Cecil 2
1 4 1980-01-05 Eric 4
2 6 1980-01-07 George 4
All the above methods work even if there are multiple rows with the same 'STK_ID'
do in your shell: $ env |grep LANG
This will probably show that your shell is not using a utf-8 locale.
I know that you can modify a javascript file when using Google Chrome.
Warning: If you refresh the page, all changes will go back to original file. I recommend to copy/paste the code somewhere else if you want to use it again.
Hope this helps!
Clone target repository same way like you cloning any other project:
git clone [email protected]:myuser/foo.git
Then install it in develop mode:
cd foo
pip install -e .
You can change anything you wan't and every code using foo
package will use modified code.
There 2 benefits ot this solution:
.git
dir, so it's regular Git repository. You can push to your fork right away.Check out my highly simplified Echo example: It is designed to use basic HTTP communication, but it can easily be modified to use named pipes by editing the app.config files for the client and server. Make the following changes:
Edit the server's app.config file, removing or commenting out the http baseAddress entry and adding a new baseAddress entry for the named pipe (called net.pipe). Also, if you don't intend on using HTTP for a communication protocol, make sure the serviceMetadata and serviceDebug is either commented out or deleted:
<configuration>
<system.serviceModel>
<services>
<service name="com.aschneider.examples.wcf.services.EchoService">
<host>
<baseAddresses>
<add baseAddress="net.pipe://localhost/EchoService"/>
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors></serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
Edit the client's app.config file so that the basicHttpBinding is either commented out or deleted and a netNamedPipeBinding entry is added. You will also need to change the endpoint entry to use the pipe:
<configuration>
<system.serviceModel>
<bindings>
<netNamedPipeBinding>
<binding name="NetNamedPipeBinding_IEchoService"/>
</netNamedPipeBinding>
</bindings>
<client>
<endpoint address = "net.pipe://localhost/EchoService"
binding = "netNamedPipeBinding"
bindingConfiguration = "NetNamedPipeBinding_IEchoService"
contract = "EchoServiceReference.IEchoService"
name = "NetNamedPipeBinding_IEchoService"/>
</client>
</system.serviceModel>
</configuration>
The above example will only run with named pipes, but nothing is stopping you from using multiple protocols to run your service. AFAIK, you should be able to have a server run a service using both named pipes and HTTP (as well as other protocols).
Also, the binding in the client's app.config file is highly simplified. There are many different parameters you can adjust, aside from just specifying the baseAddress...
I would have thought this would have been answered already - but surely what you want is this: box-shadow: 0 0 3px #CC0000;
Example: http://jsfiddle.net/vmzLW/
From Eugene Tskhovrebov
List<MyClass> myObjects = Arrays.asList(mapper.readValue(json, MyClass[].class))
This solution seems to be the best for me.
((SelectionListViewController *)myEditController).list
More examples:
int i = (int)19.5f; // (precision is lost)
id someObject = [NSMutableArray new]; // you don't need to cast id explicitly
I recommend @Jens Gustedt hexadecimal solution: use %a.
OP wants “print with maximum precision (or at least to the most significant decimal)”.
A simple example would be to print one seventh as in:
#include <float.h>
int Digs = DECIMAL_DIG;
double OneSeventh = 1.0/7.0;
printf("%.*e\n", Digs, OneSeventh);
// 1.428571428571428492127e-01
But let's dig deeper ...
Mathematically, the answer is "0.142857 142857 142857 ...", but we are using finite precision floating point numbers.
Let's assume IEEE 754 double-precision binary.
So the OneSeventh = 1.0/7.0
results in the value below. Also shown are the preceding and following representable double
floating point numbers.
OneSeventh before = 0.1428571428571428 214571170656199683435261249542236328125
OneSeventh = 0.1428571428571428 49212692681248881854116916656494140625
OneSeventh after = 0.1428571428571428 769682682968777953647077083587646484375
Printing the exact decimal representation of a double
has limited uses.
C has 2 families of macros in <float.h>
to help us.
The first set is the number of significant digits to print in a string in decimal so when scanning the string back,
we get the original floating point. There are shown with the C spec's minimum value and a sample C11 compiler.
FLT_DECIMAL_DIG 6, 9 (float) (C11)
DBL_DECIMAL_DIG 10, 17 (double) (C11)
LDBL_DECIMAL_DIG 10, 21 (long double) (C11)
DECIMAL_DIG 10, 21 (widest supported floating type) (C99)
The second set is the number of significant digits a string may be scanned into a floating point and then the FP printed, still retaining the same string presentation. There are shown with the C spec's minimum value and a sample C11 compiler. I believe available pre-C99.
FLT_DIG 6, 6 (float)
DBL_DIG 10, 15 (double)
LDBL_DIG 10, 18 (long double)
The first set of macros seems to meet OP's goal of significant digits. But that macro is not always available.
#ifdef DBL_DECIMAL_DIG
#define OP_DBL_Digs (DBL_DECIMAL_DIG)
#else
#ifdef DECIMAL_DIG
#define OP_DBL_Digs (DECIMAL_DIG)
#else
#define OP_DBL_Digs (DBL_DIG + 3)
#endif
#endif
The "+ 3" was the crux of my previous answer. Its centered on if knowing the round-trip conversion string-FP-string (set #2 macros available C89), how would one determine the digits for FP-string-FP (set #1 macros available post C89)? In general, add 3 was the result.
Now how many significant digits to print is known and driven via <float.h>
.
To print N significant decimal digits one may use various formats.
With "%e"
, the precision field is the number of digits after the lead digit and decimal point.
So - 1
is in order. Note: This -1
is not in the initial int Digs = DECIMAL_DIG;
printf("%.*e\n", OP_DBL_Digs - 1, OneSeventh);
// 1.4285714285714285e-01
With "%f"
, the precision field is the number of digits after the decimal point.
For a number like OneSeventh/1000000.0
, one would need OP_DBL_Digs + 6
to see all the significant digits.
printf("%.*f\n", OP_DBL_Digs , OneSeventh);
// 0.14285714285714285
printf("%.*f\n", OP_DBL_Digs + 6, OneSeventh/1000000.0);
// 0.00000014285714285714285
Note: Many are use to "%f"
. That displays 6 digits after the decimal point; 6 is the display default, not the precision of the number.
class Countries < ActiveRecord::Base
self.table_name = "cc"
end
In Rails 3.x this is the way to specify the table name.
Assuming you want to change the url to another within the same domain, you can use this:
history.pushState('data', '', 'http://www.yourcurrentdomain.com/new/path');
Use the Path
class from System.IO
. It contains useful calls for manipulating file paths, including GetDirectoryName
which does what you want, returning the directory portion of the file path.
Usage is simple.
string directoryPath = Path.GetDirectoryName(filePath);
Using the -clean
option is the way to go, as mentioned by the other answers.
Make sure that you remove it from your .ini
or shortcut after you've fixed the problem. It causes Eclipse to reevaluate all of the plugins everytime it starts and can dramatically increase startup time, depending on how many Eclipse plugins you have installed.
placeBets(betList, stakeAmt)
is an instance method not a static method. You need to create an instance of CBetfairAPI
first:
MyBetfair api = new MyBetfair();
ArrayList bets = api.placeBets(betList, stakeAmt);
Below code for black:-
<color name="black">#000000</color>
Now if i want to use opacity than you can use below code :-
<color name="black">#99000000</color>
and below for opacity code:-
Hex Opacity Values
100% — FF
95% — F2
90% — E6
85% — D9
80% — CC
75% — BF
70% — B3
65% — A6
60% — 99
55% — 8C
50% — 80
45% — 73
40% — 66
35% — 59
30% — 4D
25% — 40
20% — 33
15% — 26
10% — 1A
5% — 0D
0% — 00
If you're just checking if word
is a number, that's not too hard:
#include <ctype.h>
...
string word;
bool isNumber = true;
for(string::const_iterator k = word.begin(); k != word.end(); ++k)
isNumber &&= isdigit(*k);
Optimize as desired.
It took me some time to figure out the whole picture and I'd like to share here.
Visual Studio has two approaches to use package restore: Automatic Package Restore and MSBuild-Integrated package restore. The 'MSBuild-Integrated Package Restore' restores packages DURING the building process that might cause issues in some scenarios. The 'Automatic Package Restore' is the recommended approach by the NuGet team.
There are several steps to to make 'Automatic Package Restore' work:
In Visual Studio, Tools -> Extensions and Updates, Upgrade NuGet if there is a newer version (Version 2.7 or later)
If you use TFS, in your solution's .nuget folder, remove the NuGet.exe and NuGet.targes files. Then edit NuGet.Config to not check in NuGet packages:
<configuration>
<solution>
<add key="disableSourceControlIntegration" value="true" />
</solution>
</configuration>
If you checked in the solution's packages folder to TFS before, delete the folder and check in the deletion of package folder deletion.
If you don't use TFS, delete the .nuget folder.
In each project file (.csproj or .vbproj) in your solution, remove the line that references NuGet.targets file. The reference looks like this:
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
Remove this line in every project file in your solution.
In Visual Studio menu, either through
Tools -> Options -> Package Manager -> General or Tools -> NuGet Package Manager -> Package Manager Settings
please enable the following two options 1) 'Allow NuGet to download missing packages' 2) 'Automatically check for missing packages during build in Visual Studio'
Test your package restore configuration by the following steps
This started for me when I redirected my site to https:// (for SSL Certificate). From my experience with this issue, the session_start()
had to be before the browser saw any HTML code. For my example, I was using session_start()
in nav.php to determine the options of the navigation bar. I ended up placing session_start()
right after the php comments in the index.php file and every page which called nav.php. I was able to keep the php comments before session_start()
but could not keep the HTML comments above the php.
you can apply line-height on that <p>
element, so lines become larger.
I have a jQuery plugin called waitForImages
that can detect when background images have downloaded.
$('body')
.css('background-image','url(http://picture.de/image.png)')
.waitForImages(function() {
alert('Background image done loading');
// This *does* work
}, $.noop, true);
You can try:
top -bn1 | grep "Cpu(s)" | \
sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | \
awk '{print 100 - $1"%"}'
set /p choice= "Please Select one of the above options :"
echo '%choice%'
The space after =
is very important.
The values indicated by Ram Sharma might need to be changed in Wamp alias configuration files instead.
In <wamp_dir>/alias/phpmyadmin.conf
, in the <Directory>
section:
php_admin_value upload_max_filesize 1280M
php_admin_value post_max_size 1280M
php_admin_value max_execution_time 1800
A quick and easy Tidyverse solution to get a NA
count for all columns is to use summarise_all()
which I think makes a much easier to read solution than using purrr
or sapply
library(tidyverse)
# Example data
df <- tibble(col1 = c(1, 2, 3, NA),
col2 = c(NA, NA, "a", "b"))
df %>% summarise_all(~ sum(is.na(.)))
#> # A tibble: 1 x 2
#> col1 col2
#> <int> <int>
#> 1 1 2
Another way you can achieve the desired effect is to use this Material Search View library. It handles search history automatically and it's possible to provide search suggestions to the view as well.
Sample: (It's shown in Portuguese, but it also works in english and italian).
Before you can use this lib, you have to implement a class named MsvAuthority
inside the br.com.mauker
package on your app module, and it should have a public static String variable called CONTENT_AUTHORITY
. Give it the value you want and don't forget to add the same name on your manifest file. The lib will use this file to set the Content Provider authority.
Example:
MsvAuthority.java
package br.com.mauker;
public class MsvAuthority {
public static final String CONTENT_AUTHORITY = "br.com.mauker.materialsearchview.searchhistorydatabase";
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
<application ... >
<provider
android:name="br.com.mauker.materialsearchview.db.HistoryProvider"
android:authorities="br.com.mauker.materialsearchview.searchhistorydatabase"
android:exported="false"
android:protectionLevel="signature"
android:syncable="true"/>
</application>
</manifest>
To use it, add the dependency:
compile 'br.com.mauker.materialsearchview:materialsearchview:1.2.0'
And then, on your Activity
layout file, add the following:
<br.com.mauker.materialsearchview.MaterialSearchView
android:id="@+id/search_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
After that, you'll just need to get the MaterialSearchView
reference by using getViewById()
, and open it up or close it using MaterialSearchView#openSearch()
and MaterialSearchView#closeSearch()
.
P.S.: It's possible to open and close the view not only from the Toolbar
. You can use the openSearch()
method from basically any Button
, such as a Floating Action Button.
// Inside onCreate()
MaterialSearchView searchView = (MaterialSearchView) findViewById(R.id.search_view);
Button bt = (Button) findViewById(R.id.button);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
searchView.openSearch();
}
});
You can also close the view using the back button, doing the following:
@Override
public void onBackPressed() {
if (searchView.isOpen()) {
// Close the search on the back button press.
searchView.closeSearch();
} else {
super.onBackPressed();
}
}
For more information on how to use the lib, check the github page.
The first parameter to LayoutParams is the width and the second is the height. So if you want the width to be FILL_PARENT, but the width to be, say, 20px, then use something new LayoutParams(FILL_PARENT, 20). Of course you should never use actual pixels in your code; you'll need to conver that to density-independent pixels, but you get the idea. Also, you need to make sure your parent LinearLayout has the right width and height that you're looking for. Seems to be you want the LinearLayout to fill the parent width-wise and then have the adview fill that linearlayout witdh-wise as well, so you probably need to specify android:layout_width:"fill_parent" and android:layout_height:"wrap_content" in your linear layout's xml.
The language standard simply doesn't allow for it. Labels can only be followed by statements, and declarations do not count as statements in C. The easiest way to get around this is by inserting an empty statement after your label, which relieves you from keeping track of the scope the way you would need to inside a block.
#include <stdio.h>
int main ()
{
printf("Hello ");
goto Cleanup;
Cleanup: ; //This is an empty statement.
char *str = "World\n";
printf("%s\n", str);
}
I will add my solution as well - I found it the most friendly for myself from what I read in this thread.
export const aggregate = (...mixins) => (Base) => {
const copyProps = (target, source) => {
Object.getOwnPropertyNames(source)
.concat(Object.getOwnPropertySymbols(source))
.forEach((prop) => {
if (prop.match(/^(?:constructor|prototype|arguments|caller|name|bind|call|apply|toString|length)$/)) {
return;
}
Object.defineProperty(target, prop, Object.getOwnPropertyDescriptor(source, prop));
});
};
mixins.forEach((mixin) => {
copyProps(Base, mixin);
copyProps(Base.prototype, mixin.prototype);
});
return Base;
};
You can use it then like this:
class _MyBaseClass {}
const MyBaseClass = aggregate(ExtensionOne, ExtensionTwo)(_MyBaseClass);
String dateTime="15-3-2019 09:50 AM" //time should be two digit like 08,09,10
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm a");
LocalDateTime zdt = LocalDateTime.parse(dateTime,dtf);
LocalDateTime now = LocalDateTime.now();
ZoneId zone = ZoneId.of("Asia/Kolkata");
ZoneOffset zoneOffSet = zone.getRules().getOffset(now);
long a= zdt.toInstant(zoneOffSet).toEpochMilli();
Log.d("time","---"+a);
you can get zone id form this a link!
This is yet another implementation based on the code posted by Nicolas Tyler.
The following bugs are fixed:
minScale
to a number less than 1 now workssetImageBitmap()
to set the image (you can use, for example setImageResource()
The following things, amongst others are tidied up:
An OnTouchListener
is not used, it's not necessary because the the class can just implement the onTouchEvent()
method.
The assignment right = width * saveScale - width - (2 * redundantXSpace * saveScale);
has been simplified to right = (originalBitmapWidth * saveScale) - width
Which, in my option, is much less confusing.
It's not perfect but here you go:
import android.content.Context;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.widget.ImageView;
/**
* Created by alex on 23/02/16.
* Based on code posted by Nicolas Tyler here:
* https://stackoverflow.com/questions/6650398/android-imageview-zoom-in-and-zoom-out
*/
public class ZoomableImageView extends ImageView {
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
mode = ZOOM;
return true;
}
@Override
public boolean onScale(ScaleGestureDetector detector) {
float scaleFactor = detector.getScaleFactor();
float newScale = saveScale * scaleFactor;
if (newScale < maxScale && newScale > minScale) {
saveScale = newScale;
float width = getWidth();
float height = getHeight();
right = (originalBitmapWidth * saveScale) - width;
bottom = (originalBitmapHeight * saveScale) - height;
float scaledBitmapWidth = originalBitmapWidth * saveScale;
float scaledBitmapHeight = originalBitmapHeight * saveScale;
if (scaledBitmapWidth <= width || scaledBitmapHeight <= height) {
matrix.postScale(scaleFactor, scaleFactor, width / 2, height / 2);
} else {
matrix.postScale(scaleFactor, scaleFactor, detector.getFocusX(), detector.getFocusY());
}
}
return true;
}
}
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
static final int CLICK = 3;
private int mode = NONE;
private Matrix matrix = new Matrix();
private PointF last = new PointF();
private PointF start = new PointF();
private float minScale = 0.5f;
private float maxScale = 4f;
private float[] m;
private float redundantXSpace, redundantYSpace;
private float saveScale = 1f;
private float right, bottom, originalBitmapWidth, originalBitmapHeight;
private ScaleGestureDetector mScaleDetector;
public ZoomableImageView(Context context) {
super(context);
init(context);
}
public ZoomableImageView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public ZoomableImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
super.setClickable(true);
mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
m = new float[9];
setImageMatrix(matrix);
setScaleType(ScaleType.MATRIX);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int bmHeight = getBmHeight();
int bmWidth = getBmWidth();
float width = getMeasuredWidth();
float height = getMeasuredHeight();
//Fit to screen.
float scale = width > height ? height / bmHeight : width / bmWidth;
matrix.setScale(scale, scale);
saveScale = 1f;
originalBitmapWidth = scale * bmWidth;
originalBitmapHeight = scale * bmHeight;
// Center the image
redundantYSpace = (height - originalBitmapHeight);
redundantXSpace = (width - originalBitmapWidth);
matrix.postTranslate(redundantXSpace / 2, redundantYSpace / 2);
setImageMatrix(matrix);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
mScaleDetector.onTouchEvent(event);
matrix.getValues(m);
float x = m[Matrix.MTRANS_X];
float y = m[Matrix.MTRANS_Y];
PointF curr = new PointF(event.getX(), event.getY());
switch (event.getAction()) {
//when one finger is touching
//set the mode to DRAG
case MotionEvent.ACTION_DOWN:
last.set(event.getX(), event.getY());
start.set(last);
mode = DRAG;
break;
//when two fingers are touching
//set the mode to ZOOM
case MotionEvent.ACTION_POINTER_DOWN:
last.set(event.getX(), event.getY());
start.set(last);
mode = ZOOM;
break;
//when a finger moves
//If mode is applicable move image
case MotionEvent.ACTION_MOVE:
//if the mode is ZOOM or
//if the mode is DRAG and already zoomed
if (mode == ZOOM || (mode == DRAG && saveScale > minScale)) {
float deltaX = curr.x - last.x;// x difference
float deltaY = curr.y - last.y;// y difference
float scaleWidth = Math.round(originalBitmapWidth * saveScale);// width after applying current scale
float scaleHeight = Math.round(originalBitmapHeight * saveScale);// height after applying current scale
boolean limitX = false;
boolean limitY = false;
//if scaleWidth is smaller than the views width
//in other words if the image width fits in the view
//limit left and right movement
if (scaleWidth < getWidth() && scaleHeight < getHeight()) {
// don't do anything
}
else if (scaleWidth < getWidth()) {
deltaX = 0;
limitY = true;
}
//if scaleHeight is smaller than the views height
//in other words if the image height fits in the view
//limit up and down movement
else if (scaleHeight < getHeight()) {
deltaY = 0;
limitX = true;
}
//if the image doesnt fit in the width or height
//limit both up and down and left and right
else {
limitX = true;
limitY = true;
}
if (limitY) {
if (y + deltaY > 0) {
deltaY = -y;
} else if (y + deltaY < -bottom) {
deltaY = -(y + bottom);
}
}
if (limitX) {
if (x + deltaX > 0) {
deltaX = -x;
} else if (x + deltaX < -right) {
deltaX = -(x + right);
}
}
//move the image with the matrix
matrix.postTranslate(deltaX, deltaY);
//set the last touch location to the current
last.set(curr.x, curr.y);
}
break;
//first finger is lifted
case MotionEvent.ACTION_UP:
mode = NONE;
int xDiff = (int) Math.abs(curr.x - start.x);
int yDiff = (int) Math.abs(curr.y - start.y);
if (xDiff < CLICK && yDiff < CLICK)
performClick();
break;
// second finger is lifted
case MotionEvent.ACTION_POINTER_UP:
mode = NONE;
break;
}
setImageMatrix(matrix);
invalidate();
return true;
}
public void setMaxZoom(float x) {
maxScale = x;
}
private int getBmWidth() {
Drawable drawable = getDrawable();
if (drawable != null) {
return drawable.getIntrinsicWidth();
}
return 0;
}
private int getBmHeight() {
Drawable drawable = getDrawable();
if (drawable != null) {
return drawable.getIntrinsicHeight();
}
return 0;
}
}
In the Terminal, type:
$ curl -V
That's a capital V
for the version
The simplest way is using libraries like google-http-java-client but if you want parse the JSON response by yourself you can do that in a multiple ways, you can use org.json, json-simple, Gson, minimal-json, jackson-mapper-asl (from 1.x)... etc
A set of simple examples:
Using Gson:
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class Gson {
public static void main(String[] args) {
}
public HttpResponse http(String url, String body) {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpPost request = new HttpPost(url);
StringEntity params = new StringEntity(body);
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
com.google.gson.Gson gson = new com.google.gson.Gson();
Response respuesta = gson.fromJson(json, Response.class);
System.out.println(respuesta.getExample());
System.out.println(respuesta.getFr());
} catch (IOException ex) {
}
return null;
}
public class Response{
private String example;
private String fr;
public String getExample() {
return example;
}
public void setExample(String example) {
this.example = example;
}
public String getFr() {
return fr;
}
public void setFr(String fr) {
this.fr = fr;
}
}
}
Using json-simple:
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JsonSimple {
public static void main(String[] args) {
}
public HttpResponse http(String url, String body) {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpPost request = new HttpPost(url);
StringEntity params = new StringEntity(body);
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
try {
JSONParser parser = new JSONParser();
Object resultObject = parser.parse(json);
if (resultObject instanceof JSONArray) {
JSONArray array=(JSONArray)resultObject;
for (Object object : array) {
JSONObject obj =(JSONObject)object;
System.out.println(obj.get("example"));
System.out.println(obj.get("fr"));
}
}else if (resultObject instanceof JSONObject) {
JSONObject obj =(JSONObject)resultObject;
System.out.println(obj.get("example"));
System.out.println(obj.get("fr"));
}
} catch (Exception e) {
// TODO: handle exception
}
} catch (IOException ex) {
}
return null;
}
}
etc...
You should know that CPython doesn't really support multithreading (it does, but not optimal) because of the Global Interpreter Lock. It also has no Optimisation mechanisms for recursion, and has many other limitations that other implementations and libraries try to fill.
You should take a look at this page on the python wiki.
Look at the code snippets on this page, it'll give you a good idea of what an interpreter is.
Without reading your code but just your scenario, I would solve by using localStorage
.
Here's an example, I'll use prompt()
for short.
On page1:
window.onload = function() {
var getInput = prompt("Hey type something here: ");
localStorage.setItem("storageName",getInput);
}
On page2:
window.onload = alert(localStorage.getItem("storageName"));
You can also use cookies but localStorage allows much more spaces, and they aren't sent back to servers when you request pages.
grep -rl SOSTITUTETHIS . | xargs sed -Ei 's/(.*)SOSTITUTETHIS(.*)/\1WITHTHIS\2/g'
Or use the XmlSerializer class.
XmlSerializer xs = new XmlSerializer(objectType);
obj = xs.Deserialize(new StringReader(yourXmlString));
I use this
var e = document.getElementById('ticket_category_clone').value;
Notice that you don't need the '#' character in javascript.
function check () {
var str = document.getElementById('ticket_category_clone').value;
if (str==="Hardware")
{
SPICEWORKS.utils.addStyle('#ticket_c_hardware_clone{display: none !important;}');
}
}
SPICEWORKS.app.helpdesk.ready(check);?
My problem was overwriting my query string parameters with default values:
routes.MapRoute(
"apiRoute",
"api/{action}/{key}",
new { controller = "Api", action = "Prices", key = ""}
);
No matter what I plugged into query string or how only key=""
results.
Then got rid of default overwrites using UrlParameter.Optional:
routes.MapRoute(
"apiRoute",
"api/{action}/{key}",
new { controller = "Api", action = "Prices", key = UrlParameter.Optional }
);
now
prices/{key}
or
prices?key={key}
both work fine.
Starting with Python 2.6 you can use anything implementing the TextIOBase
API from the io module as a replacement.
This solution also enables you to use sys.stdout.buffer.write()
in Python 3 to write (already) encoded byte strings to stdout (see stdout in Python 3).
Using StringIO
wouldn't work then, because neither sys.stdout.encoding
nor sys.stdout.buffer
would be available.
A solution using TextIOWrapper:
import sys
from io import TextIOWrapper, BytesIO
# setup the environment
old_stdout = sys.stdout
sys.stdout = TextIOWrapper(BytesIO(), sys.stdout.encoding)
# do something that writes to stdout or stdout.buffer
# get output
sys.stdout.seek(0) # jump to the start
out = sys.stdout.read() # read output
# restore stdout
sys.stdout.close()
sys.stdout = old_stdout
This solution works for Python 2 >= 2.6 and Python 3.
Please note that our new sys.stdout.write()
only accepts unicode strings and sys.stdout.buffer.write()
only accepts byte strings.
This might not be the case for old code, but is often the case for code that is built to run on Python 2 and 3 without changes, which again often makes use of sys.stdout.buffer
.
You can build a slight variation that accepts unicode and byte strings for write()
:
class StdoutBuffer(TextIOWrapper):
def write(self, string):
try:
return super(StdoutBuffer, self).write(string)
except TypeError:
# redirect encoded byte strings directly to buffer
return super(StdoutBuffer, self).buffer.write(string)
You don't have to set the encoding of the buffer the sys.stdout.encoding, but this helps when using this method for testing/comparing script output.
Would this help?
final List<String> l = new ArrayList<String>();
for (int i = 0; i < 10; i++) l.add("Number " + i);
for (int i = 0; i < 10; i++) System.out.println(l.get(i));
I was very reluctant to choose the path I finally decide to take because of many answers. While they add more understanding to what is SQL and its principles, I decided to become an outlaw. I was also hesitant to post my findings as for some it's more important to vent frustration to someone breaking the rules rather than understanding that there are very few universal truthes.
I have tested it extensively and, in my specific case, it was way more efficient than both using array type (generously offered by PostgreSQL) or querying another table.
Here is my answer: I have successfully implemented a list into a single field in PostgreSQL, by making use of the fixed length of each item of the list. Let say each item is a color as an ARGB hex value, it means 8 char. So you can create your array of max 10 items by multiplying by the length of each item:
ALTER product ADD color varchar(80)
In case your list items length differ you can always fill the padding with \0
NB: Obviously this is not necessarily the best approach for hex number since a list of integers would consume less storage but this is just for the purpose of illustrating this idea of array by making use of a fixed length allocated to each item.
The reason why: 1/ Very convenient: retrieve item i at substring i*n, (i +1)*n. 2/ No overhead of cross tables queries. 3/ More efficient and cost-saving on the server side. The list is like a mini blob that the client will have to split.
While I respect people following rules, many explanations are very theoretical and often fail to acknowledge that, in some specific cases, especially when aiming for cost optimal with low-latency solutions, some minor tweaks are more than welcome.
"God forbid that it is violating some holy sacred principle of SQL": Adopting a more open-minded and pragmatic approach before reciting the rules is always the way to go. Else you might end up like a candid fanatic reciting the Three Laws of Robotics before being obliterated by Skynet
I don't pretend that this solution is a breakthrough, nor that it is ideal in term of readability and database flexibility, but it can certainly give you an edge when it comes to latency.
The API Guide has it all wrong (really Google?). With Maps API v2 you do not need to enable a layer to show yourself, there is a simple call to the GoogleMaps instance you created with your map.
The actual documentation that Google provides gives you your answer. You just need to
// map is a GoogleMap object
map.isMyLocationEnabled = true
// map is a GoogleMap object
map.setMyLocationEnabled(true);
and watch the magic happen.
Just make sure that you have location permission and requested it at runtime on API Level 23 (M) or above
I think because C would be seen the C drive on the client pc, it wont let you. And if it could do this, it would be a big security hole.
I ran this on MacOS /Applications/Python\ 3.6/Install\ Certificates.command
$("input").is(":not(':checked')"))
This is jquery 1.3, mind the ' and " signs!
You can follow this code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$(".add").on("click", function () {
var v = $(this).closest(".division").find("input[name='roll']").val();
alert(v);
});
});
</script>
<?php
for ($i = 1; $i <= 5; $i++) {
echo'<div class = "division">'
. '<form method="POST" action="">'
. '<p><input type="number" name="roll" placeholder="Enter Roll"></p>'
. '<p><input type="button" class="add" name = "submit" value = "Click"></p>'
. '</form></div>';
}
?>
You can get idea from this.
Best way is to use the Carbon dependency.
With Carbon\Carbon::now();
you get the current Datetime.
With Carbon you can do like enything with the DateTime. Event things like this:
$tomorrow = Carbon::now()->addDay();
$lastWeek = Carbon::now()->subWeek();
There is the Math.pow(double a, double b)
method. Note that it returns a double, you will have to cast it to an int like (int)Math.pow(double a, double b)
.
curl
used to include a list of accepted certificate authorities (CAs) but no longer bundles ANY CA certs since 7.18.1 and onwards. So by default it'll reject all TLS/SSL certificates as unverifiable.
You'll have to get your CA's root certificate and point curl at it. More details at curl's details on TLS/SSL certificates verification.
I also had the issue of the Eclipse Tomcat Server timing out and tried every suggestion including:
Nothing worked until I read a comment on a related issue and realized that I had added a breakpoint in an interceptor class after a big code change and had forgotten to toggle it off. I removed it and all other breakpoints and Tomcat started right up as it usually did.
While
constructs are terminated not with an End While
but with a Wend
.
While counter < 20
counter = counter + 1
Wend
Note that this information is readily available in the documentation; just press F1. The page you link to deals with Visual Basic .NET, not VBA. While (no pun intended) there is some degree of overlap in syntax between VBA and VB.NET, one can't just assume that the documentation for the one can be applied directly to the other.
Also in the VBA help file:
Tip The
Do...Loop
statement provides a more structured and flexible way to perform looping.
here is my solution. base on spring-boot.1.2.5.RELEASE.
application.properties
first.datasource.driver-class-name=com.mysql.jdbc.Driver
first.datasource.url=jdbc:mysql://127.0.0.1:3306/test
first.datasource.username=
first.datasource.password=
first.datasource.validation-query=select 1
second.datasource.driver-class-name=com.mysql.jdbc.Driver
second.datasource.url=jdbc:mysql://127.0.0.1:3306/test2
second.datasource.username=
second.datasource.password=
second.datasource.validation-query=select 1
DataSourceConfig.java
@Configuration
public class DataSourceConfig {
@Bean
@Primary
@ConfigurationProperties(prefix="first.datasource")
public DataSource firstDataSource() {
DataSource ds = DataSourceBuilder.create().build();
return ds;
}
@Bean
@ConfigurationProperties(prefix="second.datasource")
public DataSource secondDataSource() {
DataSource ds = DataSourceBuilder.create().build();
return ds;
}
}
The best way is to use this line:
var mapUrl = "http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=16900+North+Bay+Road,+Sunny+Isles+Beach,+FL+33160&aq=0&sll=37.0625,-95.677068&sspn=61.282355,146.513672&ie=UTF8&hq=&hnear=16900+North+Bay+Road,+Sunny+Isles+Beach,+FL+33160&spn=0.01628,0.025663&z=14&iwloc=A&output=embed"
Remember to replace the first and second addresses when necessary.
You can also specify the TNS name in the JDBC URL as below
jdbc:oracle:thin:@(DESCRIPTION =(ADDRESS_LIST =(ADDRESS =(PROTOCOL=TCP)(HOST=blah.example.com)(PORT=1521)))(CONNECT_DATA=(SID=BLAHSID)(GLOBAL_NAME=BLAHSID.WORLD)(SERVER=DEDICATED)))
For Bootstrap 4
In the same line as image
add height: 300px;
<img src="..." style="height: 300px;" class="d-block w-100" alt="image">
You are talking about SQL Profiler.
A short traverse could be given too using the sub-expression operator $( ), which returns the result of one or more statements.
$hash = @{ a = 1; b = 2; c = 3}
forEach($y in $hash.Keys){
Write-Host "$y -> $($hash[$y])"
}
Result:
a -> 1
b -> 2
c -> 3
Keep in mind that there are processes on the database which may not currently support a session.
If you're interested in all processes you'll want to look to v$process (or gv$process on RAC)
Dim row As DataRow
For Each row In dtDataTable.Rows
Dim strDetail As String
strDetail = row("Detail")
Console.WriteLine("Processing Detail {0}", strDetail)
Next row
Chapter 4.8 Block Structure in K&R's The C Programming Language 2.Ed.:
An automatic variable declared and initialized in a block is initialized each time the block is entered.
I might have missed seeing the relevant description in the book like:
An automatic variable declared and initialized in a block is allocated only one time before the block is entered.
But a simple test can prove the assumption held:
#include <stdio.h>
int main(int argc, char *argv[]) {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
int k;
printf("%p\n", &k);
}
}
return 0;
}
If you can comment out code and your program still works, then yes, that code was optional.
.strip()
with no arguments (or None
as the first argument) removes all whitespace at the start and end, including spaces, tabs, newlines and carriage returns. Leaving it in doesn't do any harm, and allows your program to deal with unexpected extra whitespace inserted into the file.
For example, by using .strip()
, the following two lines in a file would lead to the same end result:
foo\tbar \n
foo\tbar\n
I'd say leave it in.
Which whitespace character? The most common is the normal space, which is between each word in my sentences. This is just " "
.
Chiming in to recommend the use of the xmltodict library. It handled your xml text pretty well and I've used it for ingesting an xml file with almost a million records.
So for today, jspdf-1.5.3. To answer the question of having the pdf file page exactly same as the canvas. After many tries of different combinations, I figured you gotta do something like this. We first need to set the height and width for the output pdf file with correct orientation, otherwise the sides might be cut off. Then we get the dimensions from the 'pdf' file itself, if you tried to use the canvas's dimensions, the sides might be cut off again. I am not sure why that happens, my best guess is the jsPDF convert the dimensions in other units in the library.
// Download button
$("#download-image").on('click', function () {
let width = __CANVAS.width;
let height = __CANVAS.height;
//set the orientation
if(width > height){
pdf = new jsPDF('l', 'px', [width, height]);
}
else{
pdf = new jsPDF('p', 'px', [height, width]);
}
//then we get the dimensions from the 'pdf' file itself
width = pdf.internal.pageSize.getWidth();
height = pdf.internal.pageSize.getHeight();
pdf.addImage(__CANVAS, 'PNG', 0, 0,width,height);
pdf.save("download.pdf");
});
Learnt about switching orientations from here: https://github.com/MrRio/jsPDF/issues/476
If you want to echo all days between the start and end date, I came up with this :
$startdatum = $_POST['start']; // starting date
$einddatum = $_POST['eind']; // end date
$now = strtotime($startdatum);
$your_date = strtotime($einddatum);
$datediff = $your_date - $now;
$number = floor($datediff/(60*60*24));
for($i=0;$i <= $number; $i++)
{
echo date('d-m-Y' ,strtotime("+".$i." day"))."<br>";
}
They're hints to the compiler to generate the hint prefixes on branches. On x86/x64, they take up one byte, so you'll get at most a one-byte increase for each branch. As for performance, it entirely depends on the application -- in most cases, the branch predictor on the processor will ignore them, these days.
Edit: Forgot about one place they can actually really help with. It can allow the compiler to reorder the control-flow graph to reduce the number of branches taken for the 'likely' path. This can have a marked improvement in loops where you're checking multiple exit cases.
Something like this should work
CSS:
input {
float: left;
clear: left;
width: 50px;
line-height: 20px;
}
label {
float: left;
vertical-align: middle;
}
Arrays.asList can help here:
new ArrayList<Integer>(Arrays.asList(1,2,3,5,8,13,21));
With the latest NodeJS you can experiment with this monkey patch:
const http = require("http");
const originalOnSocket = http.ClientRequest.prototype.onSocket;
require("http").ClientRequest.prototype.onSocket = function(socket) {
const that = this;
socket.setTimeout(this.timeout ? this.timeout : 3000);
socket.on('timeout', function() {
that.abort();
});
originalOnSocket.call(this, socket);
};
You can also use WriteConsole method to print on console.
AllocConsole();
LPSTR lpBuff = "Hello Win32 API";
DWORD dwSize = 0;
WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), lpBuff, lstrlen(lpBuff), &dwSize, NULL);
You can adjust the plot margins with plot.margin
in theme()
and then move your axis labels and title with the vjust
argument of element_text()
. For example :
library(ggplot2)
library(grid)
qplot(rnorm(100)) +
ggtitle("Title") +
theme(axis.title.x=element_text(vjust=-2)) +
theme(axis.title.y=element_text(angle=90, vjust=-0.5)) +
theme(plot.title=element_text(size=15, vjust=3)) +
theme(plot.margin = unit(c(1,1,1,1), "cm"))
will give you something like this :
If you want more informations about the different theme()
parameters and their arguments, you can just enter ?theme
at the R prompt.
function get_dir_size($directory){
$size = 0;
$files = glob($directory.'/*');
foreach($files as $path){
is_file($path) && $size += filesize($path);
is_dir($path) && $size += get_dir_size($path);
}
return $size;
}
Don't echo out HTML.
If you want to use
<?php echo "<h1> $title; </h1>"; ?>
you should be doing this:
<h1><?= $title;?></h1>
You can try to use this
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape
android:innerRadius="0dp"
android:shape="ring"
android:thicknessRatio="2"
android:useLevel="false" >
<solid android:color="@color/button_blue_two" />
</shape>
</item>
and you don't have to bother the width and height aspect ratio if you are using this for a textview
Use Thread.Sleep
when you want to block the current thread.
Use Task.Delay
when you want a logical delay without blocking the current thread.
Efficiency should not be a paramount concern with these methods. Their primary real-world use is as retry timers for I/O operations, which are on the order of seconds rather than milliseconds.
Oh, but that's ugly, non-object-oriented code. The moment you see "if/else" and "typeof", you should be thinking polymorphism. This is the wrong way to go. I think generics are your friend here.
How many types do you plan to deal with?
UPDATE:
If you're just talking about String and int, here's one way you might do it. Start with the interface XmlGenerator (enough with "foo"):
package generics;
public interface XmlGenerator<T>
{
String getXml(T value);
}
And the concrete implementation XmlGeneratorImpl:
package generics;
public class XmlGeneratorImpl<T> implements XmlGenerator<T>
{
private Class<T> valueType;
private static final int DEFAULT_CAPACITY = 1024;
public static void main(String [] args)
{
Integer x = 42;
String y = "foobar";
XmlGenerator<Integer> intXmlGenerator = new XmlGeneratorImpl<Integer>(Integer.class);
XmlGenerator<String> stringXmlGenerator = new XmlGeneratorImpl<String>(String.class);
System.out.println("integer: " + intXmlGenerator.getXml(x));
System.out.println("string : " + stringXmlGenerator.getXml(y));
}
public XmlGeneratorImpl(Class<T> clazz)
{
this.valueType = clazz;
}
public String getXml(T value)
{
StringBuilder builder = new StringBuilder(DEFAULT_CAPACITY);
appendTag(builder);
builder.append(value);
appendTag(builder, false);
return builder.toString();
}
private void appendTag(StringBuilder builder) { this.appendTag(builder, false); }
private void appendTag(StringBuilder builder, boolean isClosing)
{
String valueTypeName = valueType.getName();
builder.append("<").append(valueTypeName);
if (isClosing)
{
builder.append("/");
}
builder.append(">");
}
}
If I run this, I get the following result:
integer: <java.lang.Integer>42<java.lang.Integer>
string : <java.lang.String>foobar<java.lang.String>
I don't know if this is what you had in mind.
The plist: /private/var/mobile/Library/RemoteNotification/Clients.plist
... contains the registered clients for push notifications. Removing your app's entry will cause the prompt to re-appear
You can either use:
<button onclick="window.history.back()">Back</button>
or..
<button onclick="window.history.go(-1)">Back</button>
The difference, of course, is back()
only goes back 1 page but go()
goes back/forward the number of pages you pass as a parameter, relative to your current page.
This may not be the exact answer for the OP, but is the answer to the Title of the question: How to Update Gradle in Android Studio (AS):
var icon1 = "imageA.png";
var icon2 = "imageB.png";
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: icon1,
title: "some marker"
});
google.maps.event.addListener(marker, 'mouseover', function() {
marker.setIcon(icon2);
});
google.maps.event.addListener(marker, 'mouseout', function() {
marker.setIcon(icon1);
});
Firstly, you must understand that DataFrames
are distributed, that means you can't access them in a typical procedural way, you must do an analysis first. Although, you are asking about Scala
I suggest you to read the Pyspark Documentation, because it has more examples than any of the other documentations.
However, continuing with my explanation, I would use some methods of the RDD
API cause all DataFrame
s have one RDD
as attribute. Please, see my example bellow, and notice how I take the 2nd record.
df = sqlContext.createDataFrame([("a", 1), ("b", 2), ("c", 3)], ["letter", "name"])
myIndex = 1
values = (df.rdd.zipWithIndex()
.filter(lambda ((l, v), i): i == myIndex)
.map(lambda ((l,v), i): (l, v))
.collect())
print(values[0])
# (u'b', 2)
Hopefully, someone gives another solution with fewer steps.
If you truly want to discard the commits you've made locally, i.e. never have them in the history again, you're not asking how to pull - pull means merge, and you don't need to merge. All you need do is this:
# fetch from the default remote, origin
git fetch
# reset your current branch (master) to origin's master
git reset --hard origin/master
I'd personally recommend creating a backup branch at your current HEAD first, so that if you realize this was a bad idea, you haven't lost track of it.
If on the other hand, you want to keep those commits and make it look as though you merged with origin, and cause the merge to keep the versions from origin only, you can use the ours
merge strategy:
# fetch from the default remote, origin
git fetch
# create a branch at your current master
git branch old-master
# reset to origin's master
git reset --hard origin/master
# merge your old master, keeping "our" (origin/master's) content
git merge -s ours old-master
In my Case since I was working in my development environment, someone had shut down the Domain Controller and Windows Credentials couldn't be authenticated. After turning on the Domain Controller, the error disappeared and everything worked just fine.
Your regex "sentence(.*)"
is right. To retrieve the contents of the group in parenthesis, you would call:
Pattern p = Pattern.compile( "sentence(.*)" );
Matcher m = p.matcher( "some lame sentence that is awesome" );
if ( m.find() ) {
String s = m.group(1); // " that is awesome"
}
Note the use of m.find()
in this case (attempts to find anywhere on the string) and not m.matches()
(would fail because of the prefix "some lame"; in this case the regex would need to be ".*sentence(.*)"
)
Arrow looks promising for this:
>>> import arrow
>>> arrow.get('2014-11-13T14:53:18.694072+00:00').datetime
datetime.datetime(2014, 11, 13, 14, 53, 18, 694072, tzinfo=tzoffset(None, 0))
Arrow is a Python library that provides a sensible, intelligent way of creating, manipulating, formatting and converting dates and times. Arrow is simple, lightweight and heavily inspired by moment.js and requests.
I am trying to check if a key exist in an array in angular way and landed here on this question. In my Angularjs 1.4 ternary operator worked like below
{{ CONDITION ? TRUE : FALSE }}
hence for the array key exist i did a simple JS check
Solution 1 : {{ array['key'] !== undefined ? array['key'] : 'n/a' }}
Solution 2 : {{ "key" in array ? array['key'] : 'n/a' }}
It turns out, the error is very vague indeed!
1) Password was setting while logged on as root, as it was updating the user/password field in the users table under MySql.
2) When logged on as user, password was in fact not changing and even though there was one specified in the users table in MySql, config.inc.php file allowed authentication without password.
Solution:
Change following value to false
in the config.inc.php.
$cfg['Servers'][$i]['AllowNoPassword'] = true;
So that it reads
$cfg['Servers'][$i]['AllowNoPassword'] = false;
Change user's host from Any
or %
to localhost
in MySql users table. This could easily be achieved via phpMyAdmin console.
These two changes allowed me to authenticate as user with it's password and disallowed authentication without password.
It also allowed user to change its password while logged on as user.
Seems all permissions and the rest was fixed with these two changes.
Simple solution :-
List<String> list = new ArrayList<String>(Arrays.asList("a", "b", "d", "c"));
List<String> list2 = new ArrayList<String>(Arrays.asList("b", "f", "c"));
list.retainAll(list2);
list2.removeAll(list);
System.out.println("similiar " + list);
System.out.println("different " + list2);
Output :-
similiar [b, c]
different [f]
this
referes to the object the onclick
method belongs to. So inside func
this
would be the DOM node of the a
element and this.innerText
would be here
.
In swift:
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
if scrollView.panGestureRecognizer.translation(in: scrollView).y < 0 {
print("down")
} else {
print("up")
}
}
You can do it also in scrollViewDidScroll.
Here possible to get the User current location Without the use of GPS and Network Provider.
1 . Convert cellLocation to real location (Latitude and Longitude), using "http://www.google.com/glm/mmap"
From Python 2.5 onwards, you can use
from ..Modules import LDAPManager
The leading period takes you "up" a level in your heirarchy.
See the Python docs on intra-package references for imports.
Also note that the SPOOL
output is driven by a few SQLPlus settings:
SET LINESIZE nn
- maximum line width; if the output is longer it will wrap to display the contents of each result row.
SET TRIMSPOOL OFF|ON
- if set OFF
(the default), every output line will be padded to LINESIZE
. If set ON
, every output line will be trimmed.
SET PAGESIZE nn
- number of lines to output for each repetition of the header. If set to zero, no header is output; just the detail.
Those are the biggies, but there are some others to consider if you just want the output without all the SQLPlus chatter.
It allows browsers to determine if they can handle the scripting/style language before making a request for the script or stylesheet (or, in the case of embedded script/style, identify which language is being used).
This would be much more important if there had been more competition among languages in browser space, but VBScript never made it beyond IE and PerlScript never made it beyond an IE specific plugin while JSSS was pretty rubbish to begin with.
The draft of HTML5 makes the attribute optional.
SELECT * from games WHERE (lower(title) LIKE 'age of empires III');
The above query doesn't return any rows because you're looking for 'age of empires III' exact string which doesn't exists in any rows.
So in order to match with this string with different string which has 'age of empires'
as substring you need to use '%your string goes here%'
More on mysql string comparision
You need to try this
SELECT * from games WHERE (lower(title) LIKE '%age of empires III%');
In Like '%age of empires III%'
this will search for any matching substring in your rows, and it will show in results.
When working with a version control system where all files are read only until checked out (like Perforce), the problem may be that you accidentally submitted into this version control system one of the VS files (like filters, for example) and the file thus cannot be overridden during build.
Just go to your working directory and check that none of VS solution related files and none of temporary created files (like all moc_ and ui_ prefixed files in QT, for example) is read only.
Joshua Bloch has a talk about API design that covers how bad ones make boilerplate code necessary. (Minute 46 for reference to boilerplate, listening to this today)
Be sure to check out verilog-mode and especially verilog-auto. http://www.veripool.org/wiki/verilog-mode/ It is a verilog mode for emacs, but plugins exist for vi(m?) for example.
An instantiation can be automated with AUTOINST. The comment is expanded with M-x verilog-auto
and can afterwards be manually edited.
subcomponent subcomponent_instance_name(/*AUTOINST*/);
Expanded
subcomponent subcomponent_instance_name (/*AUTOINST*/
//Inputs
.clk, (clk)
.rst_n, (rst_n)
.data_rx (data_rx_1[9:0]),
//Outputs
.data_tx (data_tx[9:0])
);
Implicit wires can be automated with /*AUTOWIRE*/
. Check the link for further information.
The simplest way is to drop the whole database and create it once again:
drop database db_name
create database db_name
That's all.
If you renamed the folder containing your Homestead project, you'll get this error. Visit your Homestead.yaml
file and update any references to point to the renamed folder, then do vagrant up
(etc.) again
go to tsconfig.json and comment the line the //strict:true this worked for me
I did it this way:
LocalTime time = LocalTime.now();
if (time.isAfter(LocalTime.of(02, 00)) && (time.isBefore(LocalTime.of(04, 00))))
{
log.info("Checking after 2AM, before 4AM!");
}
Edit:
String time1 = "01:00:00";
String time2 = "15:00:00";
LocalTime time = LocalTime.parse(time2);
if ((time.isAfter(LocalTime.of(20,11,13))) || (time.isBefore(LocalTime.of(14,49,0))))
{
System.out.println("true");
}
else
{
System.out.println("false");
}
Take a look at FileSaver.js. It provides a handy saveAs
function which takes care of most browser specific quirks.
Just set the TextBox.PasswordChar property to '*'.
for a two factors sort (name and lastname):
users.sort((a, b) => a.name.toLowerCase() < b.name.toLowerCase() ? -1 : a.name.toLowerCase() > b.name.toLowerCase() ? 1 : a.lastname.toLowerCase() < b.lastname.toLowerCase() ? -1 : a.lastname.toLowerCase() > b.lastname.toLowerCase() ? 1 : 0)
_x000D_
These are subplot grid parameters encoded as a single integer. For example, "111" means "1x1 grid, first subplot" and "234" means "2x3 grid, 4th subplot".
Alternative form for add_subplot(111)
is add_subplot(1, 1, 1)
.
if you just want a human readable time string and not that exact format:
$t = localtime;
print "$t\n";
prints
Mon Apr 27 10:16:19 2015
or whatever is configured for your locale.
printf("%.12f", M_PI);
%.12f means floating point, with precision of 12 digits.
Use:
System.Configuration.ConfigurationSettings.AppSettings["MyKey"];
AppSettings has been deprecated and is now considered obsolete (link).
In addition, the appSettings section of the app.config has been replaced by the applicationSettings section.
As someone else mentioned, you should be using System.Configuration.ConfigurationManager (link) which is new for .NET 2.0.
Take a look at jsHybugger. It will allow you to remotely debug your js code for:
How this works (more details and alternatives on the projects site, this was what I found to be the best way).
Again, with Chrome on Android use the ADB extension without jsHybugger. I think this already described in the accepted answer to this question.
Given an array you can use the Array.ConvertAll
method:
int[] myInts = Array.ConvertAll(arr, s => int.Parse(s));
Thanks to Marc Gravell for pointing out that the lambda can be omitted, yielding a shorter version shown below:
int[] myInts = Array.ConvertAll(arr, int.Parse);
A LINQ solution is similar, except you would need the extra ToArray
call to get an array:
int[] myInts = arr.Select(int.Parse).ToArray();
This answer is for beginners (none-git gurus). I recently had this problem and maybe its just me but most of the answers seemed to require rather advance understanding of git. After reading several stack overflow answers including this thread, here are the steps I needed to take in order to easily switch between GitHub accounts (e.g. assume two GitHub accounts, github.com/personal and gitHub.com/work):
ls -al ~/.ssh
.pub
are your ssh keys so you should have two for the personal
and work
accounts. If there is only one or none, its time to generate other wise skip this.ssh-keygen -t rsa -C "the copied email"
, you'll see:/.../.ssh/id_rsa_work
if generating for work account. provide a password or just enter to ignore and, you'll read something like The key's randomart image is: and the image. done.ls -al ~/.ssh
again.pbcopy < ~/.ssh/id_rsa_work.pub
, replace id_rsa_work.pub
with what you called yours.id_rsa_work
] and navigate toEdit the global git configuration: Last step is to make sure the global configuration file is aware of all github accounts (so to say).
Run git config --global --edit
to edit this global file, if this opens vim and you don't know how to use it, press i
to enter Insert mode, edit the file as below, and press esc followed by :wq
to exit insert mode:
[inside this square brackets give a name to the followed acc.]
name = github_username
email = github_emailaddress
[any other name]
name = github_username
email = github_email
[credential]
helper = osxkeychain
useHttpPath = true
Done!, now when trying to push or pull from a repo, you'll be asked which GitHub account should be linked with this repo and its asked only once, the local configuration will remember this link and not the global configuration so you can work on different repos that are linked with different accounts without having to edit global configuration each time.
1. match_parent
When you set layout width and height as match_parent, it will occupy the complete area that the parent view has, i.e. it will be as big as the parent.
Note : If parent is applied a padding then that space would not be included.
When we create a layout.xml by default we have RelativeLayout as default parent View with android:layout_width="match_parent" and android:layout_height="match_parent" i.e it occupies the complete width and height of the mobile screen.
Also note that padding is applied to all sides,
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
Now lets add a sub-view LinearLayout and sets its layout_width="match_parent" and layout_height="match_parent", the graphical view would display something like this,
match_parent_example
Code
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.code2care.android.togglebuttonexample.MainActivity" >
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="11dp"
android:background="#FFFFEE"
android:orientation="vertical" >
2. fill_parent :
This is same as match_parent, fill_parent was depreciated in API level 8. So if you are using API level 8 or above you must avoid using fill_parent
Lets follow the same steps as we did for match_parent, just instead use fill_parent everywhere.
You would see that there is no difference in behaviour in both fill_parent and match parent.
Use Integer.compare(int, int)
. And don'try to micro-optimize your code unless you can prove that you have a performance issue.
Python 2.x and Python 3.x are different. If you would like to download a newer version of Python 2, you could just download and install the newer version.
If you want to install Python 3, you could install Python 3 separately then change the path for Python 2.x to Python 3.x in Control Panel > All Control Panel Items > System > Advanced System Settings > Environment Variables.
http://en.wikipedia.org/wiki/Representational_State_Transfer
The basic idea is that instead of having an ongoing connection to the server, you make a request, get some data, show that to a user, but maybe not all of it, and then when the user does something which calls for more data, or to pass some up to the server, the client initiates a change to a new state.
There are several way to approach globals:
Webpack evaluates modules only once, so your instance remains global and carries changes through from module to module. So if you create something like a globals.js
and export an object of all your globals then you can import './globals'
and read/write to these globals. You can import into one module, make changes to the object from a function and import into another module and read those changes in a function. Also remember the order things happen. Webpack will first take all the imports and load them up in order starting in your entry.js
. Then it will execute entry.js
. So where you read/write to globals is important. Is it from the root scope of a module or in a function called later?
config.js
export default {
FOO: 'bar'
}
somefile.js
import CONFIG from './config.js'
console.log(`FOO: ${CONFIG.FOO}`)
Note: If you want the instance to be new
each time, then use an ES6 class. Traditionally in JS you would capitalize classes (as opposed to the lowercase for objects) like
import FooBar from './foo-bar' // <-- Usage: myFooBar = new FooBar()
Here's how you can do it using Webpack's ProvidePlugin (which makes a module available as a variable in every module and only those modules where you actually use it). This is useful when you don't want to keep typing import Bar from 'foo'
again and again. Or you can bring in a package like jQuery or lodash as global here (although you might take a look at Webpack's Externals).
Step 1) Create any module. For example, a global set of utilities would be handy:
utils.js
export function sayHello () {
console.log('hello')
}
Step 2) Alias the module and add to ProvidePlugin:
webpack.config.js
var webpack = require("webpack");
var path = require("path");
// ...
module.exports = {
// ...
resolve: {
extensions: ['', '.js'],
alias: {
'utils': path.resolve(__dirname, './utils') // <-- When you build or restart dev-server, you'll get an error if the path to your utils.js file is incorrect.
}
},
plugins: [
// ...
new webpack.ProvidePlugin({
'utils': 'utils'
})
]
}
Now just call utils.sayHello()
in any js file and it should work. Make sure you restart your dev-server if you are using that with Webpack.
Note: Don't forget to tell your linter about the global, so it won't complain. For example, see my answer for ESLint here.
If you just want to use const with string values for your globals, then you can add this plugin to your list of Webpack plugins:
new webpack.DefinePlugin({
PRODUCTION: JSON.stringify(true),
VERSION: JSON.stringify("5fa3b9"),
BROWSER_SUPPORTS_HTML5: true,
TWO: "1+1",
"typeof window": JSON.stringify("object")
})
Use it like:
console.log("Running App version " + VERSION);
if(!BROWSER_SUPPORTS_HTML5) require("html5shiv");
window.foo = 'bar' // For SPA's, browser environment.
global.foo = 'bar' // Webpack will automatically convert this to window if your project is targeted for web (default), read more here: https://webpack.js.org/configuration/node/
You'll see this commonly used for polyfills, for example: window.Promise = Bluebird
(For server side projects) The dotenv package will take a local configuration file (which you could add to your .gitignore if there are any keys/credentials) and adds your configuration variables to Node's process.env object.
// As early as possible in your application, require and configure dotenv.
require('dotenv').config()
Create a .env
file in the root directory of your project. Add environment-specific variables on new lines in the form of NAME=VALUE
. For example:
DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3
That's it.
process.env
now has the keys and values you defined in your .env
file.
var db = require('db')
db.connect({
host: process.env.DB_HOST,
username: process.env.DB_USER,
password: process.env.DB_PASS
})
Regarding Webpack's Externals, use it if you want to exclude some modules from being included in your built bundle. Webpack will make the module globally available but won't put it in your bundle. This is handy for big libraries like jQuery (because tree shaking external packages doesn't work in Webpack) where you have these loaded on your page already in separate script tags (perhaps from a CDN).
You can simply use !=
instead.
After reading a couple of blog posts, it does seem to be even an easier fix by clicking BACK when the installer says couldn't find the JDK, and then simply click NEXT again and magically it finds the JDK. No registry messing around or re-downloading etc..
Use the numpy.corrcoef
function instead of numpy.correlate
to calculate the statistical correlation for a lag of t:
def autocorr(x, t=1):
return numpy.corrcoef(numpy.array([x[:-t], x[t:]]))
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << stod(" 99.999 ") << endl;
}
Output: 99.999
(which is double, whitespace was automatically stripped)
Since C++11 converting string to floating-point values (like double) is available with functions:
stof - convert str to a float
stod - convert str to a double
stold - convert str to a long double
As conversion of string to int was also mentioned in the question, there are the following functions in C++11:
stoi - convert str to an int
stol - convert str to a long
stoul - convert str to an unsigned long
stoll - convert str to a long long
stoull - convert str to an unsigned long long
I do not want to repeat others' answers, so, in short I explain some common misunderstanding
You should avoid using it all across your project
DDD stresses the need to focus the most effort on the core subdomain. The core subdomain is the area of your product that will be the difference between it being a success and it being a failure. It’s the product’s unique selling point, the reason it is being built rather than bought.
Basically, it is because it takes too much time and effort. So, it is suggested to break down the whole domain into subdomain and just apply it in those with high business value. (ex not in generic subdomain like email, ...)
It is not object oriented programming. It is mostly problem solving approach and (sometimes) you do not need to use OO patterns (such as Gang of Four) in your domain models. Simply because it can not be understood by Business Experts (they do not know much about Factory, Decorator, ...). There are even some patterns in DDD (such as The Transaction Script, Table Module) which are not 100% in line with OO concepts.
<script type="text/javascript">
function report(func)
{
func();
}
function daily()
{
alert('daily');
}
function monthly()
{
alert('monthly');
}
</script>
I was in need of copying the data from one workbook to another using VBA. The requirement was as mentioned below 1. On pressing an Active X button open the dialogue to select the file from which the data needs to be copied. 2. On clicking OK the value should get copied from a cell / range to currently working workbook.
I did not want to use the open function because it opens the workbook which will be annoying
Below is the code that I wrote in the VBA. Any improvement or new alternative is welcome.
Code: Here I am copying the A1:C4 content from a workbook to the A1:C4 of current workbook
Private Sub CommandButton1_Click()
Dim BackUp As String
Dim cellCollection As New Collection
Dim strSourceSheetName As String
Dim strDestinationSheetName As String
strSourceSheetName = "Sheet1" 'Mention the Source Sheet Name of Source Workbook
strDestinationSheetName = "Sheet2" 'Mention the Destination Sheet Name of Destination Workbook
Set cellCollection = GetCellsFromRange("A1:C4") 'Mention the Range you want to copy data from Source Workbook
With Application.FileDialog(msoFileDialogOpen)
.AllowMultiSelect = False
.Show
'.Filters.Add "Macro Enabled Xl", "*.xlsm;", 1
For intWorkBookCount = 1 To .SelectedItems.Count
Dim strWorkBookName As String
strWorkBookName = .SelectedItems(intWorkBookCount)
For cellCount = 1 To cellCollection.Count
On Error GoTo ErrorHandler
BackUp = Sheets(strDestinationSheetName).Range(cellCollection.Item(cellCount))
Sheets(strDestinationSheetName).Range(cellCollection.Item(cellCount)) = GetData(strWorkBookName, strSourceSheetName, cellCollection.Item(cellCount))
Dim strTempValue As String
strTempValue = Sheets(strDestinationSheetName).Range(cellCollection.Item(cellCount)).Value
If (strTempValue = "0") Then
strTempValue = BackUp
End If
Sheets(strDestinationSheetName).Range(cellCollection.Item(cellCount)) = strTempValue
ErrorHandler:
If (Err.Number <> 0) Then
Sheets(strDestinationSheetName).Range(cellCollection.Item(cellCount)) = BackUp
Exit For
End If
Next cellCount
Next intWorkBookCount
End With
End Sub
Function GetCellsFromRange(RangeInScope As String) As Collection
Dim startCell As String
Dim endCell As String
Dim intStartColumn As Integer
Dim intEndColumn As Integer
Dim intStartRow As Integer
Dim intEndRow As Integer
Dim coll As New Collection
startCell = Left(RangeInScope, InStr(RangeInScope, ":") - 1)
endCell = Right(RangeInScope, Len(RangeInScope) - InStr(RangeInScope, ":"))
intStartColumn = Range(startCell).Column
intEndColumn = Range(endCell).Column
intStartRow = Range(startCell).Row
intEndRow = Range(endCell).Row
For lngColumnCount = intStartColumn To intEndColumn
For lngRowCount = intStartRow To intEndRow
coll.Add (Cells(lngRowCount, lngColumnCount).Address(RowAbsolute:=False, ColumnAbsolute:=False))
Next lngRowCount
Next lngColumnCount
Set GetCellsFromRange = coll
End Function
Function GetData(FileFullPath As String, SheetName As String, CellInScope As String) As String
Dim Path As String
Dim FileName As String
Dim strFinalValue As String
Dim doesSheetExist As Boolean
Path = FileFullPath
Path = StrReverse(Path)
FileName = StrReverse(Left(Path, InStr(Path, "\") - 1))
Path = StrReverse(Right(Path, Len(Path) - InStr(Path, "\") + 1))
strFinalValue = "='" & Path & "[" & FileName & "]" & SheetName & "'!" & CellInScope
GetData = strFinalValue
End Function
Set libraries search path first:
LINK_DIRECTORIES(${CMAKE_BINARY_DIR}/res)
And then just do
TARGET_LINK_LIBRARIES(GLBall mylib)
Force popen
to not continue until all output is read by doing:
os.popen(command).read()
Check the jQuery FAQ...
You can use the length property of the jQuery collection returned by your selector:
if ( $('#myDiv').length ){}
Call the toISOString()
method:
var dt = new Date("30 July 2010 15:05 UTC");
document.write(dt.toISOString());
// Output:
// 2010-07-30T15:05:00.000Z
From http://www.dotnetperls.com:
7z a secure.7z * -pSECRET
Where:
7z : name and path of 7-Zip executable
a : add to archive
secure.7z : name of destination archive
* : add all files from current directory to destination archive
-pSECRET : specify the password "SECRET"
To open :
7z x secure.7z
Then provide the SECRET password
Note: If the password contains spaces or special characters, then enclose it with single quotes
7z a secure.7z * -p"pa$$word @|"
Using the Promise pattern:
function getImage(url){
return new Promise(function(resolve, reject){
var img = new Image()
img.onload = function(){
resolve(url)
}
img.onerror = function(){
reject(url)
}
img.src = url
})
}
And when calling the function we can handle its response or error quite neatly.
getImage('imgUrl').then(function(successUrl){
//do stufff
}).catch(function(errorUrl){
//do stuff
})
You need to run pip list
in bash not in python.
pip list
DEPRECATION: Python 2.6 is no longer supported by the Python core team, please upgrade your Python. A future version of pip will drop support for Python 2.6
argparse (1.4.0)
Beaker (1.3.1)
cas (0.15)
cups (1.0)
cupshelpers (1.0)
decorator (3.0.1)
distribute (0.6.10)
---and other modules
Here is what made the error disappear for me:
Close eclipse, open up a terminal window and run:
$ mvn clean eclipse:clean eclipse:eclipse
Are you using Maven? If so,
To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.
And then clean
Edit 1:
If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.
Edit 2:
You can also try going into the folder where you have all your projects and delete the .metadata
for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.
It means you didn't set ORACLE_HOME and ORACLE_SID variables. Kindly set proper working $ORACLE_HOME and $ORACLE_SID and after that execute sqlplus /nolog command. It will be working.
If you have defined a method inside your class as static, this is actually possible.
class myClass
{
public:
static void saySomething()
{
std::cout << "This is a static method!" << std::endl;
}
};
And from main, you declare a pointer and try to invoke the static method.
myClass * pmyClass;
pmyClass->saySomething();
/*
Output:
This is a static method!
*/
This works fine because static methods do not belong to a specific instance of the class and they are not allocated as a part of any instance of the class.
Read more on static methods here: http://en.wikipedia.org/wiki/Static_method#Static_methods
Remove C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.0
directory.
Now run :
npm install -g typescript
this will install the latest version and then re-try.
you have to check your linked project, in the new version of RN, don't need to link if you linked it cause a problem, I Fixed the problem by unlinked manually the dependency that I linked and re-run.
Looks like the type is boolean and therefore can never be null and should be false by default.
private static Double _MilesToKilometers = 1.609344;
private static Double _MilesToNautical = 0.8684;
/// <summary>
/// Calculates the distance between two points of latitude and longitude.
/// Great Link - http://www.movable-type.co.uk/scripts/latlong.html
/// </summary>
/// <param name="coordinate1">First coordinate.</param>
/// <param name="coordinate2">Second coordinate.</param>
/// <param name="unitsOfLength">Sets the return value unit of length.</param>
public static Double Distance(Coordinate coordinate1, Coordinate coordinate2, UnitsOfLength unitsOfLength)
{
double theta = coordinate1.getLongitude() - coordinate2.getLongitude();
double distance = Math.sin(ToRadian(coordinate1.getLatitude())) * Math.sin(ToRadian(coordinate2.getLatitude())) +
Math.cos(ToRadian(coordinate1.getLatitude())) * Math.cos(ToRadian(coordinate2.getLatitude())) *
Math.cos(ToRadian(theta));
distance = Math.acos(distance);
distance = ToDegree(distance);
distance = distance * 60 * 1.1515;
if (unitsOfLength == UnitsOfLength.Kilometer)
distance = distance * _MilesToKilometers;
else if (unitsOfLength == UnitsOfLength.NauticalMiles)
distance = distance * _MilesToNautical;
return (distance);
}
Here's a simple function:
function setParent(el, newParent)
{
newParent.appendChild(el);
}
el
's childNodes
are the elements to be moved, newParent
is the element el
will be moved to, so you would execute the function like:
var l = document.getElementById('old-parent').childNodes.length;
var a = document.getElementById('old-parent');
var b = document.getElementById('new-parent');
for (var i = l; i >= 0; i--)
{
setParent(a.childNodes[0], b);
}
In Management Studio, open the Object Explorer.
Views
Script view as > Create To > New query window
and you're done!
If you want to retrieve the SQL statement that defines the view from T-SQL code, use this:
SELECT
m.definition
FROM sys.views v
INNER JOIN sys.sql_modules m ON m.object_id = v.object_id
WHERE name = 'Example_1'
If you use SQL 2005 you can do something neat like this:
;WITH res
AS ( SELECT t.YourID ,
CAST(( SELECT Col1 AS c01 ,
Col2 AS c02 ,
Col3 AS c03 ,
Col4 AS c04 ,
Col5 AS c05
FROM YourTable AS cols
WHERE YourID = t.YourID
FOR
XML AUTO ,
ELEMENTS
) AS XML) AS colslist
FROM YourTable AS t
)
SELECT YourID ,
colslist.query('for $c in //cols return min(data($c/*))').value('.',
'real') AS YourMin ,
colslist.query('for $c in //cols return avg(data($c/*))').value('.',
'real') AS YourAvg ,
colslist.query('for $c in //cols return max(data($c/*))').value('.',
'real') AS YourMax
FROM res
This way you don't get lost in so many operators :)
However, this could be slower than the other choice.
It's your choice...
You could also do this:
$dump = print_r($variable, true);
I have same issue. Error message for me is not complete. But in my case, I've added generation jar with sources. By placing this code in pom.xml:
<build>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-source-plugin</artifactId>
<version>2.1.2</version>
<executions>
<execution>
<phase>deploy</phase>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
So in deploy phase I execute source:jar goal which produces jar with sources. And deploy ends with BUILD SUCCESS
From my HomeController I want to call this Method and convert Json response to List
No you don't. You really don't want to add the overhead of an HTTP call and (de)serialization when the code is within reach. It's even in the same assembly!
Your ApiController goes against (my preferred) convention anyway. Let it return a concrete type:
public IEnumerable<QDocumentRecord> GetAllRecords()
{
listOfFiles = ...
return listOfFiles;
}
If you don't want that and you're absolutely sure you need to return HttpResponseMessage
, then still there's absolutely no need to bother with calling JsonConvert.SerializeObject()
yourself:
return Request.CreateResponse<List<QDocumentRecord>>(HttpStatusCode.OK, listOfFiles);
Then again, you don't want business logic in a controller, so you extract that into a class that does the work for you:
public class FileListGetter
{
public IEnumerable<QDocumentRecord> GetAllRecords()
{
listOfFiles = ...
return listOfFiles;
}
}
Either way, then you can call this class or the ApiController directly from your MVC controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var listOfFiles = new DocumentsController().GetAllRecords();
// OR
var listOfFiles = new FileListGetter().GetAllRecords();
return View(listOfFiles);
}
}
But if you really, really must do an HTTP request, you can use HttpWebRequest
, WebClient
, HttpClient
or RestSharp
, for all of which plenty of tutorials exist.
I stumbled across this old question and I think the easiest approach is still missing.
You can use rio
to import all excel sheets with just one line of code.
library(rio)
data_list <- import_list("test.xls")
If you're a fan of the tidyverse
, you can easily import them as tibbles by adding the setclass
argument to the function call.
data_list <- import_list("test.xls", setclass = "tbl")
Suppose they have the same format, you could easily row bind them by setting the rbind
argument to TRUE
.
data_list <- import_list("test.xls", setclass = "tbl", rbind = TRUE)
If your test class extends the Spring JUnit classes
(e.g., AbstractTransactionalJUnit4SpringContextTests
or any other class that extends AbstractSpringContextTests
), you can access the app context by calling the getContext()
method.
Check out the javadocs for the package org.springframework.test.
Beside rowid, you can define your own auto increment field but it is not recommended. It is always be better solution when we use rowid that is automatically increased.
The
AUTOINCREMENT
keyword imposes extra CPU, memory, disk space, and disk I/O overhead and should be avoided if not strictly needed. It is usually not needed.
Read here for detailed information.
I would like to expand on Martin's answer there...
His solution is rather nice, but it can be tweaked so any "variable type" can be printed like that.(It's actually Value Type, more on the topic). That said, "tweaked" may be a strong word for this. Regardless, it may be helpful.
Martins Solution:
a.getClass().getName()
However, If you want it to work with anything you can do this:
((Object) myVar).getClass().getName()
//OR
((Object) myInt).getClass().getSimpleName()
In this case, the primitive will simply be wrapped in a Wrapper. You will get the Object of the primitive in that case.
I myself used it like this:
private static String nameOf(Object o) {
return o.getClass().getSimpleName();
}
Using Generics:
public static <T> String nameOf(T o) {
return o.getClass().getSimpleName();
}
Update on Jan 04, 2012
It seems like you can't just call FB-dependent methods (for example FB.getAuthResponse()
) right after FB.init()
like before, as FB.init()
seems to be asynchronous now. Wrapping your code into FB.getLoginStatus()
response seems to do the trick of detecting when API is fully ready:
window.fbAsyncInit = function() {
FB.init({
//...
});
FB.getLoginStatus(function(response){
runFbInitCriticalCode();
});
};
or if using fbEnsureInit()
implementation from below:
window.fbAsyncInit = function() {
FB.init({
//...
});
FB.getLoginStatus(function(response){
fbApiInit = true;
});
};
Original Post:
If you want to just run some script when FB is initialized you can put some callback function inside fbAsyncInit
:
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo $conf['fb']['appid']; ?>',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.Canvas.setAutoResize();
runFbInitCriticalCode(); //function that contains FB init critical code
};
If you want exact replacement of FB.ensureInit then you would have to write something on your own as there is no official replacement (big mistake imo). Here is what I use:
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo $conf['fb']['appid']; ?>',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.Canvas.setAutoResize();
fbApiInit = true; //init flag
};
function fbEnsureInit(callback) {
if(!window.fbApiInit) {
setTimeout(function() {fbEnsureInit(callback);}, 50);
} else {
if(callback) {
callback();
}
}
}
Usage:
fbEnsureInit(function() {
console.log("this will be run once FB is initialized");
});
Tips of using OS-dependent function to terminate C++ thread:
std::thread::native_handle()
only can get the thread’s valid native handle type before calling join()
or detach()
. After that, native_handle()
returns 0 - pthread_cancel()
will coredump.
To effectively call native thread termination function(e.g. pthread_cancel()
), you need to save the native handle before calling std::thread::join()
or std::thread::detach()
. So that your native terminator always has a valid native handle to use.
More explanations please refer to: http://bo-yang.github.io/2017/11/19/cpp-kill-detached-thread .
The following code will perform recursively a deep copying of objects and array:
function deepCopy(obj) {
if (Object.prototype.toString.call(obj) === '[object Array]') {
var out = [], i = 0, len = obj.length;
for ( ; i < len; i++ ) {
out[i] = arguments.callee(obj[i]);
}
return out;
}
if (typeof obj === 'object') {
var out = {}, i;
for ( i in obj ) {
out[i] = arguments.callee(obj[i]);
}
return out;
}
return obj;
}
i used Mofi sample, and change some parameters, no you can do -t
@%SystemRoot%\system32\ping.exe -n -1 4.2.2.4
Use insert method from range, for example
Sub InsertColumn()
Columns("C:C").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("C1").Value = "Loc"
End Sub
I created it in a more similar way to the SQL, I think it is easier to understand
var list = (from a in listA.AsEnumerable()
join b in listB.AsEnumerable() on a.id equals b.id into ab
from c in ab.DefaultIfEmpty()
where c != null
select new { id = c.id, name = c.nome }).ToList();
For loading animated gifs stored in a source package (in the source code), this worked for me:
URL url = MyClass.class.getResource("/res/images/animated.gif");
ImageIcon imageIcon = new ImageIcon(url);
JLabel label = new JLabel(imageIcon);
I came up with the following solution:
SELECT [Str], DecimalParsed = CASE
WHEN ISNUMERIC([Str]) = 1 AND CHARINDEX('.', [Str])=0 AND LEN(REPLACE(REPLACE([Str], '-', ''), '+', '')) < 29 THEN CONVERT(decimal(38,10), [Str])
WHEN ISNUMERIC([Str]) = 1 AND (CHARINDEX('.', [Str])!=0 AND CHARINDEX('.', REPLACE(REPLACE([Str], '-', ''), '+', ''))<=29) THEN
CONVERT(decimal(38,10),
CASE WHEN LEN([Str]) - LEN(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE([Str], '0', ''), '1', ''), '2', ''), '3', ''), '4', ''), '5', ''), '6', ''), '7', ''), '8', ''), '9', '')) <= 38
THEN [Str]
ELSE SUBSTRING([Str], 1, 38 + LEN(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE([Str], '0', ''), '1', ''), '2', ''), '3', ''), '4', ''), '5', ''), '6', ''), '7', ''), '8', ''), '9', ''))) END)
ELSE NULL END
FROM TestStrToDecimal
I know it looks like an overkill and probably it is, but it works for me (checked both positive, negative, big and small numbers of different precision and scale - everything is converted to decimal(38,10)
or NULL
).
It is hard-coded to decimal(38,10)
type, so if you need different precision, change the constants in the code (38, 10, 29).
How it works? The result is:
each case is separate WHEN statement inthe code above.
Here are few examples of conversion: