I try to solve here is my code.
first add dependency in build.gradle(app).
dependencies {
compile 'com.android.support:design:23.1.1'
}
Create PagerAdapter.class
public class PagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public PagerAdapter(FragmentManager manager) {
super(manager);
}
@Override
public Fragment getItem(int position) {
Log.i("PosTabItem",""+position);
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
@Override
public CharSequence getPageTitle(int position) {
Log.i("PosTab",""+position);
return mFragmentTitleList.get(position);
}
}
create activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/toolbar"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="@id/tab_layout" />
</RelativeLayout>
create MainActivity.class
public class MainActivity extends AppCompatActivity {
Pager pager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
pager = new Pager(getSupportFragmentManager());
pager.addFragment(new FragmentOne(), "One");
viewPager.setAdapter(pager);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setTabMode(TabLayout.MODE_FIXED);
tabLayout.setSmoothScrollingEnabled(true);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
and finally create fragment to add in viewpager
crate fragment_one.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="Location"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Create FragmentOne.class
public class FragmentOne extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container,false);
return view;
}
}
If all you want to do is display an iframe on a page, the simplest solution I was able to come up with doesn't require divs or flex stuff is:
html {
width: 100%;
height: 100%;
display: table;
}
body {
text-align: center;
vertical-align: middle;
display: table-cell;
}
And then the HTML is just:
<html>
<body>
<iframe ...></iframe>
</body>
</html>
If this is all you need you don't need wrapper divs to do it. This works for text content and stuff, too.
Also this looks even simpler.
As a follow-up to Dave.Gugg's answer, this would be the code someone would need to get all the DROP TABLE lines in MySQL:
SELECT CONCAT('DROP TABLE ', TABLE_NAME, ';')
FROM INFORMATION_SCHEMA.tables
WHERE TABLE_SCHEMA = 'your_database_name'
You should float them inside a container that is cleared.
Example:
https://jsfiddle.net/W74Z8/504/
A clean implementation is the "clearfix hack". This is Nicolas Gallagher's version:
/**
* For modern browsers
* 1. The space content is one way to avoid an Opera bug when the
* contenteditable attribute is included anywhere else in the document.
* Otherwise it causes space to appear at the top and bottom of elements
* that are clearfixed.
* 2. The use of `table` rather than `block` is only necessary if using
* `:before` to contain the top-margins of child elements.
*/
.clearfix:before,
.clearfix:after {
content: " "; /* 1 */
display: table; /* 2 */
}
.clearfix:after {
clear: both;
}
/**
* For IE 6/7 only
* Include this rule to trigger hasLayout and contain floats.
*/
.clearfix {
*zoom: 1;
}
?
I gathered insights from a bunch of answers here and I present a comprehensive solution:
So, if you setup nginx with php5-fpm and log a message using error_log()
you can see it in /var/log/nginx/error.log
by default.
A problem can arise if you want to log a lot of data (say an array) using error_log(print_r($myArr, true));
. If an array is large enough, it seems that nginx
will truncate your log entry.
To get around this you can configure fpm
(php.net fpm config) to manage logs. Here are the steps to do so.
Open /etc/php5/fpm/pool.d/www.conf
:
$ sudo nano /etc/php5/fpm/pool.d/www.conf
Uncomment the following two lines by removing ;
at the beginning of the line: (error_log is defined here: php.net)
;php_admin_value[error_log] = /var/log/fpm-php.www.log
;php_admin_flag[log_errors] = on
Create /var/log/fpm-php.www.log
:
$ sudo touch /var/log/fpm-php.www.log;
Change ownership of /var/log/fpm-php.www.log
so that php5-fpm can edit it:
$ sudo chown vagrant /var/log/fpm-php.www.log
Note: vagrant
is the user that I need to give ownership to. You can see what user this should be for you by running $ ps aux | grep php.*www
and looking at first column.
Restart php5-fpm:
$ sudo service php5-fpm restart
Now your logs will be in /var/log/fpm-php.www.log
.
I've already answered this question, but I'll do it again since in the meanwhile I've learnt that there are special cases if you're running in CLI (redirects cannot happen and thus shouldn't exit()
) or if your webserver is running PHP as a (F)CGI (it needs a previously set Status
header to properly redirect).
function Redirect($url, $code = 302)
{
if (strncmp('cli', PHP_SAPI, 3) !== 0)
{
if (headers_sent() !== true)
{
if (strlen(session_id()) > 0) // If using sessions
{
session_regenerate_id(true); // Avoids session fixation attacks
session_write_close(); // Avoids having sessions lock other requests
}
if (strncmp('cgi', PHP_SAPI, 3) === 0)
{
header(sprintf('Status: %03u', $code), true, $code);
}
header('Location: ' . $url, true, (preg_match('~^30[1237]$~', $code) > 0) ? $code : 302);
}
exit();
}
}
I've also handled the issue of supporting the different HTTP redirection codes (301
, 302
, 303
and 307
), as it was addressed in the comments of my previous answer. Here are the descriptions:
If $arrayofStringsNotInterestedIn is an [array] you should use -notcontains:
Get-Content $FileName | foreach-object { `
if ($arrayofStringsNotInterestedIn -notcontains $_) { $) }
or better (IMO)
Get-Content $FileName | where { $arrayofStringsNotInterestedIn -notcontains $_}
In Python/Spark we can do:
def quiet_logs( sc ):
logger = sc._jvm.org.apache.log4j
logger.LogManager.getLogger("org"). setLevel( logger.Level.ERROR )
logger.LogManager.getLogger("akka").setLevel( logger.Level.ERROR )
The after defining Sparkcontaxt 'sc' call this function by : quiet_logs( sc )
This one looks promising and seems to be what you're looking for: http://tree.phi-sci.com/
You can use something like this:
for i in `cat foo.txt`
do
sudo $i
done
Though if the commands have arguments (i.e. there is whitespace in the lines) you may have to monkey around with that a bit to protect the whitepace so that the whole string is seen by sudo
as a command. But it gives you an idea on how to start.
You should pass the object to get method of the field, so
Field field = object.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
Object value = field.get(object);
The Java designers decided that operator overloading was more trouble than it was worth. Simple as that.
In a language where every object variable is actually a reference, operator overloading gets the additional hazard of being quite illogical - to a C++ programmer at least. Compare the situation with C#'s == operator overloading and Object.Equals
and Object.ReferenceEquals
(or whatever it's called).
Is it as optional functionality.
If you won't provide it when user will try to purchase non-consumable product AppStore will restore old transaction. But your app will think that this is new transaction.
If you will provide restore mechanism then your purchase manager will see restored transaction.
If app should distinguish this options then you should provide functionality for restoring previously purchased products.
For Python 3 users:
changing the encoding from 'ascii' to 'latin1' works.
Also, you can try finding the encoding automatically by reading the top 10000 bytes using the below snippet:
import chardet
with open("dataset_path", 'rb') as rawdata:
result = chardet.detect(rawdata.read(10000))
print(result)
I just put into constructor something by reference, so the subform can change its value and main form can get new or modified object from subform.
As mentioned by others there's no cross platform way to do this, but on Windows you can do it like this:
The Code below checks if the key 'A' is down.
if(GetKeyState('A') & 0x8000/*Check if high-order bit is set (1 << 15)*/)
{
// Do stuff
}
In case of shift or similar you will need to pass one of these: https://msdn.microsoft.com/de-de/library/windows/desktop/dd375731(v=vs.85).aspx
if(GetKeyState(VK_SHIFT) & 0x8000)
{
// Shift down
}
The low-order bit indicates if key is toggled.
SHORT keyState = GetKeyState(VK_CAPITAL/*(caps lock)*/);
bool isToggled = keyState & 1;
bool isDown = keyState & 0x8000;
Oh and also don't forget to
#include <Windows.h>
box-shadow: -15px 0px 17px -7px rgba(0,0,0,0.75);
The first px value is the "Horizontal Length" set to -15px to position the shadow towards the left, the next px value is set to 0 so the shadow top and bottom is centred to minimise the top and bottom shadow.
The third value(17px) is known as the blur radius. The higher the number, the more blurred the shadow will be. And then last px value -7px is The spread radius, a positive value increases the size of the shadow, a negative value decreases the size of the shadow, at -7px it keeps the shadow from appearing above and below the item.
reference: CSS Box Shadow Property
Very Simply Short week day name with Month and year
echo date('D, d-M-y');
output
Tue, 16-Feb-21
as per my requirements
return $item->start_time->format("D, d-M");
output
Tue, 16-Feb
#overlay {
position: fixed;
width: 100%;
height: 100%;
background: black url(spinner.gif) center center no-repeat;
opacity: .5;
}
it's better to use rgba color instead of opacity to prevent applying alpha to spinner image.
background: rgba(0,0,0,.5) url(spinner.gif) center center no-repeat;
GCD
is a low-level C-based API that enables very simple use of a task-based concurrency model. NSOperation
and NSOperationQueue
are Objective-C classes that do a similar thing. NSOperation
was introduced first, but as of 10.5 and iOS 2, NSOperationQueue
and friends are internally implemented using GCD
.
In general, you should use the highest level of abstraction that suits your needs. This means that you should usually use NSOperationQueue
instead of GCD
, unless you need to do something that NSOperationQueue
doesn't support.
Note that NSOperationQueue
isn't a "dumbed-down" version of GCD; in fact, there are many things that you can do very simply with NSOperationQueue
that take a lot of work with pure GCD
. (Examples: bandwidth-constrained queues that only run N operations at a time; establishing dependencies between operations. Both very simple with NSOperation
, very difficult with GCD
.) Apple's done the hard work of leveraging GCD to create a very nice object-friendly API with NSOperation
. Take advantage of their work unless you have a reason not to.
Caveat:
On the other hand, if you really just need to send off a block, and don't need any of the additional functionality that NSOperationQueue
provides, there's nothing wrong with using GCD. Just be sure it's the right tool for the job.
Another alternative is to express the comment as a variable expansion that always expands to nothing.
Variable names cannot contain =
, except for undocumented dynamic variables like
%=ExitCode%
and %=C:%
. No variable name can ever contain an =
after the 1st position. So I sometimes use the following to include comments within a parenthesized block:
::This comment hack is not always safe within parentheses.
(
%= This comment hack is always safe, even within parentheses =%
)
It is also a good method for incorporating in-line comments
dir junk >nul 2>&1 && %= If found =% echo found || %= else =% echo not found
The leading =
is not necessary, but I like if for the symmetry.
There are two restrictions:
1) the comment cannot contain %
2) the comment cannot contain :
CellType cell = row.getCell(j).getCellTypeEnum();
switch(cell) {
case NUMERIC:
intVal = row.getCell(j).getNumericCellValue();
System.out.print(intVal);
break;
case STRING:
stringVal = row.getCell(j).getStringCellValue();
System.out.print(stringVal);
break;
}
$q = $dbh->prepare("DESCRIBE tablename");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);
must be
$q = $dbh->prepare("DESCRIBE database.table");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);
The delete
operator deallocates memory and calls the destructor for a single object created with new
.
The delete []
operator deallocates memory and calls destructors for an array of objects created with new []
.
Using delete
on a pointer returned by new []
or delete []
on a pointer returned by new
results in undefined behavior.
Difference between Comparator and Comparable interfaces
Comparable
is used to compare itself by using with another object.
Comparator
is used to compare two datatypes are objects.
Use TAB & TAB+SHIFT in a Specified container or element
we will handle TAB & TAB+SHIFT key listeners first
$(document).ready(function() {
lastIndex = 0;
$(document).keydown(function(e) {
if (e.keyCode == 9) var thisTab = $(":focus").attr("tabindex");
if (e.keyCode == 9) {
if (e.shiftKey) {
//Focus previous input
if (thisTab == startIndex) {
$("." + tabLimitInID).find('[tabindex=' + lastIndex + ']').focus();
return false;
}
} else {
if (thisTab == lastIndex) {
$("." + tabLimitInID).find('[tabindex=' + startIndex + ']').focus();
return false;
}
}
}
});
var setTabindexLimit = function(x, fancyID) {
console.log(x);
startIndex = 1;
lastIndex = x;
tabLimitInID = fancyID;
$("." + tabLimitInID).find('[tabindex=' + startIndex + ']').focus();
}
/*Taking last tabindex=10 */
setTabindexLimit(10, "limitTablJolly");
});
In HTML define tabindex
<div class="limitTablJolly">
<a tabindex=1>link</a>
<a tabindex=2>link</a>
<a tabindex=3>link</a>
<a tabindex=4>link</a>
<a tabindex=5>link</a>
<a tabindex=6>link</a>
<a tabindex=7>link</a>
<a tabindex=8>link</a>
<a tabindex=9>link</a>
<a tabindex=10>link</a>
</div>
I had same problem in my organization.
After many attempts, I came to the following solution:
I applied to the system administrator to change the proxy authentication type from Kerberos to NTLM. I'm not sure if it was mandatory (I'm an ignoramus in this matter), but my application was approved.
After that I add Git setting
git config --global http.proxyauthmethod ntlm
Only after that I was able to clone my repository
EXPECT
is a great program to use.
On Ubuntu install it with:
sudo apt-get install expect
On a CentOS Machine install it with:
yum install expect
Lets say you want to make a connection to a sftp server and then upload a local file from your local machine to the remote sftp server
#!/usr/bin/expect
spawn sftp [email protected]
expect "password:"
send "yourpasswordhere\n"
expect "sftp>"
send "cd logdirectory\n"
expect "sftp>"
send "put /var/log/file.log\n"
expect "sftp>"
send "exit\n"
interact
This opens a sftp connection with your password to the server.
Then it goes to the directory where you want to upload your file, in this case "logdirectory"
This uploads a log file from the local directory found at /var/log/ with the files name being file.log to the "logdirectory" on the remote server
I think it makes clear with the namespace, as we can create our own attributes and if the user specified attribute is the same as the Android one it avoid the conflict of the namespace.
Just add background-attachment to your code
body {
background-position: center;
background-image: url(../images/images5.jpg);
background-attachment: fixed;
}
Out-of-the-box solution to force JSON.stringify
ignore timezones:
// Before: JSON.stringify apply timezone offset
const date = new Date();
let string = JSON.stringify(date);
console.log(string);
// After: JSON.stringify keeps date as-is!
Date.prototype.toJSON = function(){
const hoursDiff = this.getHours() - this.getTimezoneOffset() / 60;
this.setHours(hoursDiff);
return this.toISOString();
};
string = JSON.stringify(date);
console.log(string);
_x000D_
Using moment + moment-timezone libraries:
const date = new Date();
let string = JSON.stringify(date);
console.log(string);
Date.prototype.toJSON = function(){
return moment(this).format("YYYY-MM-DDTHH:mm:ss:ms");;
};
string = JSON.stringify(date);
console.log(string);
_x000D_
<html>
<header>
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data-10-year-range.min.js"></script>
</header>
</html>
_x000D_
You can use if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)
method to detect whether never ask is checked or not.
For more reference : Check this
To check for multiple permissions use:
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)
|| ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
|| ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)
|| ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO)) {
showDialogOK("Service Permissions are required for this app",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
checkAndRequestPermissions();
break;
case DialogInterface.BUTTON_NEGATIVE:
// proceed with logic by disabling the related features or quit the app.
finish();
break;
}
}
});
}
//permission is denied (and never ask again is checked)
//shouldShowRequestPermissionRationale will return false
else {
explain("You need to give some mandatory permissions to continue. Do you want to go to app settings?");
// //proceed with logic by disabling the related features or quit the app.
}
explain() method
private void explain(String msg){
final android.support.v7.app.AlertDialog.Builder dialog = new android.support.v7.app.AlertDialog.Builder(this);
dialog.setMessage(msg)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// permissionsclass.requestPermission(type,code);
startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:com.exampledemo.parsaniahardik.marshmallowpermission")));
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
finish();
}
});
dialog.show();
}
Above code will also show dialog, which will redirect user to app settings screen from where he can give permission if had checked never ask again button.
i ran into this problem and below is a different solution. I were export my components as
export default {
MyComponent1,
MyComponent2
}
and I imported like this:
import { MyComponent1, MyComponent2} from '@/index'
export default {
name: 'App',
components: {
MyComponent1,
MyComponent2
},
};
And it gave this error.
Just use export { ... }
don't use export default
for some reason my error kept pointing to the "proxy" property in the config file. Which was misleading. During my troubleshooting I was trying different values for the proxy and https-proxy properties, but would only get the error stating to make sure the proxy config was set properly, and pointing to an older value.
Using, NPM CONFIG LS -L command lists all the properties and values in the config file. I was then able to see the value in question was matching the https-proxy, therefore using the https-proxy. So I changed the proxy (my company uses different ones) and then it worked. figured I would add this, as with these subtle confusing errors, every perspective on it helps.
This question and answer helped me solve a specific problem with signing up new users in Parse.
Because the signUp( attrs, options ) function uses local storage to persist the session, if a user is in private browsing mode it throws the "QuotaExceededError: DOM Exception 22: An attempt was made to add something to storage that exceeded the quota." exception and the success/error functions are never called.
In my case, because the error function is never called it initially appeared to be an issue with firing the click event on the submit or the redirect defined on success of sign up.
Including a warning for users resolved the issue.
Parse Javascript SDK Reference https://parse.com/docs/js/api/classes/Parse.User.html#methods_signUp
Signs up a new user with a username (or email) and password. This will create a new Parse.User on the server, and also persist the session in localStorage so that you can access the user using {@link #current}.
Something like this:
<Text style={{color: 'blue'}}
onPress={() => Linking.openURL('http://google.com')}>
Google
</Text>
using the Linking
module that's bundled with React Native.
MongoDB 3.2 now allows one to combine data from multiple collections into one through the $lookup aggregation stage. As a practical example, lets say that you have data about books split into two different collections.
First collection, called books
, having the following data:
{
"isbn": "978-3-16-148410-0",
"title": "Some cool book",
"author": "John Doe"
}
{
"isbn": "978-3-16-148999-9",
"title": "Another awesome book",
"author": "Jane Roe"
}
And the second collection, called books_selling_data
, having the following data:
{
"_id": ObjectId("56e31bcf76cdf52e541d9d26"),
"isbn": "978-3-16-148410-0",
"copies_sold": 12500
}
{
"_id": ObjectId("56e31ce076cdf52e541d9d28"),
"isbn": "978-3-16-148999-9",
"copies_sold": 720050
}
{
"_id": ObjectId("56e31ce076cdf52e541d9d29"),
"isbn": "978-3-16-148999-9",
"copies_sold": 1000
}
To merge both collections is just a matter of using $lookup in the following way:
db.books.aggregate([{
$lookup: {
from: "books_selling_data",
localField: "isbn",
foreignField: "isbn",
as: "copies_sold"
}
}])
After this aggregation, the books
collection will look like the following:
{
"isbn": "978-3-16-148410-0",
"title": "Some cool book",
"author": "John Doe",
"copies_sold": [
{
"_id": ObjectId("56e31bcf76cdf52e541d9d26"),
"isbn": "978-3-16-148410-0",
"copies_sold": 12500
}
]
}
{
"isbn": "978-3-16-148999-9",
"title": "Another awesome book",
"author": "Jane Roe",
"copies_sold": [
{
"_id": ObjectId("56e31ce076cdf52e541d9d28"),
"isbn": "978-3-16-148999-9",
"copies_sold": 720050
},
{
"_id": ObjectId("56e31ce076cdf52e541d9d28"),
"isbn": "978-3-16-148999-9",
"copies_sold": 1000
}
]
}
It is important to note a few things:
books_selling_data
, cannot be sharded.So, as a conclusion, if you want to consolidate both collections, having, in this case, a flat copies_sold field with the total copies sold, you will have to work a little bit more, probably using an intermediary collection that will, then, be $out to the final collection.
Try something like this inside ThisOutlookSession
:
Private Sub Application_NewMail()
Call Your_main_macro
End Sub
My outlook vba just fired when I received an email and had that application event open.
Edit: I just tested a hello world msg box and it ran after being called in the application_newmail
event when an email was received.
Kyle's solution worked perfectly fine for me so I made my research in order to avoid any Js and CSS, but just sticking with HTML.
Adding a value of selected
to the item we want to appear as a header forces it to show in the first place as a placeholder.
Something like:
<option selected disabled>Choose here</option>
The complete markup should be along these lines:
<select>
<option selected disabled>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
You can take a look at this fiddle, and here's the result:
If you do not want the sort of placeholder text to appear listed in the options once a user clicks on the select box just add the hidden
attribute like so:
<select>
<option selected disabled hidden>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
Check the fiddle here and the screenshot below.
Here is the solution:
<select>
<option style="display:none;" selected>Select language</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
I'd recommend this article on CSS Tricks by Chris Coyier entitled Better Helvetica:
http://css-tricks.com/snippets/css/better-helvetica/
He basically recommends the following declaration for covering all the bases:
body {
font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
font-weight: 300;
}
Assuming there are a few ignore directories, why not use "git status node/logs/" which will tell you what files are to be added? In the directory I have a text file that is not part of status output, e.g.:
On branch master
Your branch is up-to-date with 'origin/master'.
Untracked files:
(use "git add ..." to include in what will be committed)
node/logs/.gitignore
.gitignore is:
*
!.gitignore
x = [1, 10, 100]
for i in x:
print '%02d' % i
results in:
01
10
100
Read more information about string formatting using % in the documentation.
I'm posting this because (to my surprise) there was no other place I could find that recommended this.
There's a really easy way to do this, without restricting you to browser-defined input dimensions. Just use the <label>
tag around a hidden file upload button. This allows for even more freedom in styling than the styling allowed via webkit's built-in styling[1].
The label tag was made for the exact purpose of directing any click events on it to the child inputs[2], so using that, you won't require any JavaScript to direct the click event to the input button for you anymore. You'd to use something like the following:
label.myLabel input[type="file"] {_x000D_
position:absolute;_x000D_
top: -1000px;_x000D_
}_x000D_
_x000D_
/***** Example custom styling *****/_x000D_
.myLabel {_x000D_
border: 2px solid #AAA;_x000D_
border-radius: 4px;_x000D_
padding: 2px 5px;_x000D_
margin: 2px;_x000D_
background: #DDD;_x000D_
display: inline-block;_x000D_
}_x000D_
.myLabel:hover {_x000D_
background: #CCC;_x000D_
}_x000D_
.myLabel:active {_x000D_
background: #CCF;_x000D_
}_x000D_
.myLabel :invalid + span {_x000D_
color: #A44;_x000D_
}_x000D_
.myLabel :valid + span {_x000D_
color: #4A4;_x000D_
}
_x000D_
<label class="myLabel">_x000D_
<input type="file" required/>_x000D_
<span>My Label</span>_x000D_
</label>
_x000D_
I've used a fixed position to hide the input, to make it work even in ancient versions of Internet Explorer (emulated IE8- refused to work on a visibility:hidden
or display:none
file-input). I've tested in emulated IE7 and up, and it worked perfectly.
<button>
s inside <label>
tags unfortunately, so you'll have to define the styles for the buttons yourself. To me, this is the only downside to this approach.for
attribute is defined, its value is used to trigger the input with the same id
as the for
attribute on the <label>
.Try to add export PATH=$PATH:/home/me/play
in ~/.bashrc file.
The previous answers are all good, but they all show origin/master. These days, following the best practices, I rarely work directly on a master branch, let alone from origin repo.
So if you are like me who work in a branch, here are tips:
Or more simply, just use HEAD:
You have to use the isomorphic-fetch
module to your Node
project because of Node
does not contain Fetch API
yet. for fixing this problem run below command:
npm install --save isomorphic-fetch es6-promise
After installation use below code in your project:
import "isomorphic-fetch"
Hope this answer helps you.
As many people here have pointed out, arrays in C#, as well as in most other common languages, are statically sized. If you're looking for something more like PHP's arrays, which I'm just going to guess you are, since it's a popular language with dynamically sized (and typed!) arrays, you should use an ArrayList:
var mahByteArray = new ArrayList<byte>();
If you have a byte array from elsewhere, you can use the AddRange function.
mahByteArray.AddRange(mahOldByteArray);
Then you can use Add() and Insert() to add elements.
mahByteArray.Add(0x00); // Adds 0x00 to the end.
mahByteArray.Insert(0, 0xCA) // Adds 0xCA to the beginning.
Need it back in an array? .ToArray() has you covered!
mahOldByteArray = mahByteArray.ToArray();
You can use an enhanced for loop:
Set<String> set = new HashSet<String>();
//populate set
for (String s : set) {
System.out.println(s);
}
Or with Java 8:
set.forEach(System.out::println);
Use alias when defining Controller in your angular configuration. For example: NOTE: I'm using TypeScript here
Just take note of the Controller, it has an alias of homeCtrl.
module MongoAngular {
var app = angular.module('mongoAngular', ['ngResource', 'ngRoute','restangular']);
app.config([
'$routeProvider', ($routeProvider: ng.route.IRouteProvider) => {
$routeProvider
.when('/Home', {
templateUrl: '/PartialViews/Home/home.html',
controller: 'HomeController as homeCtrl'
})
.otherwise({ redirectTo: '/Home' });
}])
.config(['RestangularProvider', (restangularProvider: restangular.IProvider) => {
restangularProvider.setBaseUrl('/api');
}]);
}
And here's the way to use it...
ng-click="homeCtrl.addCustomer(customer)"
Try it.. It might work for you as it worked for me... ;)
As I felt similarly confused with .transform
operation vs. .apply
I found a few answers shedding some light on the issue. This answer for example was very helpful.
My takeout so far is that .transform
will work (or deal) with Series
(columns) in isolation from each other. What this means is that in your last two calls:
df.groupby('A').transform(lambda x: (x['C'] - x['D']))
df.groupby('A').transform(lambda x: (x['C'] - x['D']).mean())
You asked .transform
to take values from two columns and 'it' actually does not 'see' both of them at the same time (so to speak). transform
will look at the dataframe columns one by one and return back a series (or group of series) 'made' of scalars which are repeated len(input_column)
times.
So this scalar, that should be used by .transform
to make the Series
is a result of some reduction function applied on an input Series
(and only on ONE series/column at a time).
Consider this example (on your dataframe):
zscore = lambda x: (x - x.mean()) / x.std() # Note that it does not reference anything outside of 'x' and for transform 'x' is one column.
df.groupby('A').transform(zscore)
will yield:
C D
0 0.989 0.128
1 -0.478 0.489
2 0.889 -0.589
3 -0.671 -1.150
4 0.034 -0.285
5 1.149 0.662
6 -1.404 -0.907
7 -0.509 1.653
Which is exactly the same as if you would use it on only on one column at a time:
df.groupby('A')['C'].transform(zscore)
yielding:
0 0.989
1 -0.478
2 0.889
3 -0.671
4 0.034
5 1.149
6 -1.404
7 -0.509
Note that .apply
in the last example (df.groupby('A')['C'].apply(zscore)
) would work in exactly the same way, but it would fail if you tried using it on a dataframe:
df.groupby('A').apply(zscore)
gives error:
ValueError: operands could not be broadcast together with shapes (6,) (2,)
So where else is .transform
useful? The simplest case is trying to assign results of reduction function back to original dataframe.
df['sum_C'] = df.groupby('A')['C'].transform(sum)
df.sort('A') # to clearly see the scalar ('sum') applies to the whole column of the group
yielding:
A B C D sum_C
1 bar one 1.998 0.593 3.973
3 bar three 1.287 -0.639 3.973
5 bar two 0.687 -1.027 3.973
4 foo two 0.205 1.274 4.373
2 foo two 0.128 0.924 4.373
6 foo one 2.113 -0.516 4.373
7 foo three 0.657 -1.179 4.373
0 foo one 1.270 0.201 4.373
Trying the same with .apply
would give NaNs
in sum_C
.
Because .apply
would return a reduced Series
, which it does not know how to broadcast back:
df.groupby('A')['C'].apply(sum)
giving:
A
bar 3.973
foo 4.373
There are also cases when .transform
is used to filter the data:
df[df.groupby(['B'])['D'].transform(sum) < -1]
A B C D
3 bar three 1.287 -0.639
7 foo three 0.657 -1.179
I hope this adds a bit more clarity.
Thou the above answer is widely accepted and well documented, I found some of the reason to post my answer here :-
doNothing().when(InternalUtils.class); //This is the preferred way
//to mock static void methods.
InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());
Here, I dont understand why we are calling InternalUtils.sendEmail ourself. I will explain in my code why we don't need to do that.
mockStatic(Internalutils.class);
So, we have mocked the class which is fine. Now, lets have a look how we need to verify the sendEmail(/..../) method.
@PrepareForTest({InternalService.InternalUtils.class})
@RunWith(PowerMockRunner.class)
public class InternalServiceTest {
@Mock
private InternalService.Order order;
private InternalService internalService;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
internalService = new InternalService();
}
@Test
public void processOrder() throws Exception {
Mockito.when(order.isSuccessful()).thenReturn(true);
PowerMockito.mockStatic(InternalService.InternalUtils.class);
internalService.processOrder(order);
PowerMockito.verifyStatic(times(1));
InternalService.InternalUtils.sendEmail(anyString(), any(String[].class), anyString(), anyString());
}
}
These two lines is where the magic is, First line tells the PowerMockito framework that it needs to verify the class it statically mocked. But which method it need to verify ?? Second line tells which method it needs to verify.
PowerMockito.verifyStatic(times(1));
InternalService.InternalUtils.sendEmail(anyString(), any(String[].class), anyString(), anyString());
This is code of my class, sendEmail api twice.
public class InternalService {
public void processOrder(Order order) {
if (order.isSuccessful()) {
InternalUtils.sendEmail("", new String[1], "", "");
InternalUtils.sendEmail("", new String[1], "", "");
}
}
public static class InternalUtils{
public static void sendEmail(String from, String[] to, String msg, String body){
}
}
public class Order{
public boolean isSuccessful(){
return true;
}
}
}
As it is calling twice you just need to change the verify(times(2))... that's all.
Old question but nowadays CSS3 makes vertical alignment really simple!
Just add to the <div>
this css:
display:flex;
align-items:center;
justify-content:center;
Live Example:
.img_thumb {_x000D_
float: left;_x000D_
height: 120px;_x000D_
margin-bottom: 5px;_x000D_
margin-left: 9px;_x000D_
position: relative;_x000D_
width: 147px;_x000D_
background-color: rgba(0, 0, 0, 0.5);_x000D_
border-radius: 3px;_x000D_
display:flex;_x000D_
align-items:center;_x000D_
justify-content:center;_x000D_
}
_x000D_
<div class="img_thumb">_x000D_
<a class="images_class" href="http://i.imgur.com/2FMLuSn.jpg" rel="images">_x000D_
<img src="http://i.imgur.com/2FMLuSn.jpg" title="img_title" alt="img_alt" />_x000D_
</a>_x000D_
</div>
_x000D_
You can use QuickTime Player
to record the screen.
QuickTime Player
File
from the menuNew Screen recording
Now from the Screen Recording
window, click on record button.
It will provide you with an option to record the entire screen or a selective portion of your screen.
You will have to make a selection of your simulator so that only the simulator portion will be recorded.
I had a lot of trouble with this too. Couldn't get it working using the case examples above, but this does the job for me:
Replace(rtrim(ltrim(ISNULL(Flat_no, '') +
' ' + ISNULL(House_no, '') +
' ' + ISNULL(Street, '') +
' ' + ISNULL(Town, '') +
' ' + ISNULL(City, ''))),' ',' ')
Replace corrects the double spaces caused by concatenating single spaces with nothing between them. r/ltrim gets rid of any spaces at the ends.
<html>
<head>
<title>Names</title>
</head>
<body style="background-color:powderblue;">
<form method='post' action='alex.php'>
<input type='text' name='name'>
<input type='submit' value='name'>
</form>
Enter Name:
<?php
if($_POST)
{
$Name = $_POST['name'];
$count = 0;
$fh=fopen("alex.txt",'a+') or die("failed to create");
while(!feof($fh))
{
$line = chop(fgets($fh));
if($line==$Name && $line!="")
$count=1;
}
if($count==0 && $Name!="")
{
fwrite($fh, "\r\n$Name");
}
else if($count!=0 && $line!="")
{
echo '<font color="red">'.$Name.', the name you entered is already in the list.</font><br><br>';
}
$count=0;
fseek($fh, 0);
while(!feof($fh))
{
$a = chop(fgets($fh));
echo $a.'<br>';
$count++;
}
if($count<=1)
echo '<br>There are no names in the list<br>';
fclose($fh);
}
?>
</body>
</html>
Previous answers missed this addition: a generator has a close
method, while typical iterators don’t. The close
method triggers a StopIteration
exception in the generator, which may be caught in a finally
clause in that iterator, to get a chance to run some clean-up. This abstraction makes it most usable in the large than simple iterators. One can close a generator as one could close a file, without having to bother about what’s underneath.
That said, my personal answer to the first question would be: iteratable has an __iter__
method only, typical iterators have a __next__
method only, generators has both an __iter__
and a __next__
and an additional close
.
For the second question, my personal answer would be: in a public interface, I tend to favor generators a lot, since it’s more resilient: the close
method an a greater composability with yield from
. Locally, I may use iterators, but only if it’s a flat and simple structure (iterators does not compose easily) and if there are reasons to believe the sequence is rather short especially if it may be stopped before it reach the end. I tend to look at iterators as a low level primitive, except as literals.
For control flow matters, generators are an as much important concept as promises: both are abstract and composable.
You will love this framework.
And you will love this tool.
For learning about JSON you might like this resource.
And you'll probably love this tutorial.
Binding to both mousewheel
and DOMMouseScroll
ended up working really well for me:
$(window).bind('mousewheel DOMMouseScroll', function(event){
if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) {
// scroll up
}
else {
// scroll down
}
});
This method is working in IE9+, Chrome 33, and Firefox 27.
Edit - Mar 2016
I decided to revisit this issue since it's been a while. The MDN page for the scroll event has a great way of retrieving the scroll position that makes use of requestAnimationFrame
, which is highly preferable to my previous detection method. I modified their code to provide better compatibility in addition to scroll direction and position:
(function() {_x000D_
var supportOffset = window.pageYOffset !== undefined,_x000D_
lastKnownPos = 0,_x000D_
ticking = false,_x000D_
scrollDir,_x000D_
currYPos;_x000D_
_x000D_
function doSomething(scrollPos, scrollDir) {_x000D_
// Your code goes here..._x000D_
console.log('scroll pos: ' + scrollPos + ' | scroll dir: ' + scrollDir);_x000D_
}_x000D_
_x000D_
window.addEventListener('wheel', function(e) {_x000D_
currYPos = supportOffset ? window.pageYOffset : document.body.scrollTop;_x000D_
scrollDir = lastKnownPos > currYPos ? 'up' : 'down';_x000D_
lastKnownPos = currYPos;_x000D_
_x000D_
if (!ticking) {_x000D_
window.requestAnimationFrame(function() {_x000D_
doSomething(lastKnownPos, scrollDir);_x000D_
ticking = false;_x000D_
});_x000D_
}_x000D_
ticking = true;_x000D_
});_x000D_
})();
_x000D_
This code is currently working in Chrome v50, Firefox v44, Safari v9, and IE9+
References:
A special case is when trying to assess if a boolean value is nil:
false.present? == false
false.blank? == true
false.nil? == false
In this case the recommendation would be to use .nil?
You could use the below to take multiple inputs separated by a keyword
a,b,c=raw_input("Please enter the age of 3 people in one line using commas\n").split(',')
If you're fine with using the std c library:
#include <sys/stat.h>
off_t fsize(char *file) {
struct stat filestat;
if (stat(file, &filestat) == 0) {
return filestat.st_size;
}
return 0;
}
#include <sstream>
and use the fully qualified name i.e. std::stringstream ss;
Off the top of my head, the following are the only built-ins that are subscriptable:
string: "foobar"[3] == "b"
tuple: (1,2,3,4)[3] == 4
list: [1,2,3,4][3] == 4
dict: {"a":1, "b":2, "c":3}["c"] == 3
But mipadi's answer is correct - any class that implements __getitem__
is subscriptable
with alias as
(
select name,salary,row_number() over(order by salary desc ) as rn from employees
)
select name,salary from alias where rn=n--n being the nth highest salary
You typically set the port at the server using the rmiregistry command. You can set the port on the command line, or it will default to 1099
Add the objects you want to remove to a second array and, after the loop, use -removeObjectsInArray:.
Go TO Environment Variables and Either Remove or set it to empty
HTTP_PROXY and HTTPS_PROXY
it will resolve proxy issue for corporate env too
Quoting part of @Jatin answer with some modifications,
use this in your where
statement:
SELECT * FROM .... etc.
Where
REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE (Name, '0', ''),
'1', ''),
'2', ''),
'3', ''),
'4', ''),
'5', ''),
'6', ''),
'7', ''),
'8', ''),
'9', '') = P_SEARCH_KEY
See this article for a longer discussion of named actions. It also shows that you can use the [HttpGet] attribute instead of prefixing the action name with "get".
http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api
When you add yor map use:
getChildFragmentManager().beginTransaction()
.replace(R.id.menu_map_container, mapFragment, "f" + shabbatIndex).commit();
instead of .add
and instead of getFragmentManager
.
I found this article very helpful to understand the difference between them:
RUN - RUN instruction allows you to install your application and packages required for it. It executes any commands on top of the current image and creates a new layer by committing the results. Often you will find multiple RUN instructions in a Dockerfile.
CMD -
CMD instruction allows you to set a default command, which will be
executed only when you run container without specifying a command.
If Docker container runs with a command, the default command will be
ignored. If Dockerfile has more than one CMD instruction, all but last
CMD instructions are ignored.
Using !important
is not recommended but in this situation I think you should -
Write this in your internal CSS -
.flex-control-thumbs li {
width: auto !important;
float: none !important;
}
Asking about "a class" in the question title, the answer is getElementsByClassName
:
var hrefs = document.getElementsByClassName("YOUR-CLASS-NAME-HERE");
for (var i = 0; i < hrefs.length; i++) {
hrefs.item(i).addEventListener('click', function(e){
e.preventDefault(); /*use if you want to prevent the original link following action*/
alert('hohoho');
});
}
You can enable connection logging. For SQL Server 2008, you can enable Login Auditing. In SQL Server Management Studio, open SQL Server Properties > Security > Login Auditing select "Both failed and successful logins".
Make sure to restart the SQL Server service.
Once you've done that, connection attempts should be logged into SQL's error log. The physical logs location can be determined here.
Corrupted cert and/or key files
For me it was just corrupted files. I copied the contents from GitHub PullRequest webpage and I guess I added an extra space somewhere or whatever... once I grabbed the raw thing and replaced the file, it worked.
Trying to connect to your local computer.try with the hostname "localhost" instead or perhaps ::/ - the last one is ipv6
Does it open correctly when you run "explorer.exe c:\teste" from your start menu? How long have you been trying this? I see a similar behavior when my machine has a lot of processes and when I open a new process(sets say IE)..it starts in the task manager but does not show up in the front end. Have you tried a restart?
The following code should open a new explorer instance
class sample{
static void Main()
{
System.Diagnostics.Process.Start("explorer.exe",@"c:\teste");
}
}
I fully support @Charles Bretana's answer. However, if it's not working, please make sure that there is only one <section>
element AND that configSections
is the first child of the root element:
configsections
must be the first element in your app.Config
after configuration:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821" />
</configSections>
<!-- add log 4 net config !-->
<!-- add others e.g. <startup> !-->
</configuration>
Make sure your Java version matches the project's Java version requirement. This could be an another cause for such kinds of issues.
In PHP, you can send POST data with cURL. Is there something comparable for .NET?
Yes, HttpWebRequest, see my post below.
Per the docs, replace
returns the new string - it does not modify the string you pass it.
var tt="88,9827";
tt = tt.replace(/,/g, '.');
^^^^
alert(tt);
I ran into this page while wondering the same question.
As others have noted, it's simple enough to just grab the __name__
attribute from a function in order to determine the name of the function. It's marginally trickier with objects that don't have a sane way to determine __name__
, i.e. base/primitive objects like basestring instances, ints, longs, etc.
Long story short, you could probably use the inspect module to make an educated guess about which one it is, but you would have to probably know what frame you're working in/traverse down the stack to find the right one. But I'd hate to imagine how much fun this would be trying to deal with eval/exec'ed code.
% python2 whats_my_name_again.py
needle => ''b''
['a', 'b']
[]
needle => '<function foo at 0x289d08ec>'
['c']
['foo']
needle => '<function bar at 0x289d0bfc>'
['f', 'bar']
[]
needle => '<__main__.a_class instance at 0x289d3aac>'
['e', 'd']
[]
needle => '<function bar at 0x289d0bfc>'
['f', 'bar']
[]
%
whats_my_name_again.py:
#!/usr/bin/env python
import inspect
class a_class:
def __init__(self):
pass
def foo():
def bar():
pass
a = 'b'
b = 'b'
c = foo
d = a_class()
e = d
f = bar
#print('globals', inspect.stack()[0][0].f_globals)
#print('locals', inspect.stack()[0][0].f_locals)
assert(inspect.stack()[0][0].f_globals == globals())
assert(inspect.stack()[0][0].f_locals == locals())
in_a_haystack = lambda: value == needle and key != 'needle'
for needle in (a, foo, bar, d, f, ):
print("needle => '%r'" % (needle, ))
print([key for key, value in locals().iteritems() if in_a_haystack()])
print([key for key, value in globals().iteritems() if in_a_haystack()])
foo()
You've only got a forward declaration for student
in the header file; you need to place the struct declaration in the header file, not the .cpp. The method definitions will be in the .cpp (assuming you have any).
You can use ::after
to create a 0px
-height block after the <h4>
, which effectively moves anything after the <h4>
to the next line:
h4 {_x000D_
display: inline;_x000D_
}_x000D_
h4::after {_x000D_
content: "";_x000D_
display: block;_x000D_
}
_x000D_
<ul>_x000D_
<li>_x000D_
Text, text, text, text, text. <h4>Sub header</h4>_x000D_
Text, text, text, text, text._x000D_
</li>_x000D_
</ul>
_x000D_
Now it has full support in latest version of major browsers like Chrome, Edge, Firefox , Safari etc. Here's the comparison between the null operator and Nullish Coalescing Operator
const response = {
settings: {
nullValue: null,
height: 400,
animationDuration: 0,
headerText: '',
showSplashScreen: false
}
};
/* OR Operator */
const undefinedValue = response.settings.undefinedValue || 'Default Value'; // 'Default Value'
const nullValue = response.settings.nullValue || 'Default Value'; // 'Default Value'
const headerText = response.settings.headerText || 'Hello, world!'; // 'Hello, world!'
const animationDuration = response.settings.animationDuration || 300; // 300
const showSplashScreen = response.settings.showSplashScreen || true; // true
/* Nullish Coalescing Operator */
const undefinedValue = response.settings.undefinedValue ?? 'Default Value'; // 'Default Value'
const nullValue = response.settings.nullValue ?? ''Default Value'; // 'Default Value'
const headerText = response.settings.headerText ?? 'Hello, world!'; // ''
const animationDuration = response.settings.animationDuration ?? 300; // 0
const showSplashScreen = response.settings.showSplashScreen ?? true; // false
JavaScript only has a Number type that stores floating point values.
There is no int.
Edit:
If you want to format the number as a string with two digits after the decimal point use:
(4).toFixed(2)
I recommend using the awesome requests library:
import requests
url = 'http://maps.googleapis.com/maps/api/directions/json'
params = dict(
origin='Chicago,IL',
destination='Los+Angeles,CA',
waypoints='Joplin,MO|Oklahoma+City,OK',
sensor='false'
)
resp = requests.get(url=url, params=params)
data = resp.json() # Check the JSON Response Content documentation below
JSON Response Content: https://requests.readthedocs.io/en/master/user/quickstart/#json-response-content
Use ON DUPLICATE KEY UPDATE ...
,
Negative : because the UPDATE
uses resources for the second action.
Use INSERT IGNORE ...
,
Negative : MySQL will not show any errors if something goes wrong, so you cannot handle the errors. Use it only if you don’t care about the query.
Try this,
return RedirectToAction("ActionEventName", "Controller", new { ID = model.ID, SiteID = model.SiteID });
Here i mention you are pass multiple values or model also. That's why here i mention that.
I had the same issue, multiple data type values in single column, package load only numeric values. Remains all it updated as null.
Solution
To fix this changing the excel data type is one of the solution. In Excel Copy the column data and paste in different file. Delete that column and insert new column as Text datatype and paste that copied data in new column.
Now in ssis package delete and recreate the Excel source and destination table change the column data type as varchar.
This will work.
Sorry for tacking on to an old thread, but I think something that was said above may be incorrect/misleading.
From what I can tell .Timeout is NOT the connection time, it is the TOTAL time allowed for the entire life of the HttpWebRequest and response. Proof:
I Set:
.Timeout=5000
.ReadWriteTimeout=32000
The connect and post time for the HttpWebRequest took 26ms
but the subsequent call HttpWebRequest.GetResponse() timed out in 4974ms thus proving that the 5000ms was the time limit for the whole send request/get response set of calls.
I didn't verify if the DNS name resolution was measured as part of the time as this is irrelevant to me since none of this works the way I really need it to work--my intention was to time out quicker when connecting to systems that weren't accepting connections as shown by them failing during the connect phase of the request.
For example: I'm willing to wait 30 seconds on a connection request that has a chance of returning a result, but I only want to burn 10 seconds waiting to send a request to a host that is misbehaving.
The accepted answer will return all the parent nodes too. To get only the actual nodes with ABC even if the string is after
:
//*[text()[contains(.,'ABC')]]/text()[contains(.,"ABC")]
In VScode, they call this Copy Line Up
and Copy Line Down
From the menu, go to:
File > Preferences > Keyboard Shortcuts
Check already assigned keyboard shortcut for this, or adjust yours.
Sometimes the default assigned shortcut may not work, mostly because of OS.
In my Ubuntu, I adjusted this to: Ctrl+Shift+D
After six days I find the answer which make me crazy! The answer is disable proxy at web.config file:
<system.net>
<defaultProxy>
<proxy usesystemdefault="False"/>
</defaultProxy>
</system.net>
Immediately after that line try closing the response using exit
or die()
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
exit;
or
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
die();
You could name the anonymous delegate :-)
And you can write the second as:
someList.ForEach(s => s.ToUpper())
Which I prefer, and saves a lot of typing.
As Joachim says, parallelism is easier to apply to the second form.
Reminder
SQL Server only allows one table to have IDENTITY_INSERT property set to ON.
This does not work:
SET IDENTITY_INSERT TableA ON
SET IDENTITY_INSERT TableB ON
... INSERT ON TableA ...
... INSERT ON TableB ...
SET IDENTITY_INSERT TableA OFF
SET IDENTITY_INSERT TableB OFF
Instead:
SET IDENTITY_INSERT TableA ON
... INSERT ON TableA ...
SET IDENTITY_INSERT TableA OFF
SET IDENTITY_INSERT TableB ON
... INSERT ON TableB ...
SET IDENTITY_INSERT TableB OFF
I installed mod_rewrite to fix the issue. Below link provides an installation guide:- http://www.iasptk.com/enable-apache-mod_rewrite-ubuntu-14-04-lts/
In MySQL
:-
RENAME TABLE `Stu Table` TO `Stu Table_10`
type Services
at search, then start Services
then start all VM services
If you want to revert the element to the source position if it's not dropped inside a #droppable
element, just save the original parent element of the draggable at the start of the script (instead of the position), and if you verify that it's not dropped into #droppable
, then just restore the parent of #draggable
to this original element.
So, replace this:
}).each(function() {
var top = $(this).position().top;
var left = $(this).position().left;
$(this).data('orgTop', top);
$(this).data('orgLeft', left);
});
with this:
}).each(function() {
$(this).data('originalParent', $(this).parent())
});
Here, you'll have the original parent element of the draggable. Now, you have to restore it's parent in a precise moment.
drop
is called every time the element is dragged out from the droppable, not at the stop. So, you're adding a lot of event callbacks. This is wrong, because you never clean the mouseup
event. A good place where you can hook a callback and check if the element was dropped inside or outside the #droppable
element, is revert
, and you're doing it right now, so, just delete the drop
callback.
When the element is dropped, and needs to know if it should be reverted or not, you know for sure that you'll not have any other interaction from the user until the new drag start. So, using the same condition you're using to know if it should revert or know, let's replace this alert
with a fragment of code that: restores the parent element to the original div, and resets the originalPosition
from the draggable
internals. The originalPosition
proeprty is setted at the time of _mouseStart
, so, if you change the owner of the element, you should reset it, in order to make the animation of revert go to the proper place. So, let's set this to {top: 0, left: 0}
, making the animation go to the origin point of the element:
revert: function(dropped) {
var dropped = dropped && dropped[0].id == "droppable";
if(!dropped) {
$(this).data("draggable").originalPosition = {top:0, left:0}
$(this).appendTo($(this).data('originalParent'))
}
return !dropped;
}
And that's it! You can check this working here: http://jsfiddle.net/eUs3e/1/
Take into consideration that, if in any jQuery's UI update, the behavior of revert
or originalPosition
changes, you'll need to update your code in order to make it work. Keep in mind that.
If you need a solution which doesn't make use of calls to the internals of ui.draggable, you can make your body
an droppable element with greedy
option defined as false
. You'll have to make sure that your body
elements take the full screen.
Good luck!
For MYSQL
ALTER TABLE myTable MODIFY myColumn {DataType} NULL
Try git merge origin/master
. If you want to be sure that it only does a fast-forward, you can say git merge --ff-only origin/master
.
There are 4 levels of API defined in the Richardson Maturity Model. These are defined as:
level 0: any system that has a single endpoint for all its apis(SOAP or RPC fall in this category). Level 0 apis can also resemble "commands".
level 1: a ResourceUri described system. This is a system that defines multiple entity-based URIs (instead of having a single endpoint like a level 0 systems would). These URIs can use different http actions (POST, GET, PUT, etc) to implement different actions against that resource.
level 2: aka level 1 w/ a compliant use of Standard HTTP methods/verbs and multi status code responses
level 3: aka level 2 plus HATEOAS (hypermedia included in the response which describes additional calls you can make)
While levels 1, level 2, and level 3 can be considered as REST systems, only the stricter levels (aka level 2 and level 3) are considered to be RESTful.
So essentially all RESTful apis are REST apis, but not all REST apis are RESTful
@Nickparsa … you have 2 issues:
1). mysql -uroot -p
should be typed in bash (also known as your terminal) not in MySQL command-line. You fix this error by typing
exit
in your MySQL command-line. Now you are back in your bash/terminal command-line.
2). You have a syntax error:
mysql -uroot -p;
the semicolon in front of -p needs to go. The correct syntax is:
mysql -uroot -p
type the correct syntax in your bash commandline. Enter a password if you have one set up; else just hit the enter button. You should get a response that is similar to this:
Hope this helps!
This should work for you. Infact the one which you are thinking will also work:-
.......
DECLARE @returnvalue INT
EXEC @returnvalue = SP_One
.....
A File object in Java is a representation of a path to a directory or file, not the file itself. You don't need to have write access to the filesystem to create a File
object, you only need it if you intend to actually write to the file (using a FileOutputStream for example)
var lst = new List<int>() { 1, 2, 3 };
var ans = lst.Where( i => i > 3 );
(ans == null).Dump(); // False
(ans.Count() == 0 ).Dump(); // True
(Dump is from LinqPad)
I actually had this kind of problem and I solve it by these steps:
Get the bundle of root CA certificates from here: https://curl.haxx.se/ca/cacert.pem and save it on local
Find the php.ini
file
Set the curl.cainfo
to be the path of the certificates. So it will something like:
curl.cainfo = /path/of/the/keys/cacert.pem
Change the database.php file from
$db['default']['dbdriver'] = 'mysql';
to
$db['default']['dbdriver'] = 'mysqli';
Try this
if(name.getText() != null && name.getText().equals(""))
{
loginbt.setEnabled(false);
}
else
{
loginbt.setEnabled(true);
}
Paste this code after setContentView or into onCreate
if you have a color code use this ;
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#408ed4")));
if you want a specific code from Color library use this ;
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
Hiding through CSS is achieved by using either the "visibility" or the "display" attributes. Though both achieve similar results, it's useful to know the differences.
If you only want to hide the element but retain the space occupied by it, you should use:
#mybox:hover {
visibility: hidden;
}
If you want to hide the element and remove the space occupied by it, so that other elements can take its space, then you should use:
#mybox:hover {
display: none;
}
Also remember that IE6 and below do not respond to :hover for anything except A tags. In which case, you'll need some Javascript to change the classname:
document.getElementById('mybox').className = 'hide';
and define the "hide" class in CSS:
.hide { display: none; }
For those like me who would rather not embed their UITableViewController
in a UIViewController
try this:
A custom UITableViewController
subclass can append a mask view to the tableView's superview. Add the mask on viewDidAppear, and remove the mask on viewWillDisappear.
private var statusBarMaskView: UIView!
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let superview = self.tableView.superview {
self.statusBarMaskView = UIView(frame: CGRect.zero)
superview.insertSubview(self.statusBarMaskView, aboveSubview: self.tableView)
self.statusBarMaskView.backgroundColor = self.tableView.backgroundColor
// using a nice constraint layout library to set the frame
self.statusBarMaskView.pinTop(to: superview)
self.statusBarMaskView.pinLeft(to: superview)
self.statusBarMaskView.pinRight(to: superview)
self.statusBarMaskView.addHeightConstraint(with: 22.0)
////
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.statusBarMaskView.removeFromSuperview()
self.statusBarMaskView = nil
}
Shortcut way: (windows xp)
1) click Start > run > services.msc
2) Scroll down to 'Windows Presentation Foundation Font Cache 4.0.0.0' and then right click and select properties
rx = r'\b(?<=\w){0}\b(?!\w)'.format(TEXTO)
Start GDB on your project.
Go to project directory, where you've already compiled the project executable. Issue the command gdb and the name of the executable as below:
gdb projectExecutablename
This starts up gdb, prints the following: GNU gdb (Ubuntu 7.11.1-0ubuntu1~16.04) 7.11.1 Copyright (C) 2016 Free Software Foundation, Inc. ................................................. Type "apropos word" to search for commands related to "word"... Reading symbols from projectExecutablename...done. (gdb)
Before you start your program running, you want to set up your breakpoints. The break command allows you to do so. To set a breakpoint at the beginning of the function named main:
(gdb) b main
Once you've have the (gdb) prompt, the run command starts the executable running. If the program you are debugging requires any command-line arguments, you specify them to the run command. If you wanted to run my program on the "xfiles" file (which is in a folder "mulder" in the project directory), you'd do the following:
(gdb) r mulder/xfiles
Hope this helps.
Disclaimer: This solution is not mine, it is adapted from https://web.stanford.edu/class/cs107/guide_gdb.html This short guide to gdb was, most probably, developed at Stanford University.
To complement the existing helpful answers:
Using Bash's own regex-matching operator, =~
, is a faster alternative in this case, given that you're only matching a single value already stored in a variable:
set -- '12-34-5678' # set $1 to sample value
kREGEX_DATE='^[0-9]{2}[-/][0-9]{2}[-/][0-9]{4}$' # note use of [0-9] to avoid \d
[[ $1 =~ $kREGEX_DATE ]]
echo $? # 0 with the sample value, i.e., a successful match
Note, however, that the caveat re using flavor-specific regex constructs such as \d
equally applies:
While =~
supports EREs (extended regular expressions), it also supports the host platform's specific extension - it's a rare case of Bash's behavior being platform-dependent.
To remain portable (in the context of Bash), stick to the POSIX ERE specification.
Note that =~
even allows you to define capture groups (parenthesized subexpressions) whose matches you can later access through Bash's special ${BASH_REMATCH[@]}
array variable.
Further notes:
$kREGEX_DATE
is used unquoted, which is necessary for the regex to be recognized as such (quoted parts would be treated as literals).
While not always necessary, it is advisable to store the regex in a variable first, because Bash has trouble with regex literals containing \
.
\<
is supported to match word boundaries, [[ 3 =~ \<3 ]] && echo yes
doesn't work, but re='\<3'; [[ 3 =~ $re ]] && echo yes
does.I've changed variable name REGEX_DATE
to kREGEX_DATE
(k
signaling a (conceptual) constant), so as to ensure that the name isn't an all-uppercase name, because all-uppercase variable names should be avoided to prevent conflicts with special environment and shell variables.
This is based on Jim's answer,
SELECT
@field_text + SPACE(@pad_length - LEN(@field_text)) AS RightPad
,SPACE(@pad_length - LEN(@field_text)) + @field_text AS LeftPad
Advantages
Disadvantages
For IntelliJ Mac / IOS,
Click on IntelliJ IDEA
text besides on top left corner then Preferences->Editor->Color Scheme-> Select the required one
For python version >= 3.6 (see PEP 498)
s1='albha'
s2='beta'
f'{s1}{s2:>10}'
#output
'albha beta'
Get the querystring collection, parse it into a (name=value pair
) string, excluding the one you want to REMOVE, and name it newQueryString
Then call Response.Redirect(known_path?newqueryString)
;
it is similar to jason lee as he mentioned earlier:
in Jupyter notebook, you can access the current working directory by
pwd()
or by import OS from library and running os.getcwd()
i.e. for example
In[ ]: import os
os.getcwd( )
out[ ]: :c\\users\\admin\\Desktop\\python
(#This is my working directory)
Changing Working Directory
For changing the Working Directory (much more similar to current W.d just you need to change from os.getcwd()
to os.chdir('desired location')
In[ ]: import os
os.chdir('c:user/chethan/Desktop') (#This is where i want to update my w.d,
like that choose your desired location)
out[ ]: 'c:user\\chethan\\Desktop'
window.location = myUrl;
Anyway, this is not jQuery: it's plain javascript
Use this SQL:
SELECT DATE_FORMAT(date_column_here,'%d/%m/%Y') FROM table_name;
Also, if you're performing the query on the Bash command line, I believe the tr
command can be used to substitute the default tabs to arbitrary delimiters.
$ echo "SELECT * FROM Table123" | mysql Database456 | tr "\t" ,
>>> a={ 'a': 1, 'b': 2, 'c': 3 } >>> [(x,a[x]) for x in a.keys() ] [('a', 1), ('c', 3), ('b', 2)] >>> [(a[x],x) for x in a.keys() ] [(1, 'a'), (3, 'c'), (2, 'b')]
I was challenged by the same error message, with .net 4.7 installed.
The solution was to follow one earlier mentioned post to go with the "Turn Windows feature on or off", where the ".NET Framework 4.7 Advanced Services" --> "ASP.NET 4.7" already was checked.
Further down the list, there is the "Internet Information Services" and subnote "Application Development Features" --> "ASP.NET 4.7", that also needs to be checked.
When enabling this, allot of other features are enabled... I simply pressed the Ok button, and the issue was resolved. Screendump of the windows features dialog
You can use a scope watch:
$scope.$watch('user', function(newValue, oldValue) {
// access new and old value here
console.log("Your former user.name was "+oldValue.name+", you're current user name is "+newValue.name+".");
});
https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watch
ServicePointManager.ServerCertificateValidationCallback isn't supported in .Net Core.
Current situation is that it will be a a new ServerCertificateCustomValidationCallback method for the upcoming 4.1.* System.Net.Http contract (HttpClient). .NET Core team are finalizing the 4.1 contract now. You can read about this in here on github
You can try out the pre-release version of System.Net.Http 4.1 by using the sources directly here in CoreFx or on the MYGET feed: https://dotnet.myget.org/gallery/dotnet-core
Current WinHttpHandler.ServerCertificateCustomValidationCallback definition on Github
Circular imports cause problems, but Python has ways to mitigate it built-in.
The problem is when you run python a.py
, it runs a.py
but not mark it imported as a module. So in turn a.py
-> imports module b -> imports module a -> imports module b. The last import a no-op since b is currently being imported and Python guards against that. And b is an empty module for now. So when it executes b.hi()
, it can't find anything.
Note that the b.hi()
that got executed is during a.py
-> module b -> module a, not in a.py
directly.
In your specific example, you can just run python -c 'import a'
at top-level, so the first execution of a.py
is registered as importing a module.
EDIT
I think the reason that your table is not responsive to start with was you did not wrap in .container
, .row
and .col-md-x
classes like this one
<div class="container">
<div class="row">
<div class="col-md-12">
<!-- or use any other number .col-md- -->
<div class="table-responsive">
<div class="table">
</div>
</div>
</div>
</div>
</div>
With this, you can still use <p>
tags and even make it responsive.
Please see the Bootply example here
I use GET/204 with a RESTful collection that is a positional array of known fixed length but with holes.
GET /items
200: ["a", "b", null]
GET /items/0
200: "a"
GET /items/1
200: "b"
GET /items/2
204:
GET /items/3
404: Not Found
I used the got and lost focus events:
Private Sub txtSearchBox_GotFocus(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles txtSearchBox.GotFocus
If txtSearchBox.Text = "Search" Then
txtSearchBox.Text = ""
Else
End If
End Sub
Private Sub txtSearchBox_LostFocus(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles txtSearchBox.LostFocus
If txtSearchBox.Text = "" Then
txtSearchBox.Text = "Search"
Else
End If
End Sub
It works well, but the text is in gray still. Needs cleaning up. I was using VB.NET
A submodule may be marked as dirty if filemode settings is enabled and you changed file permissions in submodule subtree.
To disable filemode in a submodule, you can edit /.git/modules/path/to/your/submodule/config and add
[core]
filemode = false
If you want to ignore all dirty states, you can either set ignore = dirty
property in /.gitmodules file, but I think it's better to only disable filemode.
I arrive late I know but I answer this because I think this solution is simple and elegant:
List<String> listFixed = new ArrayList<String>();
List<String> dynamicList = new ArrayList<String>();
public void fillingList() {
listFixed.add("Andrea");
listFixed.add("Susana");
listFixed.add("Oscar");
listFixed.add("Valeria");
listFixed.add("Kathy");
listFixed.add("Laura");
listFixed.add("Ana");
listFixed.add("Becker");
listFixed.add("Abraham");
dynamicList.addAll(listFixed);
}
public void updatingListFixed() {
for (String newList : dynamicList) {
if (!listFixed.contains(newList)) {
listFixed.add(newList);
}
}
//this is for add elements if you want eraser also
String removeRegister="";
for (String fixedList : listFixed) {
if (!dynamicList.contains(fixedList)) {
removeResgister = fixedList;
}
}
fixedList.remove(removeRegister);
}
All this is for updating from one list to other and you can make all from just one list and in method updating you check both list and can eraser or add elements betwen list. This means both list always it same size
try this,
package example.txtRead;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Vector;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class txtRead extends Activity {
String labels="caption";
String text="";
String[] s;
private Vector<String> wordss;
int j=0;
private StringTokenizer tokenizer;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
wordss = new Vector<String>();
TextView helloTxt = (TextView)findViewById(R.id.hellotxt);
helloTxt.setText(readTxt());
}
private String readTxt(){
InputStream inputStream = getResources().openRawResource(R.raw.toc);
// InputStream inputStream = getResources().openRawResource(R.raw.internals);
System.out.println(inputStream);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return byteArrayOutputStream.toString();
}
}
Or - build on @Jamaica Geek's answer, using Express - to avoid saving and reading a file:
res.attachment('file.xls');
var header="Sl No"+"\t"+" Age"+"\t"+"Name"+"\n";
var row1 = [0,21,'BOB'].join('\t')
var row2 = [0,22,'bob'].join('\t');
var c = header + row1 + row2;
return res.send(c);
You might try using a library like redux-saga. It allows for a very clean way to sequence async functions, fire off actions, use delays and more. It is very powerful!
post_max_size should be slightly bigger than upload_max_filesize, because when uploading using HTTP POST method the text also includes headers with file size and name, etc.
If you want to successfully uppload 1GiB files, you have to set:
upload_max_filesize = 1024M
post_max_size = 1025M
Note, the correct suffix for GB is G, i.e. upload_max_filesize = 1G.
No need to set memory_limit.
In Python shape()
is use in pandas to give number of row/column:
Number of rows is given by:
train = pd.read_csv('fine_name') //load the data
train.shape[0]
Number of columns is given by
train.shape[1]
You need to specify a type on person:
void addStudent(struct student person) {
...
}
Also, you can typedef your struct to avoid having to type struct every time you use it:
typedef struct student{
...
} student_t;
void addStudent(student_t person) {
...
}
What context/language? Some languages use /
as the pattern delimiter, so yes, you need to escape it, depending on which language/context. You escape it by putting a backward slash in front of it: \/
For some languages (like PHP) you can use other characters as the delimiter and therefore you don't need to escape it. But AFAIK in all languages, the only special significance the /
has is it may be the designated pattern delimiter.
Try this:
SELECT DISTINCT * FROM (
SELECT column1, column2 FROM Table1
UNION ALL
SELECT column1, column2 FROM Table2
UNION ALL
SELECT column1, column2 FROM Table3
) X ORDER BY Column1
A nice one liner to list only the files recursively. I used this in my setup.py package_data directive:
import os
[os.path.join(x[0],y) for x in os.walk('<some_directory>') for y in x[2]]
I know it's not the answer to the question, but may come in handy
The simplest way is to map over the DataFrame's RDD and use mkString:
df.rdd.map(x=>x.mkString(","))
As of Spark 1.5 (or even before that)
df.map(r=>r.mkString(","))
would do the same
if you want CSV escaping you can use apache commons lang for that. e.g. here's the code we're using
def DfToTextFile(path: String,
df: DataFrame,
delimiter: String = ",",
csvEscape: Boolean = true,
partitions: Int = 1,
compress: Boolean = true,
header: Option[String] = None,
maxColumnLength: Option[Int] = None) = {
def trimColumnLength(c: String) = {
val col = maxColumnLength match {
case None => c
case Some(len: Int) => c.take(len)
}
if (csvEscape) StringEscapeUtils.escapeCsv(col) else col
}
def rowToString(r: Row) = {
val st = r.mkString("~-~").replaceAll("[\\p{C}|\\uFFFD]", "") //remove control characters
st.split("~-~").map(trimColumnLength).mkString(delimiter)
}
def addHeader(r: RDD[String]) = {
val rdd = for (h <- header;
if partitions == 1; //headers only supported for single partitions
tmpRdd = sc.parallelize(Array(h))) yield tmpRdd.union(r).coalesce(1)
rdd.getOrElse(r)
}
val rdd = df.map(rowToString).repartition(partitions)
val headerRdd = addHeader(rdd)
if (compress)
headerRdd.saveAsTextFile(path, classOf[GzipCodec])
else
headerRdd.saveAsTextFile(path)
}
Just use the function plot
as follows
figure()
...
plot(t, a)
plot(t, b)
plot(t, c)
None of the above worked for me - the following did:
devenv /ResetSettings
The nice thing about this option was it didn't wipe out all of my Visual Studio configuration (as /ResetUserData does)
The simplest way to do this is by
df["DateColumn"] = (df["DateColumn"]).dt.days
I am creating a folder under /data/ in my init.rc (mucking around with the aosp on Nexus 7) and had exactly this problem.
It turned out that giving the folder rw (666) permission was not sufficient and it had to be rwx (777) then it all worked!
Taken from http://www.dotnetspider.com/resources/189-AutoPostBack-What-How-works.aspx:
Autopostback
is the mechanism by which the page will be posted back to the server automatically based on some events in the web controls. In some of the web controls, the property called auto post back, if set to true, will send the request to the server when an event happens in the control.Whenever we set the autopostback attribute to true on any of the controls, the .NET framework will automatically insert a few lines of code into the HTML generated to implement this functionality.
- A JavaScript method with name __doPostBack (eventtarget, eventargument)
- Two hidden variables with name __EVENTTARGET and __EVENTARGUMENT
- OnChange JavaScript event to the control
Opening a file creates it and (unless append ('a') is set) overwrites it with emptyness, such as this:
open(filename, 'w').close()
The example code here http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.connected.aspx shows how to determine whether the Socket is still connected without sending any data.
If you called Socket.BeginReceive() on the server program and then the client closed the connection "gracefully", your receive callback will be called and EndReceive() will return 0 bytes. These 0 bytes mean that the client "may" have disconnected. You can then use the technique shown in the MSDN example code to determine for sure whether the connection was closed.
By "shallow copying" it means the content of the dictionary is not copied by value, but just creating a new reference.
>>> a = {1: [1,2,3]}
>>> b = a.copy()
>>> a, b
({1: [1, 2, 3]}, {1: [1, 2, 3]})
>>> a[1].append(4)
>>> a, b
({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})
In contrast, a deep copy will copy all contents by value.
>>> import copy
>>> c = copy.deepcopy(a)
>>> a, c
({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})
>>> a[1].append(5)
>>> a, c
({1: [1, 2, 3, 4, 5]}, {1: [1, 2, 3, 4]})
So:
b = a
: Reference assignment, Make a
and b
points to the same object.
b = a.copy()
: Shallow copying, a
and b
will become two isolated objects, but their contents still share the same reference
b = copy.deepcopy(a)
: Deep copying, a
and b
's structure and content become completely isolated.
Another way would be to catch the exeption:
def is_nat(npdatetime):
try:
npdatetime.strftime('%x')
return False
except:
return True
max233 was certainly on the right track, at least for the autoincrement case. However, do not do the ALTER TABLE. Simply set the auto-increment field in the temporary table to NULL. This will present an error, but the following INSERT of all fields in the temporary table will happen and the NULL auto field will obtain a unique value.
It is not very efficient solution, but working one:
public static <T> T getFirstElement(final Iterable<T> elements) {
return elements.iterator().next();
}
public static <T> T getLastElement(final Iterable<T> elements) {
T lastElement = null;
for (T element : elements) {
lastElement = element;
}
return lastElement;
}
All I needed to do was restart Visual Studio, open the NuGet Package Manager Console
, and then using the Manage NuGet Packages
dialog worked.
var html = "";
for (var i = 0; i < data.length; i++){
html +="<tr>"+
"<td>"+ (i+1) + "</td>"+
"<td>"+ data[i].name + "</td>"+
"<td>"+ data[i].number + "</td>"+
"<td>"+ data[i].city + "</td>"+
"<td>"+ data[i].hobby + "</td>"+
"<td>"+ data[i].birthdate + "</td>"+"<td><button data-arrayIndex='"+ i +"' onclick='editData(this)'>Edit</button><button data-arrayIndex='"+ i +"' onclick='deleteData()'>Delete</button></td>"+"</tr>";
}
$("#tableHtml").html(html);
Use OnCommand event of imagebutton. Within it do
<asp:Button id="Button1" Text="Click" CommandName="Something" CommandArgument="your command arg" OnCommand="CommandBtn_Click" runat="server"/>
Code-behind:
void CommandBtn_Click(Object sender, CommandEventArgs e)
{
switch(e.CommandName)
{
case "Something":
// Do your code
break;
default:
break;
}
}
Response status comes as second parameter in callback, (from docs):
// Simple GET request example :
$http.get('/someUrl').
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Assuming the image data is already in the format you want, you don't need image ImageIO
at all - you just need to write the data to the file:
// Note preferred way of declaring an array variable
byte[] data = Base64.decodeBase64(crntImage);
try (OutputStream stream = new FileOutputStream("c:/decode/abc.bmp")) {
stream.write(data);
}
(I'm assuming you're using Java 7 here - if not, you'll need to write a manual try/finally statement to close the stream.)
If the image data isn't in the format you want, you'll need to give more details.
You can imitate the C idiom in Python.
To read a buffer up to max_size
number of bytes, you can do this:
with open(filename, 'rb') as f:
while True:
buf = f.read(max_size)
if not buf:
break
process(buf)
Or, a text file line by line:
# warning -- not idiomatic Python! See below...
with open(filename, 'rb') as f:
while True:
line = f.readline()
if not line:
break
process(line)
You need to use while True / break
construct since there is no eof test in Python other than the lack of bytes returned from a read.
In C, you might have:
while ((ch != '\n') && (ch != EOF)) {
// read the next ch and add to a buffer
// ..
}
However, you cannot have this in Python:
while (line = f.readline()):
# syntax error
because assignments are not allowed in expressions in Python (although recent versions of Python can mimic this using assignment expressions, see below).
It is certainly more idiomatic in Python to do this:
# THIS IS IDIOMATIC Python. Do this:
with open('somefile') as f:
for line in f:
process(line)
Update: Since Python 3.8 you may also use assignment expressions:
while line := f.readline():
process(line)
So i had a adifferent case where i needed to assign values before running a session, So this was the easiest way to do that:
other_variable = tf.get_variable("other_variable", dtype=tf.int32,
initializer=tf.constant([23, 42]))
here i'm creating a variable as well as assigning it values at the same time
To select columns to plot, I added 2 lines to Vincent Zoonekynd's answer:
#convert to tall/long format(from wide format)
col_plot = c("A","B")
dlong <- melt(d[,c("Xax", col_plot)], id.vars="Xax")
#"value" and "variable" are default output column names of melt()
ggplot(dlong, aes(Xax,value, col=variable)) +
geom_point() +
geom_smooth()
Google "tidy data" to know more about tall(or long)/wide format.
I think you are looking for print_r which will print out the array as text. You can't control the formatting though, it's more for debugging. If you want cool formatting you'll need to do it manually.
Why would anyone want a mouse over event on a drop down list? Here's a way of manipulating IE8 for the way a drop down list should work:
First, let's make sure we are only passing our function in IE8:
var isIE8 = $.browser.version.substring(0, 2) === "8.";
if (isIE8) {
//fix me code
}
Then, to allow the select to expand outside of the content area, let's wrap our drop down lists in div's with the correct structure, if not already, and then call the helper function:
var isIE8 = $.browser.version.substring(0, 2) === "8.";
if (isIE8) {
$('select').wrap('<div class="wrapper" style="position:relative; display: inline-block; float: left;"></div>').css('position', 'absolute');
//helper function for fix
ddlFix();
}
Now onto the events. Since IE8 throws an event after focusing in for whatever reason, IE will close the widget after rendering when trying to expand. The work around will be to bind to 'focusin' and 'focusout' a class that will auto expand based on the longest option text. Then, to ensure a constant min-width that doesn't shrink past the default value, we can obtain the current select list width, and set it to the drop down list min-width property on the 'onchange' binding:
function ddlFix() {
var minWidth;
$('select')
.each(function () {
minWidth = $(this).width();
$(this).css('min-width', minWidth);
})
.bind('focusin', function () {
$(this).addClass('expand');
})
.change(function () {
$(this).css('width', minWidth);
})
.bind('focusout', function () {
$(this).removeClass('expand');
});
}
Lastly, make sure to add this class in the style sheet:
select:focus, select.expand {
width: auto;
}
If your segue exists in the storyboard with a segue identifier between your two views, you can just call it programmatically using:
performSegue(withIdentifier: "mySegueID", sender: nil)
For older versions:
performSegueWithIdentifier("mySegueID", sender: nil)
You could also do:
presentViewController(nextViewController, animated: true, completion: nil)
Or if you are in a Navigation controller:
self.navigationController?.pushViewController(nextViewController, animated: true)
Select *, (Select SUM(SOMENUMT)
From @t S
Where S.id <= M.id)
From @t M
Shortest (correct) version:
grep -q "something" file; [ $? -eq 0 ] && echo "yes" || echo "no"
can be also written as
grep -q "something" file; test $? -eq 0 && echo "yes" || echo "no"
but you dont need to explicitly test it in this case, so the same with:
grep -q "something" file && echo "yes" || echo "no"
This might help someone:
I am installing the latest Java on my system for development, and currently it's Java SE 7. Now, let's dive into this "madness", as you put it...
All of these are the same (when developers are talking about Java for development):
Starting with Java v1.5:
And we can assume this will remain for future versions.
Next, for developers, download JDK, not JRE.
JDK will contain JRE. If you need JDK and JRE, get JDK. Both will be installed from the single JDK install, as you will see below.
As someone above mentioned:
Here's the step by step links I followed (one step leads to the next, this is all for a single download) to download Java for development (JDK):
Keep in mind the above links are for reference purposes only, to show you the step by step method of what it takes to download the JDK.
And install with default settings to:
Remember from above that JDK contains JRE, which makes sense if you know what they both are. Again, see above.
After your install, double check “C:\Program Files\Java” to see both these folders. Now you know what they are and why they are there.
I know I wrote this for newbies, but I enjoy knowing things in full detail, so I hope this helps.
String
vs string
Argument of type 'String' is not assignable to parameter of type 'string'.
'string' is a primitive, but 'String' is a wrapper object.
Prefer using 'string' when possible.
String Object
// error
class SVGStorageUtils {
store: object;
constructor(store: object) {
this.store = store;
}
setData(key: String = ``, data: object) {
sessionStorage.setItem(key, JSON.stringify(data));
}
getData(key: String = ``) {
const obj = JSON.parse(sessionStorage.getItem(key));
}
}
string primitive
// ok
class SVGStorageUtils {
store: object;
constructor(store: object) {
this.store = store;
}
setData(key: string = ``, data: object) {
sessionStorage.setItem(key, JSON.stringify(data));
}
getData(key: string = ``) {
const obj = JSON.parse(sessionStorage.getItem(key));
}
}
In Java, the 'int' type is a primitive, whereas the 'Integer' type is an object.
In C#, the 'int' type is the same as System.Int32
and is a value type (ie more like the java 'int'). An integer (just like any other value types) can be boxed ("wrapped") into an object.
The differences between objects and primitives are somewhat beyond the scope of this question, but to summarize:
Objects provide facilities for polymorphism, are passed by reference (or more accurately have references passed by value), and are allocated from the heap. Conversely, primitives are immutable types that are passed by value and are often allocated from the stack.
If you're doing this in Drupal and use the Form API to change the #type from text to 'hidden' in hook_form_alter (for example), be advised that the output HTML will have different (or omitted) DIV wrappers, IDs and class names.
on os x these are the same for me... could this maybe be extra "\r" in windows?
in any case you may be better of with:
contents = File.read("e.tgz")
newFile = File.open("ee.tgz", "w")
newFile.write(contents)
Not sure what you meant, but you can permanently turn showing whitespaces on and off in Settings -> Editor -> General -> Appearance -> Show whitespaces
.
Also, you can set it for a current file only in View -> Active Editor -> Show WhiteSpaces
.
Edit:
Had some free time since it looks like a popular issue, I had written a plugin to inspect the code for such abnormalities. It is called Zero Width Characters locator and you're welcome to give it a try.
Handle the form’s Resize event. In this handler, you override the basic functionality of the Resize event to make the form minimize to the system tray and not to the taskbar. This can be done by doing the following in your form’s Resize event handler: Check whether the form’s WindowState property is set to FormWindowState.Minimized. If yes, hide your form, enable the NotifyIcon object, and show the balloon tip that shows some information. Once the WindowState becomes FormWindowState.Normal, disable the NotifyIcon object by setting its Visible property to false. Now, you want the window to reappear when you double click on the NotifyIcon object in the taskbar. For this, handle the NotifyIcon’s MouseDoubleClick event. Here, you show the form using the Show() method.
private void frmMain_Resize(object sender, EventArgs e)
{
if (FormWindowState.Minimized == this.WindowState)
{
mynotifyicon.Visible = true;
mynotifyicon.ShowBalloonTip(500);
this.Hide();
}
else if (FormWindowState.Normal == this.WindowState)
{
mynotifyicon.Visible = false;
}
}
A good solution if you are used to the chrome inspector tools is Pony debugger: https://github.com/square/PonyDebugger
It is a bit of a pain to setup, but once you do it work well. Be sure to use Safari instead of Chrome to use it though.
foreach($results['data'] as $result) {
echo $result['type'], '<br />';
}
or echo $results['data'][1]['type'];
You can use recursion here to do this. For example:
jQuery(document).ready(checkContainer);
function checkContainer () {
if($('#divIDer').is(':visible'))){ //if the container is visible on the page
createGrid(); //Adds a grid to the html
} else {
setTimeout(checkContainer, 50); //wait 50 ms, then try again
}
}
Basically, this function will check to make sure that the element exists and is visible. If it is, it will run your createGrid()
function. If not, it will wait 50ms and try again.
Note:: Ideally, you would just use the callback function of your AJAX call to know when the container was appended, but this is a brute force, standalone approach. :)
using System;
namespace ConsoleApp1
{
class Program
{
static void Main()
{
Console.WriteLine("Enter Your FirstName ");
String FirstName = Console.ReadLine();
Console.WriteLine("Enter Your LastName ");
String LastName = Console.ReadLine();
Console.ReadLine();
Console.WriteLine("Hello {0}, {1} ", FirstName, LastName);
Console.ReadLine();
}
}
}
Use an HTML line break (<br />
) to force a line break within a table cell:
|Something|Something else<br />that's rather long|Something else|
The examples have very different outcomes.
Before looking at the differences, the following should be noted:
[[Prototype]]
property.myObj.method()
) then this within the method references the object. Where this is not set by the call or by the use of bind, it defaults to the global object (window in a browser) or in strict mode, remains undefined.So here are the snippets in question:
var A = function () {
this.x = function () {
//do something
};
};
In this case, variable A
is assigned a value that is a reference to a function. When that function is called using A()
, the function's this isn't set by the call so it defaults to the global object and the expression this.x
is effective window.x
. The result is that a reference to the function expression on the right-hand side is assigned to window.x
.
In the case of:
var A = function () { };
A.prototype.x = function () {
//do something
};
something very different occurs. In the first line, variable A
is assigned a reference to a function. In JavaScript, all functions objects have a prototype property by default so there is no separate code to create an A.prototype object.
In the second line, A.prototype.x is assigned a reference to a function. This will create an x property if it doesn't exist, or assign a new value if it does. So the difference with the first example in which object's x property is involved in the expression.
Another example is below. It's similar to the first one (and maybe what you meant to ask about):
var A = new function () {
this.x = function () {
//do something
};
};
In this example, the new
operator has been added before the function expression so that the function is called as a constructor. When called with new
, the function's this is set to reference a new Object whose private [[Prototype]]
property is set to reference the constructor's public prototype. So in the assignment statement, the x
property will be created on this new object. When called as a constructor, a function returns its this object by default, so there is no need for a separate return this;
statement.
To check that A has an x property:
console.log(A.x) // function () {
// //do something
// };
This is an uncommon use of new since the only way to reference the constructor is via A.constructor. It would be much more common to do:
var A = function () {
this.x = function () {
//do something
};
};
var a = new A();
Another way of achieving a similar result is to use an immediately invoked function expression:
var A = (function () {
this.x = function () {
//do something
};
}());
In this case, A
assigned the return value of calling the function on the right-hand side. Here again, since this is not set in the call, it will reference the global object and this.x
is effective window.x
. Since the function doesn't return anything, A
will have a value of undefined
.
These differences between the two approaches also manifest if you're serializing and de-serializing your Javascript objects to/from JSON. Methods defined on an object's prototype are not serialized when you serialize the object, which can be convenient when for example you want to serialize just the data portions of an object, but not it's methods:
var A = function () {
this.objectsOwnProperties = "are serialized";
};
A.prototype.prototypeProperties = "are NOT serialized";
var instance = new A();
console.log(instance.prototypeProperties); // "are NOT serialized"
console.log(JSON.stringify(instance));
// {"objectsOwnProperties":"are serialized"}
Related questions:
Sidenote: There may not be any significant memory savings between the two approaches, however using the prototype to share methods and properties will likely use less memory than each instance having its own copy.
JavaScript isn't a low-level language. It may not be very valuable to think of prototyping or other inheritance patterns as a way to explicitly change the way memory is allocated.
you can put
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
at the top of your car.js file for it to work, or you can do what Raynos said to do.
Run this
for (Method m : sex.class.getDeclaredMethods()) {
System.out.println(m);
}
you will see
public static test.Sex test.Sex.valueOf(java.lang.String)
public static test.Sex[] test.Sex.values()
These are all public methods that "sex" class has. They are not in the source code, javac.exe added them
Notes:
never use sex as a class name, it's difficult to read your code, we use Sex in Java
when facing a Java puzzle like this one, I recommend to use a bytecode decompiler tool (I use Andrey Loskutov's bytecode outline Eclispe plugin). This will show all what's inside a class
jQuery's .contents() method method allows us to search through the immediate children of the element in the DOM tree.
jQuery:
$('iframe').height( $('iframe').contents().outerHeight() );
Remember that the body of the page inner the iframe must have its height
CSS:
body {
height: auto;
overflow: auto
}
package main
import "fmt"
func main() {
var x float64 = 5.7
var y int = int(x)
fmt.Println(y) // outputs "5"
}
The right script would be like this:
select
p.spid, p.status,p.hostname,p.loginame,p.cpu,r.start_time, t.text
from sys.dm_exec_requests as r, sys.sysprocesses p
cross apply sys.dm_exec_sql_text(p.sql_handle) t
where p.status not in ('sleeping', 'background')
and r.session_id=p.spid
No Root and no ADB tools required method. Install MyAppSharer app from the play store.
You might need to install the grunt-cli, try this before doing a npm install:
sudo npm install -g grunt-cli
That fixes the grunt does not exit for me, you'll also need a valid grunt file.
Instead of .*
use .\{-}
.
%s/style=".\{-}"//g
Also, see :help non-greedy
You do it by setting a OnKeyListener
on your EditText
.
Here is a sample from my own code. I have an EditText
named addCourseText
, which will call the function addCourseFromTextBox
when either the enter key or the d-pad is clicked.
addCourseText = (EditText) findViewById(R.id.clEtAddCourse);
addCourseText.setOnKeyListener(new OnKeyListener()
{
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if (event.getAction() == KeyEvent.ACTION_DOWN)
{
switch (keyCode)
{
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_ENTER:
addCourseFromTextBox();
return true;
default:
break;
}
}
return false;
}
});
This seems to be the easiest to use:
<?php single_post_title(); ?>
Just perform a list comprehension to create your columns:
In [28]:
filter_col = [col for col in df if col.startswith('foo')]
filter_col
Out[28]:
['foo.aa', 'foo.bars', 'foo.fighters', 'foo.fox', 'foo.manchu']
In [29]:
df[filter_col]
Out[29]:
foo.aa foo.bars foo.fighters foo.fox foo.manchu
0 1.0 0 0 2 NA
1 2.1 0 1 4 0
2 NaN 0 NaN 1 0
3 4.7 0 0 0 0
4 5.6 0 0 0 0
5 6.8 1 0 5 0
Another method is to create a series from the columns and use the vectorised str method startswith
:
In [33]:
df[df.columns[pd.Series(df.columns).str.startswith('foo')]]
Out[33]:
foo.aa foo.bars foo.fighters foo.fox foo.manchu
0 1.0 0 0 2 NA
1 2.1 0 1 4 0
2 NaN 0 NaN 1 0
3 4.7 0 0 0 0
4 5.6 0 0 0 0
5 6.8 1 0 5 0
In order to achieve what you want you need to add the following to filter the values that don't meet your ==1
criteria:
In [36]:
df[df[df.columns[pd.Series(df.columns).str.startswith('foo')]]==1]
Out[36]:
bar.baz foo.aa foo.bars foo.fighters foo.fox foo.manchu nas.foo
0 NaN 1 NaN NaN NaN NaN NaN
1 NaN NaN NaN 1 NaN NaN NaN
2 NaN NaN NaN NaN 1 NaN NaN
3 NaN NaN NaN NaN NaN NaN NaN
4 NaN NaN NaN NaN NaN NaN NaN
5 NaN NaN 1 NaN NaN NaN NaN
EDIT
OK after seeing what you want the convoluted answer is this:
In [72]:
df.loc[df[df[df.columns[pd.Series(df.columns).str.startswith('foo')]] == 1].dropna(how='all', axis=0).index]
Out[72]:
bar.baz foo.aa foo.bars foo.fighters foo.fox foo.manchu nas.foo
0 5.0 1.0 0 0 2 NA NA
1 5.0 2.1 0 1 4 0 0
2 6.0 NaN 0 NaN 1 0 1
5 6.8 6.8 1 0 5 0 0
You can use map
:
List<String> names =
personList.stream()
.map(Person::getName)
.collect(Collectors.toList());
EDIT :
In order to combine the Lists of friend names, you need to use flatMap
:
List<String> friendNames =
personList.stream()
.flatMap(e->e.getFriends().stream())
.collect(Collectors.toList());
<link rel="shortcut icon" type="image/png" href="{% static 'favicon/sample.png' %}" />
Also run: python manage.py collectstatic
Aaron Bennet's solution is working perfectly for me, but i had to remove this line from his code --> white-space: -pre-wrap;
beacause it was giving an error, so the final working code is the following:
.wordwrap {
white-space: pre-wrap; /* CSS3 */
white-space: -moz-pre-wrap; /* Firefox */
white-space: -o-pre-wrap; /* Opera 7 */
word-wrap: break-word; /* IE */
}
thank you very much
String a = new String("foo");
String b = new String("foo");
System.out.println(a == b); // prints false
System.out.println(a.equals(b)); // prints true
Make sure you understand why. It's because the ==
comparison only compares references; the equals()
method does a character-by-character comparison of the contents.
When you call new for a
and b
, each one gets a new reference that points to the "foo"
in the string table. The references are different, but the content is the same.