Use helper like this (permissions names do not matter).
public class MyPermission {
private static final int PERMISSION_REQUEST_ALL = 127;
private MainActivity mMainActivity;
MyPermission(MainActivity mainActivity) {
mMainActivity = mainActivity;
}
public static boolean hasPermission(String permission, Context context) {
if (isNewPermissionModel()) {
return (ActivityCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED);
}
return true;
}
private static boolean hasPermissions(Context context, String... permissions) {
if (isNewPermissionModel() && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
private static boolean shouldShowRationale(Activity activity, String permission) {
return isNewPermissionModel() && ActivityCompat.shouldShowRequestPermissionRationale(activity, permission);
}
private static boolean isNewPermissionModel() {
return VERSION.SDK_INT > VERSION_CODES.LOLLIPOP_MR1;
}
/**
* check all permissions
*/
void checkAll() {
//check dangerous permissions, make request if need (Android will ask only for the ones it needs)
String[] PERMISSIONS = {
permission.READ_CALENDAR,
permission.ACCESS_COARSE_LOCATION
};
if (!hasPermissions(mMainActivity, PERMISSIONS)) {
ActivityCompat.requestPermissions(mMainActivity, PERMISSIONS, PERMISSION_REQUEST_ALL);
}
}
void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == PERMISSION_REQUEST_ALL) {
if (grantResults.length > 0) {
//for not granted
for (int i = 0; i < permissions.length; i++) {
if (permissions[i].equals(permission.READ_CALENDAR)) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
smartRequestPermissions(permission.READ_CALENDAR, R.string.permission_required_dialog_read_calendar);
}
} else if (permissions[i].equals(permission.ACCESS_COARSE_LOCATION)) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
smartRequestPermissions(permission.ACCESS_COARSE_LOCATION, R.string.permission_required_dialog_access_coarse_location);
}
}
}
}
}
}
private void smartRequestPermissions(final String permissionName, int permissionRequiredDialog) {
if (shouldShowRationale(mMainActivity, permissionName)) {// If the user turned down the permission request in the past and chose the Don't ask again option in the permission request system dialog, this method returns false.
//Show an explanation to the user with action
mMainActivity.mSnackProgressBarManager.show(
new SnackProgressBar(
SnackProgressBar.TYPE_ACTION, mMainActivity.getString(permissionRequiredDialog)
)
.setAction("OK", new OnActionClickListener() {
@Override
public void onActionClick() {
checkAll();
}
})
.setSwipeToDismiss(true).setAllowUserInput(true)
, MainActivity.SNACKBAR_WARNING_DURATION
);
} // else do nothing
}
}
It sounds like you're trying to link with your resulting object file with gcc
instead of g++
:
Note that programs using C++ object files must always be linked with g++, in order to supply the appropriate C++ libraries. Attempting to link a C++ object file with the C compiler gcc will cause "undefined reference" errors for C++ standard library functions:
$ g++ -Wall -c hello.cc
$ gcc hello.o (should use g++)
hello.o: In function `main':
hello.o(.text+0x1b): undefined reference to `std::cout'
.....
hello.o(.eh_frame+0x11):
undefined reference to `__gxx_personality_v0'
Source: An Introduction to GCC - for the GNU compilers gcc and g++
Per this announcement, Anaconda upgraded to Python 3.6 starting with version 4.3, so... you probably want the 4.2.0 package from the installer archive.
I would recommend you to use background-image instead of default list.
.listStyle {
list-style: none;
background: url(image_path.jpg) no-repeat left center;
padding-left: 30px;
width: 20px;
height: 20px;
}
Or, if you don't want to use background-image as bullet, there is an option to do it with pseudo element:
.liststyle{
list-style: none;
margin: 0;
padding: 0;
}
.liststyle:before {
content: "• ";
color: red; /* or whatever color you prefer */
font-size: 20px;/* or whatever the bullet size you prefer */
}
You can change location of legend using loc argument. https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.legend
import matplotlib.pyplot as plt
plt.subplot(211)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend above this subplot, expanding itself to
# fully use the given bounding box.
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
ncol=2, mode="expand", borderaxespad=0.)
plt.subplot(223)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend to the right of this smaller subplot.
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()
While the suggestions given already may work for some people, it does not work for my case. When performing the merge, users at rev 1443
who update to rev 1445
, still sync all files changed in 1444
even though they are equal to 1443
from the merge. I needed end users to not see the update at all.
If you want to completely hide the commit it is possible by creating a new branch at correct revision and then swapping the branches. The only thing is you need to remove and re add all locks.
copy -r 1443 file:///<your_branch> file:///<your_branch_at_correct_rev>
svn move file:///<your_branch> file:///<backup_branch>
svn move file:///<your_branch_at_correct_rev> file:///<your_branch>
This worked for me, perhaps it will be helpful to someone else out there =)
ProcessBuilder is very easy to use.
ProcessBuilder pb = new ProcessBuilder("python","Your python file",""+Command line arguments if any);
Process p = pb.start();
This should call python. Refer to the process approach here for full example!
https://bytes.com/topic/python/insights/949995-three-ways-run-python-programs-java
You do not "declare" arrays or anything else in python. You simply assign to a (new) variable. If you want a multidimensional array, simply add a new array as an array element.
arr = []
arr.append([])
arr[0].append('aa1')
arr[0].append('aa2')
or
arr = []
arr.append(['aa1', 'aa2'])
subinacl.exe command-line tool is probably the only viable and very easy to use from anything in this post. You cant use a GPO with non-system services and the other option is just way way way too complicated.
//Variables
char END_OF_FILE = '#';
char singleCharacter;
//Get a character from the input file
inFile.get(singleCharacter);
//Read the file until it reaches #
//When read pointer reads the # it will exit loop
//This requires that you have a # sign as last character in your text file
while (singleCharacter != END_OF_FILE)
{
cout << singleCharacter;
inFile.get(singleCharacter);
}
//If you need to store each character, declare a variable and store it
//in the while loop.
This worked for me. I made a function. Put this in your shell script:
sshcmd(){
ssh $1@$2 $3
}
sshcmd USER HOST COMMAND
If you have multiple machines that you want to do the same command on you would repeat that line with a semi colon. For example, if you have two machines you would do this:
sshcmd USER HOST COMMAND ; sshcmd USER HOST COMMAND
Replace USER with the user of the computer. Replace HOST with the name of the computer. Replace COMMAND with the command you want to do on the computer.
Hope this helps!
If you prefer to use a library, use ts-essentials.
import { Omit } from "ts-essentials";
type ComplexObject = {
simple: number;
nested: {
a: string;
array: [{ bar: number }];
};
};
type SimplifiedComplexObject = Omit<ComplexObject, "nested">;
// Result:
// {
// simple: number
// }
// if you want to Omit multiple properties just use union type:
type SimplifiedComplexObject = Omit<ComplexObject, "nested" | "simple">;
// Result:
// { } (empty type)
PS: You will find lots of other useful stuff there ;)
Another simple solution to digest an array elements once:
while(Auction.auctions.length){
// From first to last...
var auction = Auction.auctions.shift();
// From last to first...
var auction = Auction.auctions.pop();
// Do stuff with auction
}
For assemblies not in GAC, and which are referred in the build, sometimes this error also happens if the platform target does not match. So match the assembly platform type to the one where it is being used.
Neither is more correct, so take your pick. The empty return;
statement is provided to allow a return in a void
function from somewhere other than the end. No other reason I believe.
This will redirect the stderr (which is descriptor 2) to the file descriptor 1 which is the the stdout.
2>&1
Now when perform this you are redirecting the stdout to the file sample.s
myprogram > sample.s
Combining the two commands will result in redirecting both stderr and stdout to sample.s
myprogram > sample.s 2>&1
Redirect to /dev/null
if you want to completely silent your application.
myprogram >/dev/null 2>&1
Instead of remotely putting popper js from CDN you can directly install it in your angular project.
Try this.
npm install popper.js --save
This query installs an updated version of popper.js Don't mention any version there, it will work for you.
You can only match to constants in switch statements.
Example:
switch (variable1)
{
case 1: // A hard-coded value
// Code
break;
default:
// Code
break;
}
Successful!
switch (variable1)
{
case variable2:
// Code
break;
default:
// Code
break;
}
CS0150 A constant value is expected.
import warnings
warnings.warn("Warning...........Message")
See the python documentation: here
It's very simple.
If you want to have something like a glyphicon icon and then "Wish List",
<span class="glyphicon-heart"></span> @Html.ActionLink("Wish List (0)", "Index", "Home")
All cookies are client and server
There is no difference. A regular cookie can be set server side or client side. The 'classic' cookie will be sent back with each request. A cookie that is set by the server, will be sent to the client in a response. The server only sends the cookie when it is explicitly set or changed, while the client sends the cookie on each request.
But essentially it's the same cookie.
But, behavior can change
A cookie is basically a name=value
pair, but after the value can be a bunch of semi-colon separated attributes that affect the behavior of the cookie if it is so implemented by the client (or server).
Those attributes can be about lifetime, context and various security settings.
HTTP-only (is not server-only)
One of those attributes can be set by a server to indicate that it's an HTTP-only cookie. This means that the cookie is still sent back and forth, but it won't be available in JavaScript. Do note, though, that the cookie is still there! It's only a built in protection in the browser, but if somebody would use a ridiculously old browser like IE5, or some custom client, they can actually read the cookie!
So it seems like there are 'server cookies', but there are actually not. Those cookies are still sent to the client. On the client there is no way to prevent a cookie from being sent to the server.
Alternatives to achieve 'only-ness'
If you want to store a value only on the server, or only on the client, then you'd need some other kind of storage, like a file or database on the server, or Local Storage on the client.
Keep in mind that docker ps --size
may be an expensive command, taking more than a few minutes to complete. The same applies to container list API requests with size=1
. It's better not to run it too often.
Take a look at alternatives we compiled, including the du -hs
option for the docker persistent volume directory.
With the help of ProgrammersBlock posts I came up with this. My needs were slightly different. I needed to take a string and return it as a LocalDate object. I was handed code that was using the older Calendar and SimpleDateFormat. I wanted to make it a little more current. This is what I came up with.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
void ExampleFormatDate() {
LocalDate formattedDate = null; //Declare LocalDate variable to receive the formatted date.
DateTimeFormatter dateTimeFormatter; //Declare date formatter
String rawDate = "2000-01-01"; //Test string that holds a date to format and parse.
dateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE;
//formattedDate.parse(String string) wraps the String.format(String string, DateTimeFormatter format) method.
//First, the rawDate string is formatted according to DateTimeFormatter. Second, that formatted string is parsed into
//the LocalDate formattedDate object.
formattedDate = formattedDate.parse(String.format(rawDate, dateTimeFormatter));
}
Hopefully this will help someone, if anyone sees a better way of doing this task please add your input.
You don't tend to execute the make file itself, rather you execute make
, giving it the make file as an argument:
make -f pax.mk
If your make file is actually one of the standard names (like makefile
or Makefile
), you don't even need to specify it. It'll be picked up by default (if you have more than one of these standard names in your build directory, you better look up the make
man page to see which takes precedence).
.ico
, or is it just named ".ico"?The absolutely easiest way to have a favicon is to place an icon called "favicon.ico" in the root folder. That just works everywhere, no code needed at all.
If you must have it in a subdirectory, use:
<link rel="shortcut icon" href="/img/favicon.ico" />
Note the /
before img
to ensure it is anchored to the root folder.
In any system, the basic steps to correctly setup nbconvert to convert ipython notebooks to pdf/latex are
Installing nbconvert
pip install nbconvert
or conda install nbconvert
Installing pandoc
sudo apt-get install pandoc
for Ubuntu
or sudo yum install pandoc
for CentOS
for others visit pandoc-installation
Installing texlive
You can install recommended packages or full install. For Ubuntu
sudo apt-get install texlive texlive-xetex texlive-generic-extra texlive-generic-recommended
`
For others and to full install texlive follow the instructions given at tug as per your system and choice.
I downloaded tar.gz file from tug-texlive-download and followed instructions given at TeX Live - Quick install. Installation instructions in summary:
Clean up
rm -rf /usr/local/texlive/2019
rm -rf ~/.texlive2019
Run installer
unpack the zip file
cd /your/unpacked/directory
perl install-tl
Enter command: i
Setting path
sudo vi /etc/bash.bashrc
and insert
PATH=/usr/local/texlive/2019/bin/x86_64-linux:$PATH; export PATH
MANPATH=/usr/local/texlive/2019/texmf-dist/doc/man:$MANPATH; export MANPATH
INFOPATH=/usr/local/texlive/2019/texmf-dist/doc/info:$INFOPATH; export INFOPATH
Setting default papersize
tlmgr paper letter
The commands may differ as per your system but the basic steps remains the same.
The solutions above using classes with int constants lack type-safety. I.e. you could invent new values actually not defined in the class. Furthermore it is not possible for example to write a method taking one of these classes as input.
You would need to write
public void DoSomethingMeaningFull(int consumeValue) ...
However, there is a class based solution of the old days of Java, when there were no enums available. This provides an almost enum-like behaviour. The only caveat is that these constants cannot be used within a switch-statement.
public class MyBaseEnum
{
public static readonly MyBaseEnum A = new MyBaseEnum( 1 );
public static readonly MyBaseEnum B = new MyBaseEnum( 2 );
public static readonly MyBaseEnum C = new MyBaseEnum( 3 );
public int InternalValue { get; protected set; }
protected MyBaseEnum( int internalValue )
{
this.InternalValue = internalValue;
}
}
public class MyEnum : MyBaseEnum
{
public static readonly MyEnum D = new MyEnum( 4 );
public static readonly MyEnum E = new MyEnum( 5 );
protected MyEnum( int internalValue ) : base( internalValue )
{
// Nothing
}
}
[TestMethod]
public void EnumTest()
{
this.DoSomethingMeaningful( MyEnum.A );
}
private void DoSomethingMeaningful( MyBaseEnum enumValue )
{
// ...
if( enumValue == MyEnum.A ) { /* ... */ }
else if (enumValue == MyEnum.B) { /* ... */ }
// ...
}
if you have USB internet like me the emulator seems to dislike connection being turned on and off so you may need to restart the emulator
With angular 6 spread operator and concat not work. You can resolve it easy:
result.push(...data);
Swift Array performance revisited:
I wrote my own benchmark comparing Swift with C/Objective-C. My benchmark calculates prime numbers. It uses the array of previous prime numbers to look for prime factors in each new candidate, so it is quite fast. However, it does TONS of array reading, and less writing to arrays.
I originally did this benchmark against Swift 1.2. I decided to update the project and run it against Swift 2.0.
The project lets you select between using normal swift arrays and using Swift unsafe memory buffers using array semantics.
For C/Objective-C, you can either opt to use NSArrays, or C malloc'ed arrays.
The test results seem to be pretty similar with fastest, smallest code optimization ([-0s]) or fastest, aggressive ([-0fast]) optimization.
Swift 2.0 performance is still horrible with code optimization turned off, whereas C/Objective-C performance is only moderately slower.
The bottom line is that C malloc'd array-based calculations are the fastest, by a modest margin
Swift with unsafe buffers takes around 1.19X - 1.20X longer than C malloc'd arrays when using fastest, smallest code optimization. the difference seems slightly less with fast, aggressive optimization (Swift takes more like 1.18x to 1.16x longer than C.
If you use regular Swift arrays, the difference with C is slightly greater. (Swift takes ~1.22 to 1.23 longer.)
Regular Swift arrays are DRAMATICALLY
faster than they were in Swift 1.2/Xcode 6. Their performance is so close to Swift unsafe buffer based arrays that using unsafe memory buffers does not really seem worth the trouble any more, which is big.
BTW, Objective-C NSArray performance stinks. If you're going to use the native container objects in both languages, Swift is DRAMATICALLY faster.
You can check out my project on github at SwiftPerformanceBenchmark
It has a simple UI that makes collecting stats pretty easy.
It's interesting that sorting seems to be slightly faster in Swift than in C now, but that this prime number algorithm is still faster in Swift.
Here is a nice tutorial, which describes callbacks and the use-case well.
The concept of callbacks is to inform a class synchronous / asynchronous if some work in another class is done. Some call it the Hollywood principle: "Don't call us we call you".
Here's a example:
class A implements ICallback {
MyObject o;
B b = new B(this, someParameter);
@Override
public void callback(MyObject o){
this.o = o;
}
}
class B {
ICallback ic;
B(ICallback ic, someParameter){
this.ic = ic;
}
new Thread(new Runnable(){
public void run(){
// some calculation
ic.callback(myObject)
}
}).start();
}
interface ICallback{
public void callback(MyObject o);
}
Class A calls Class B to get some work done in a Thread. If the Thread finished the work, it will inform Class A over the callback and provide the results. So there is no need for polling or something. You will get the results as soon as they are available.
In Android Callbacks are used f.e. between Activities and Fragments. Because Fragments should be modular you can define a callback in the Fragment to call methods in the Activity.
This solved it for me on my Linux Mint local enviroment https://askubuntu.com/questions/350942/cannot-get-mcrypt-for-php5
I needed to make a symlink to my /etc/php5/conf.d/mcrypt.ini file in the following folders /etc/php5/apache2/conf.d/mcrypt.ini and /etc/php5/cli/conf.d/mcrypt.ini
Of course, this wasn't an option when the OP submitted the question, but ECMAScript 6 now also allows for constants by way of the "const" keyword:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const
You can see ECMAScript 6 adoption here.
I hope you will find this useful.
$query1="SELECT TIMESTAMPDIFF (YEAR, YOUR_DOB_COLUMN, CURDATE()) AS age FROM your_table WHERE id='$user_id'";
$res1=mysql_query($query1);
$row=mysql_fetch_array($res1);
echo $row['age'];
Fixing must override a super class method error is not difficult, You just need to change Java source version to 1.6 because from Java 1.6 @Override annotation can be used along with interface method. In order to change source version to 1.6 follow below steps :
I found an excellent utility that is configurable at https://github.com/acch/genfiles.
It fills the target file with random data, so there are no problems with sparse files, and for my purposes (testing compression algorithms) it gives a nice level of white noise.
You can use:
try:
# get your models
except ObjectDoesNotExist:
# do something
You need to update currentTime video element and then draw the frame in canvas. Don't init play() event on the video.
You can also use for ex. this plugin https://github.com/tstabla/stVideo
I accept @Rocket hazmat's answer as it lead me to the solution. It was indeed on the GAE server I needed to set the header. I had to set these
"Access-Control-Allow-Origin" -> "*"
"Access-Control-Allow-Headers" -> "Origin, X-Requested-With, Content-Type, Accept"
setting only "Access-Control-Allow-Origin"
gave error
Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers.
Also, if auth token needs to be sent, add this too
"Access-Control-Allow-Credentials" -> "true"
Also, at client, set withCredentials
this causes 2 requests to sent to the server, one with OPTIONS
. Auth cookie is not send with it, hence need to treat outside auth.
I have an histogram with the variable : group
Here how I calculate my median :
int[] group = new int[nbr];
// -- Fill the group with values---
// sum all data in median
int median = 0;
for (int i =0;i<nbr;i++) median += group[i];
// then divide by 2
median = median / 2;
// find 50% first part
for (int i = 0; i < nbr; i++)
{
median -= group[i];
if (median <= 0)
{
median = i;
break;
}
}
median is the group index of median
We can also use it for the guideline of the constraint layout.
Create integer.xml file and add into
<item name="guideline_button_top" type="integer" format="float">0.60</item>
Use from a layout.xml file
app:layout_constraintGuide_percent="@integer/guideline_button_top"
There are already many good answers to the part "what is uintptr_t data type". I will try to address the "what it can be used for?" part in this post.
Primarily for bitwise operations on pointers. Remember that in C++ one cannot perform bitwise operations on pointers. For reasons see Why can't you do bitwise operations on pointer in C, and is there a way around this?
Thus in order to do bitwise operations on pointers one would need to cast pointers to type unitpr_t and then perform bitwise operations.
Here is an example of a function that I just wrote to do bitwise exclusive or of 2 pointers to store in a XOR linked list so that we can traverse in both directions like a doubly linked list but without the penalty of storing 2 pointers in each node.
template <typename T>
T* xor_ptrs(T* t1, T* t2)
{
return reinterpret_cast<T*>(reinterpret_cast<uintptr_t>(t1)^reinterpret_cast<uintptr_t>(t2));
}
I ended up with this slightly different version:
var dirty = false;
window.onbeforeunload = function() {
return dirty ? "If you leave this page you will lose your unsaved changes." : null;
}
Elsewhere I set the dirty flag to true when the form gets dirtied (or I otherwise want to prevent navigating away). This allows me to easily control whether or not the user gets the Confirm Navigation prompt.
With the text in the selected answer you see redundant prompts:
It is a code style convention; it indicates that a method returns a boolean value.
The question mark is a valid character at the end of a method name.
i also think that link list is more better than arrays. because we do traversing in link list but not in arrays
As the title suggests that we want to adjust the size of the labels and not the tick marks I figured that I actually might add something to the question, you need to use the mtext() if you want to specify one of the label sizes, or you can just use par(cex.lab=2)
as a simple alternative. Here's a more advanced mtext() example:
set.seed(123)
foo <- data.frame(X = rnorm(10), Y = rnorm(10))
plot(Y ~ X, data=foo,
yaxt="n", ylab="",
xlab="Regular boring x",
pch=16,
col="darkblue")
axis(2,cex.axis=1.2)
mtext("Awesome Y variable", side=2, line=2.2, cex=2)
You may need to adjust the line=
option to get the optimal positioning of the text but apart from that it's really easy to use.
{{ Form::open(array('action' => "WelcomeController@log_in")) }}
...
{{ Form::close() }}
Use the index
attribute of DataFrame
. Note that I don't type all the rows in the example.
In [14]: df = data.groupby(['Country','Place'])['Value'].max()
In [15]: df.index
Out[15]:
MultiIndex
[Spain Manchester, UK London , US Mchigan , NewYork ]
In [16]: df.index[0]
Out[16]: ('Spain', 'Manchester')
In [17]: df.index[1]
Out[17]: ('UK', 'London')
You can also get the value by that index:
In [21]: for index in df.index:
print index, df[index]
....:
('Spain', 'Manchester') 512
('UK', 'London') 778
('US', 'Mchigan') 854
('US', 'NewYork') 562
Sorry for misunderstanding what you want, try followings:
In [52]: s=data.max()
In [53]: print '%s, %s, %s' % (s['Country'], s['Place'], s['Value'])
US, NewYork, 854
I tried the above answer - using page.html#ID_name
it gave me a 404 page doesn't exist error.
Then instead of using .html
, I simply put a slash /
before the #
and that worked fine. So my example on the sending page between the link tags looks like:
<a href= "http://my website.com/target-page/#El_Chorro">El Chorro</a>
Just use /
instead of .html
.
Try this one Open your projectname.csproj file its work for me.
<PackageReference Include="System.Data.SqlClient" Version="4.6.0" />
You need to add this Reference "ItemGroup" tag inside.
Another example:
Dim myPath As String = """" & Path.Combine(part1, part2) & """"
Good luck!
I use SharePrefrences:
package myapps.serializedemo;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.io.IOException;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Create the SharedPreferences
SharedPreferences sharedPreferences = this.getSharedPreferences("myapps.serilizerdemo", Context.MODE_PRIVATE);
ArrayList<String> friends = new ArrayList<>();
friends.add("Jack");
friends.add("Joe");
try {
//Write / Serialize
sharedPreferences.edit().putString("friends",
ObjectSerializer.serialize(friends)).apply();
} catch (IOException e) {
e.printStackTrace();
}
//READ BACK
ArrayList<String> newFriends = new ArrayList<>();
try {
newFriends = (ArrayList<String>) ObjectSerializer.deserialize(
sharedPreferences.getString("friends", ObjectSerializer.serialize(new ArrayList<String>())));
} catch (IOException e) {
e.printStackTrace();
}
Log.i("***NewFriends", newFriends.toString());
}
}
Google Drive folders can be embedded and displayed in list
and grid
views:
<iframe src="https://drive.google.com/embeddedfolderview?id=FOLDER-ID#list" style="width:100%; height:600px; border:0;"></iframe>
<iframe src="https://drive.google.com/embeddedfolderview?id=FOLDER-ID#grid" style="width:100%; height:600px; border:0;"></iframe>
Q: What is a folder ID (FOLDER-ID) and how can I get it?
A: Go to Google Drive >> open the folder >> look at its URL in the address bar of your browser. For example:
Folder URL: https://drive.google.com/drive/folders/0B1iqp0kGPjWsNDg5NWFlZjEtN2IwZC00NmZiLWE3MjktYTE2ZjZjNTZiMDY2
Folder ID:
0B1iqp0kGPjWsNDg5NWFlZjEtN2IwZC00NmZiLWE3MjktYTE2ZjZjNTZiMDY2
This technique works best for folders with public access. Folders that are shared only with certain Google accounts will cause trouble when you embed them this way. At the time of this edit, a message "You need permission" appears, with some buttons to help you "Request access" or "Switch accounts" (or possibly sign-in to a Google account). The Javascript in these buttons doesn't work properly inside an IFRAME
in Chrome.
Read more at https://productforums.google.com/forum/#!msg/drive/GpVgCobPL2Y/_Xt7sMc1WzoJ
Is there a more elegant way to write this code?
from collections import defaultdict
dates_dict = defaultdict(list)
for key, date in cur:
dates_dict[key].append(date)
use
window.location.origin
and for: "http://aaa.bbb.ccc.ddd.com/sadf.aspx?blah"
you will get: http://aaa.bbb.ccc.ddd.com/
Let us say we have to sort a list of objects in ascending order based on a particular property, in this example lets say we have to sort based on the "name" property, then below is the required code :
var list_Objects = [{"name"="Bob"},{"name"="Jay"},{"name"="Abhi"}];
Console.log(list_Objects); //[{"name"="Bob"},{"name"="Jay"},{"name"="Abhi"}]
list_Objects.sort(function(a,b){
return a["name"].localeCompare(b["name"]);
});
Console.log(list_Objects); //[{"name"="Abhi"},{"name"="Bob"},{"name"="Jay"}]
var obj=[
{
id : "001",
name : "apple",
category : "fruit",
color : "red"
},
{
id : "002",
name : "melon",
category : "fruit",
color : "green"
},
{
id : "003",
name : "banana",
category : "fruit",
color : "yellow"
}
]
var tbl=$("<table/>").attr("id","mytable");
$("#div1").append(tbl);
for(var i=0;i<obj.length;i++)
{
var tr="<tr>";
var td1="<td>"+obj[i]["id"]+"</td>";
var td2="<td>"+obj[i]["name"]+"</td>";
var td3="<td>"+obj[i]["color"]+"</td></tr>";
$("#mytable").append(tr+td1+td2+td3);
}
The server_name
docs directive is used to identify virtual hosts, they're not used to set the binding.
netstat
tells you that nginx listens on 0.0.0.0:80
which means that it will accept connections from any IP.
If you want to change the IP nginx binds on, you have to change the listen
docs rule.
So, if you want to set nginx to bind to localhost
, you'd change that to:
listen 127.0.0.1:80;
In this way, requests that are not coming from localhost are discarded (they don't even hit nginx).
No. HTML explicitly forbids nested forms.
From the HTML 5 draft:
Content model: Flow content, but with no form element descendants.
From the HTML 4.01 Recommendation:
<!ELEMENT FORM - - (%block;|SCRIPT)+ -(FORM) -- interactive form -->
(Note the -(FORM) section).
If you really want to use a sed
command without installing a new Python module, you could simply do the following:
import subprocess
subprocess.call("sed command")
All can be defined as in f:ajax
attiributes.
i.e.
<p:selectOneMenu id="employees" value="#{mymb.employeesList}" required="true">
<f:selectItems value="#{mymb.employeesList}" var="emp" itemLabel="#{emp.employeeName}" />
<f:ajax event="valueChange" listener="#{mymb.handleChange}" execute="@this" render="@all" />
</p:selectOneMenu>
event: it can be normal DOM Events like click
, or valueChange
execute: This is a space separated list of client ids of components that will participate in the "execute" portion of the Request Processing Lifecycle.
render: The clientIds of components that will participate in the "render" portion of the Request Processing Lifecycle. After action done, you can define which components should be refresh. Id, IdList or these keywords can be added: @this
, @form
, @all
, @none
.
You can reache the whole attribute list by following link: http://docs.oracle.com/javaee/6/javaserverfaces/2.1/docs/vdldocs/facelets/f/ajax.html
Hello sorry for the delay! Here is the best and the most efficiency answer that you are looking for:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MyPatternReplace {
public String replaceWithPattern(String str,String replace){
Pattern ptn = Pattern.compile("\\s+");
Matcher mtch = ptn.matcher(str);
return mtch.replaceAll(replace);
}
public static void main(String a[]){
String str = "My name is kingkon. ";
MyPatternReplace mpr = new MyPatternReplace();
System.out.println(mpr.replaceWithPattern(str, " "));
}
So your output of this example will be: My name is kingkon.
However this method will remove also the "\n" that your string may has. So if you do not want that just use this simple method:
while (str.contains(" ")){ //2 spaces
str = str.replace(" ", " "); //(2 spaces, 1 space)
}
And if you want to strip the leading and trailing spaces too just add:
str = str.trim();
In case you don't want to use any graphical interface for vim and you prefer to just stick with terminal emulator there may be a much simpler approach to this problem. Instead of using yank or anything like this, first take a look at documentation of terminal you use. I've been struggling with the same issue (trying to use +clipboard and xclip and so on) and in the end it turned out that in my terminal emulator it's enough to just press shift and select any text you want to copy. That's it. Quite simple and no need for messing with configuration. (I use urxvt by the way).
For me I was Building the Ionic using "ionic build android" command and I was getting the same problem! The solution was simply
You need to change the default layout type of top level QWidget object from Break layout type to other layout types (Vertical Layout, Horizontal Layout, Grid Layout, Form Layout). For example:
To something like this:
1.You can make overload functions.
SomeF(strin s){}
SomeF(string s, string s2){}
SomeF(string s1, string s2, string s3){}
More info: http://csharpindepth.com/Articles/General/Overloading.aspx
2.or you may create one function with params
SomeF( params string[] paramArray){}
SomeF("aa","bb", "cc", "dd", "ff"); // pass as many as you like
More info: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/params
3.or you can use simple array
Main(string[] args){}
A quick trick to use for me is using the find duplicates query SQL and changing 1 to 0 in Having expression. Like this:
SELECT COUNT([UniqueField]) AS DistinctCNT FROM
(
SELECT First([FieldName]) AS [UniqueField]
FROM TableName
GROUP BY [FieldName]
HAVING (((Count([FieldName]))>0))
);
Hope this helps, not the best way I am sure, and Access should have had this built in.
alternative to stdbuf is awk '{print} END {fflush()}'
I wish there were a bash builtin to do this.
Normally it shouldn't be necessary, but with older versions there might be bash synchronization bugs on file descriptors.
create a logfile in php, to do it you need to pass data on function and it will create log file for you.
function wh_log($log_msg)
{
$log_filename = "log";
if (!file_exists($log_filename))
{
// create directory/folder uploads.
mkdir($log_filename, 0777, true);
}
$log_file_data = $log_filename.'/log_' . date('d-M-Y') . '.log';
// if you don't add `FILE_APPEND`, the file will be erased each time you add a log
file_put_contents($log_file_data, $log_msg . "\n", FILE_APPEND);
}
// call to function
wh_log("this is my log message");
There is also a pure Python recursive option:
def checkEqual(lst):
if len(lst)==2 :
return lst[0]==lst[1]
else:
return lst[0]==lst[1] and checkEqual(lst[1:])
However for some reason it is in some cases two orders of magnitude slower than other options. Coming from C language mentality, I expected this to be faster, but it is not!
The other disadvantage is that there is recursion limit in Python which needs to be adjusted in this case. For example using this.
Basing on lovely visual answer on Maps by @shevchyk here is my take:
+------------------------------------------------------------------------------+
¦ Property ¦ HashSet ¦ TreeSet ¦ LinkedHashSet ¦
¦--------------+---------------------+-------------------+---------------------¦
¦ ¦ no guarantee order ¦ sorted according ¦ ¦
¦ Order ¦ will remain constant¦ to the natural ¦ insertion-order ¦
¦ ¦ over time ¦ ordering ¦ ¦
¦--------------+---------------------+-------------------+---------------------¦
¦ Add/remove ¦ O(1) ¦ O(log(n)) ¦ O(1) ¦
¦--------------+---------------------+-------------------+---------------------¦
¦ ¦ ¦ NavigableSet ¦ ¦
¦ Interfaces ¦ Set ¦ Set ¦ Set ¦
¦ ¦ ¦ SortedSet ¦ ¦
¦--------------+---------------------+-------------------+---------------------¦
¦ ¦ ¦ not allowed ¦ ¦
¦ Null values ¦ allowed ¦ 1st element only ¦ allowed ¦
¦ ¦ ¦ in Java 7 ¦ ¦
¦--------------+---------------------------------------------------------------¦
¦ ¦ Fail-fast behavior of an iterator cannot be guaranteed ¦
¦ Fail-fast ¦ impossible to make any hard guarantees in the presence of ¦
¦ behavior ¦ unsynchronized concurrent modification ¦
¦--------------+---------------------------------------------------------------¦
¦ Is ¦ ¦
¦ synchronized ¦ implementation is not synchronized ¦
+------------------------------------------------------------------------------+
I haven't seen this mentioned yet but if you are still having issues after recreating your provisioning profiles, deleting the existing ones you have in your Provision Profiles folder, checking for dupes in your Keychain, etc (all other answers ITT), open your Target > Build Settings > Code Signing and make sure everything looks consistent in there. For example, I had changed the Code Signing Identify for Debug to a Distribution identity, which obviously wouldn't work as the Development Provisioning Profile doesn't have the Distribution certificate and was causing the error in the first place.
String interpolation to the rescue.
let imageUrl = 'imageurl.png';
$('myOjbect').css('background-image', `url(${imageUrl})`);
Just "git clean -f -d" worked for me!
Usually for jumping people use Rigidbody2D.AddForce
with Forcemode.Impulse
. It may seem like your object is pushed once in Y axis and it will fall down automatically due to gravity.
Example:
rigidbody2D.AddForce(new Vector2(0, 10), ForceMode2D.Impulse);
I use this function to indent my output (for example to print a tree structure). The indent
is the number of spaces before the string.
void print_with_indent(int indent, char * string)
{
printf("%*s%s", indent, "", string);
}
For multiple classes
in the same js
file, extending Component
from @wordpress/element
, you can do that :
// classes.js
import { Component } from '@wordpress/element';
const Class1 = class extends Component {
}
const Class2 = class extends Component {
}
export { Class1, Class2 }
And import them in another js
file :
import { Class1, Class2 } from './classes';
On the selector .nav-tabs > li > a:hover
add !important
to the background-color
.
.nav-tabs{_x000D_
background-color:#161616;_x000D_
}_x000D_
.tab-content{_x000D_
background-color:#303136;_x000D_
color:#fff;_x000D_
padding:5px_x000D_
}_x000D_
.nav-tabs > li > a{_x000D_
border: medium none;_x000D_
}_x000D_
.nav-tabs > li > a:hover{_x000D_
background-color: #303136 !important;_x000D_
border: medium none;_x000D_
border-radius: 0;_x000D_
color:#fff;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>_x000D_
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<ul class="nav nav-tabs" id="myTab">_x000D_
<li class="active"><a data-toggle="tab" href="#search">SEARCH</a></li>_x000D_
<li><a data-toggle="tab" href="#advanced">ADVANCED</a></li>_x000D_
</ul>_x000D_
<div class="tab-content">_x000D_
<div id="search" class="tab-pane fade in active">_x000D_
Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel,_x000D_
butcher voluptate nisi qui._x000D_
</div>_x000D_
<div id="advanced" class="tab-pane fade">_x000D_
Vestibulum nec erat eu nulla rhoncus fringilla ut non neque. Vivamus nibh urna._x000D_
</div>_x000D_
</div>
_x000D_
You have mixed indentation formatting (spaces and tabs)
Go to Settings -> Preferences -> Tab Settings -> Replace by spaces
Select everything CTRL+A
Click TAB once, to add an indentation everywhere
Run SHIFT + TAB to remove the extra indentation, it will replace all TAB characters to 4 spaces.
Jason,
This is how it works.
Localnamespace - java:comp/env is a local name space used by the application. The name that you use in it jdbc/db is just an alias. It does not refer to a physical resource.
During deployment this alias should be mapped to a physical resource (in your case a data source) that is defined on the WAS/WPS run time.
This is actually stored in ejb-bnd.xmi files. In the latest versions the XMIs are replaced with XML files. These files are referred to as the Binding files.
HTH Manglu
//Hope This will help you..
DataTable table = new DataTable();
//DataRow[] rowArray = dataTable.Select();
table = dataTable.Clone();
for (int i = dataTable.Rows.Count - 1; i >= 0; i--)
{
table.ImportRow(dataTable.Rows[i]);
}
return table;
Just try this.
<asp:TextBox ID="tb" onkeypress="javascript:return false;" width="50px" runat="server"></asp:TextBox>
This won't allow any characters to be entered inside the TextBox.
Uncaught SyntaxError: Unexpected token }
Chrome gaved me the error for this sample code:
<div class="file-square" onclick="window.location = " ?dir=zzz">
<div class="square-icon"></div>
<div class="square-text">zzz</div>
</div>
and solved it fixing the onclick to be like
... onclick="window.location = '?dir=zzz'" ...
But the error has nothing to do with the problem..
I was getting the same error message when I tried to change the domain for iframe.src.
For me, the answer was to change the iframe.src to a url on the same domain, but which was actually an html re-direct page to the desired domain. The other domain then showed up in my iframe without any errors.
Worked like a charm.:)
The following could be used if you know that your object doesn't have a concat method.
var arr = [];_x000D_
if (typeof arr.concat === 'function') {_x000D_
console.log("It's an array");_x000D_
}
_x000D_
You do not need to use substring at all since your format
doesn't hold that info.
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String fechaStr = "2013-10-10 10:49:29.10000";
Date fechaNueva = format.parse(fechaStr);
System.out.println(format.format(fechaNueva)); // Prints 2013-10-10 10:49:29
As this is specifically tagged for jQuery -
$("#myElement")[0].getBoundingClientRect();
or
$("#myElement").get(0).getBoundingClientRect();
(These are functionally identical, in some older browsers .get()
was slightly faster)
Note that if you try to get the values via jQuery calls then it will not take into account any css transform values, which can give unexpected results...
Note 2: In jQuery 3.0 it has changed to using the proper getBoundingClientRect()
calls for its own dimension calls (see the jQuery Core 3.0 Upgrade Guide) - which means that the other jQuery answers will finally always be correct - but only when using the new jQuery version - hence why it's called a breaking change...
Make sure that you handle all the errors by sending a return value.
`if err!=nil{
return nil, err
}`
Assuming that you're talking about desktop and not web applications:
When you add settings to a project, VS creates a file named app.config
in your project directory and stores the settings in that file. It also builds the Settings.cs
file that provides the static accessors to the individual settings.
At compile time, VS will (by default; you can change this) copy the app.config
to the build directory, changing its name to match the executable (e.g. if your executable is named foo.exe
, the file will be named foo.exe.config
), which is the name the .NET configuration manager looks for when it retrieves settings at runtime.
If you change a setting through the VS settings editor, it will update both app.config
and Settings.cs
. (If you look at the property accessors in the generated code in Settings.cs
, you'll see that they're marked with an attribute containing the default value of the setting that's in your app.config
file.) If you change a setting by editing the app.config
file directly, Settings.cs
won't be updated, but the new value will still be used by your program when you run it, because app.config
gets copied to foo.exe.config
at compile time. If you turn this off (by setting the file's properties), you can change a setting by directly editing the foo.exe.config
file in the build directory.
Then there are user-scoped settings.
Application-scope settings are read-only. Your program can modify and save user-scope settings, thus allowing each user to have his/her own settings. These settings aren't stored in the foo.exe.config
file (since under Vista, at least, programs can't write to any subdirectory of Program Files
without elevation); they're stored in a configuration file in the user's application data directory.
The path to that file is %appdata%\%publisher_name%\%program_name%\%version%\user.config
, e.g. C:\Users\My Name\AppData\Local\My_Company\My_Program.exe\1.0.0\user.config
. Note that if you've given your program a strong name, the strong name will be appended to the program name in this path.
DROP TABLE TEST; -- COMMENT THIS OUT FOR THE FIRST RUN
CREATE TABLE TEST
(
COL_NAME,
TEST_NAME
) AS
(
SELECT NULL, 'ACTUAL NULL' FROM DUAL
UNION ALL
SELECT '', 'NULL STRING' FROM DUAL
UNION ALL
SELECT ' ', 'SINGLE SPACE' FROM DUAL
UNION ALL
SELECT ' ', 'DOUBLE SPACE' FROM DUAL
UNION ALL
SELECT ' ', 'TEN SPACES' FROM DUAL
UNION ALL
SELECT 'NONSPACE', 'NONSPACES' FROM DUAL
)
;
SELECT LENGTH(COL_NAME) NUM_OF_SPACES, TEST_NAME
FROM TEST
WHERE LENGTH(COL_NAME) > 0 -- THERE IS SOMETHING IN THE FIELD
AND TRIM(COL_NAME) IS NULL; -- WHICH EQUATES TO NULL
table TEST dropped.
table TEST created.
NUM_OF_SPACES TEST_NAME
1 SINGLE SPACE 2 DOUBLE SPACE 10 TEN SPACES
Once you have identified the columns that contain blanks, wrap that query in a count. If you actually need to identify the fields for some kind of update, consider selecting the ROWID as well.
I needed to capture both stdout and stderr and have it timeout if the process didn't exit when expected. I came up with this:
Process process = new Process();
StringBuilder outputStringBuilder = new StringBuilder();
try
{
process.StartInfo.FileName = exeFileName;
process.StartInfo.WorkingDirectory = args.ExeDirectory;
process.StartInfo.Arguments = args;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
process.EnableRaisingEvents = false;
process.OutputDataReceived += (sender, eventArgs) => outputStringBuilder.AppendLine(eventArgs.Data);
process.ErrorDataReceived += (sender, eventArgs) => outputStringBuilder.AppendLine(eventArgs.Data);
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
var processExited = process.WaitForExit(PROCESS_TIMEOUT);
if (processExited == false) // we timed out...
{
process.Kill();
throw new Exception("ERROR: Process took too long to finish");
}
else if (process.ExitCode != 0)
{
var output = outputStringBuilder.ToString();
var prefixMessage = "";
throw new Exception("Process exited with non-zero exit code of: " + process.ExitCode + Environment.NewLine +
"Output from process: " + outputStringBuilder.ToString());
}
}
finally
{
process.Close();
}
I am piping the stdout and stderr into the same string, but you could keep it separate if needed. It uses events, so it should handle them as they come (I believe). I have run this successfully, and will be volume testing it soon.
A very more efficient way to do this in php:
<form action="#" method="post">
<select name="Color">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
<option value="Pink">Pink</option>
<option value="Yellow">Yellow</option>
</select>
<input type="submit" name="submit" value="Get Selected Values" />
</form>
<?php
if(isset($_POST['submit'])){
$selected_val = $_POST['Color']; // Storing Selected Value In Variable
echo "You have selected :" .$selected_val; // Displaying Selected Value
}
?>
and for check boxes multiple choice:
<form action="#" method="post">
<select name="Color[]" multiple> // Initializing Name With An Array
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
<option value="Pink">Pink</option>
<option value="Yellow">Yellow</option>
</select>
<input type="submit" name="submit" value="Get Selected Values" />
</form>
<?php
if(isset($_POST['submit'])){
// As output of $_POST['Color'] is an array we have to use foreach Loop to display individual value
foreach ($_POST['Color'] as $select)
{
echo "You have selected :" .$select; // Displaying Selected Value
}
?>
XmlDocument doc = new XmlDocument();
doc.LoadXml(str);
Where str
is your XML string. See the MSDN article for more info.
Such steps helped me:
I jealous the strtotime() in php, but I do mine in javascript using moment. Not as sweet as that from php, but does the trick neatly too.
// first day of the month
var firstDayThisMonth = moment(firstDayThisMonth).startOf('month').toDate();
Go back and forth using the subtract()
and add()
with the endOf()
and startOf()
:
// last day of previous month
var yesterMonthLastDay = moment(yesterMonthLastDay).subtract(1,'months').endOf('month').toDate();
An upside-down circumflex is called a caron, or a hácek.
It has an HTML entity in the TADS Latin-2 extension to HTML: ˇ
and looks like this: ˇ which unfortunately doesn't display in the same size/proportion as the ^ caret.
Or you can use the unicode U+30C
.
The BlackBerry browser and Safari for iOS (iPhone/iPod/iPad) automatically detect phone numbers and email addresses and convert them to links. If you don’t want this feature, you should use the following meta tags.
For Safari:
<meta name="format-detection" content="telephone=no">
For BlackBerry:
<meta http-equiv="x-rim-auto-match" content="none">
Source: mobilexweb.com
Similar to mangledorf's solution, but shorter and layman friendly
:%s/.*/\L&/g
I had a "fatal : bad revision" with Idea / Webstorm because I had a git directory inside another, without using properly submodules or subtrees.
I checked for .git
dirs with :
find ./ -name '.git' -print
Throwing in an option since I didn't see this exact scenario covered. If you don't want c
updated when a
or b
update, then an ES6 IIFE works well.
var foo = ((a,b) => ({
a,
b,
c: a + b
}))(a,b);
For my needs, I have an object that relates to an array which will end up being used in a loop, so I only want to calculate some common setup once, so this is what I have:
let processingState = ((indexOfSelectedTier) => ({
selectedTier,
indexOfSelectedTier,
hasUpperTierSelection: tiers.slice(0,indexOfSelectedTier)
.some(t => pendingSelectedFiltersState[t.name]),
}))(tiers.indexOf(selectedTier));
Since I need to set a property for indexOfSelectedTier
and I need to use that value when setting the hasUpperTierSelection
property, I calculate that value first and pass it in as a param to the IIFE
I was really looking for a way to fetch the connection status of a device, not listen to connection events. Here's what worked for me:
BluetoothManager bm = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
List<BluetoothDevice> devices = bm.getConnectedDevices(BluetoothGatt.GATT);
int status = -1;
for (BluetoothDevice device : devices) {
status = bm.getConnectionState(device, BLuetoothGatt.GATT);
// compare status to:
// BluetoothProfile.STATE_CONNECTED
// BluetoothProfile.STATE_CONNECTING
// BluetoothProfile.STATE_DISCONNECTED
// BluetoothProfile.STATE_DISCONNECTING
}
In IDEA 2019.3.3 community on mac ( catalina)
IntelliJ IDEA => preferences
Build,Execution,Deployment=>Compiler=>Annotation Processors:
Check Enable annotation Processing
I've just faced the same problem just after installed Oracle XE 11.2. After reading and consulting a DBA friend, I ran the following command:
C:\>tnsping xe
TNS Ping Utility for 64-bit Windows: Version 11.2.0.2.0 - Production on 11-ENE-2017 14:27:44
Copyright (c) 1997, 2014, Oracle. All rights reserved.
Used parameter files:
C:\oraclexe\app\oracle\product\11.2.0\server\network\admin\sqlnet.ora
Used TNSNAMES adapter to resolve the alias
Attempting to contact (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = myLaptop)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = XE)))
OK (30 msec)
C:\>
As you can see, it takes long time to resolve, so I added an entry to hosts file as follows:
127.0.0.1 localhost
Once done, ran again the same command:
C:\>tnsping xe
TNS Ping Utility for 64-bit Windows: Version 11.2.0.2.0 - Production on 11-ENE-2
017 14:40:29
Copyright (c) 1997, 2014, Oracle. All rights reserved.
Used parameter files:
C:\oraclexe\app\oracle\product\11.2.0\server\network\admin\sqlnet.ora
Used TNSNAMES adapter to resolve the alias
Attempting to contact (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = myLaptop)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SER
VICE_NAME = XE)))
OK (30 msec)
C:\>
As time response radically decreases, I tried my connection on sqldeveloper successfully.
Just a little expansion to Nathan's Linq Expression solution. Use multi generic param so that the property doesn't limited to string.
void GetString<TClass, TProperty>(string input, TClass outObj, Expression<Func<TClass, TProperty>> outExpr)
{
if (!string.IsNullOrEmpty(input))
{
var expr = (MemberExpression) outExpr.Body;
var prop = (PropertyInfo) expr.Member;
if (!prop.GetValue(outObj).Equals(input))
{
prop.SetValue(outObj, input, null);
}
}
}
If you're working on an Android project, make sure you aren't calling any static methods on any Android classes. I'm only using JUnit + Mockito, so maybe some other frameworks might help you avoid the problem altogether, I'm not sure.
My problem was calling Uri.parse(uriString)
as part of a static initializer for a unit test. The Uri class is an Android API, which is why the unit test build couldn't find it. I changed this value to null
instead and everything went back to normal.
You could try running a script as follows
var WindowStyle_Hidden = 0
var objShell = WScript.CreateObject("WScript.Shell")
var result = objShell.Run("cmd.exe /c setrbvars.bat", WindowStyle_Hidden)
save the file as filename.js
There is an ipython nbextension that constructs a table of contents for a notebook. It seems to only provide navigation, not section folding.
RandomStringUtils has a provision to create a string from given input size. Cant comment on the speed, but its a one liner.
RandomStringUtils.random(5,"\t");
creates an output
\t\t\t\t\t
preferable if you dont want to see \0 in your code.
There is no such thing as a byte or short literal. You need to cast to short using (short)100
String fname = "Sam\u0025";
PreparedStatement ps= conn.prepareStatement("SELECT * FROM Users WHERE User_FirstName LIKE ? ");
ps.setString(1, fname);
You are actually getting the correct value out.
The way your x86
(compatible) processor stores data like this, is in Little Endian order, meaning that, the MSB is last in your output.
So, given your output:
10101010
the last two hex values 10
are the Most Significant Byte (2 hex digits = 1 byte = 8 bits
(for (possibly unnecessary) clarification).
So, by reversing the memory storage order of the bytes, your value is actually: 01010101
.
Hope that clears it up!
If the file that you want to open is in the same folder as your batch(.bat) file then you can simply try:
start filename.filetype
example: start image.png
Okay. You only need to use 'flatMap' when you're facing nested Optionals. Here's the example.
public class Person {
private Optional<Car> optionalCar;
public Optional<Car> getOptionalCar() {
return optionalCar;
}
}
public class Car {
private Optional<Insurance> optionalInsurance;
public Optional<Insurance> getOptionalInsurance() {
return optionalInsurance;
}
}
public class Insurance {
private String name;
public String getName() {
return name;
}
}
public class Test {
// map cannot deal with nested Optionals
public Optional<String> getCarInsuranceName(Person person) {
return person.getOptionalCar()
.map(Car::getOptionalInsurance) // ? leads to a Optional<Optional<Insurance>
.map(Insurance::getName); // ?
}
}
Like Stream, Optional#map will return a value wrapped by a Optional. That's why we get a nested Optional -- Optional<Optional<Insurance>
. And at ?, we want to map it as an Insurance instance, that's how the tragedy happened.
The root is nested Optionals. If we can get the core value regardless the shells, we'll get it done. That's what flatMap does.
public Optional<String> getCarInsuranceName(Person person) {
return person.getOptionalCar()
.flatMap(Car::getOptionalInsurance)
.map(Insurance::getName);
}
In the end, I stronly recommed the Java 8 In Action to you if you'd like to study Java8 Systematicly.
OK.I just found out that if we want the FlatList to know the data change outside of the data prop,we need set it to extraData, so I do it like this now:
<FlatList data={...} extraData={this.state} .../>
refer to : https://facebook.github.io/react-native/docs/flatlist#extradata
You might also consider Microsoft Enterprise Library Logging Block. It comes with nice designer.
Run following command in the Terminal to connect to the DBMS (you need root access):
sudo mysql -u root -p;
run update password of the target user (for my example username is mousavi
and it's password must be 123456
):
UPDATE mysql.user SET authentication_string=PASSWORD('123456') WHERE user='mousavi';
at this point you need to do a flush to apply changes:
FLUSH PRIVILEGES;
Done! You did it without any stop or restart mysql service.
I think this is the most reliable way to get the desktop path which isn't always the same as the username.
MsgBox CreateObject("WScript.Shell").specialfolders("Desktop")
Try format
function:
> xx = 100000000000
> xx
[1] 1e+11
> format(xx, scientific=F)
[1] "100000000000"
[]
is replaced by %5B%5D
at URL encoding time.
As someone who has worked with ASP.NET API for about 3 years, I'd recommend returning an HttpResponseMessage instead. Don't use the ActionResult or IEnumerable!
ActionResult is bad because as you've discovered.
Return IEnumerable<> is bad because you may want to extend it later and add some headers, etc.
Using JsonResult is bad because you should allow your service to be extendable and support other response formats as well just in case in the future; if you seriously want to limit it you can do so using Action Attributes, not in the action body.
public HttpResponseMessage GetAllNotificationSettings()
{
var result = new List<ListItems>();
// Filling the list with data here...
// Then I return the list
return Request.CreateResponse(HttpStatusCode.OK, result);
}
In my tests, I usually use the below helper method to extract my objects from the HttpResponseMessage:
public class ResponseResultExtractor
{
public T Extract<T>(HttpResponseMessage response)
{
return response.Content.ReadAsAsync<T>().Result;
}
}
var actual = ResponseResultExtractor.Extract<List<ListItems>>(response);
In this way, you've achieved the below:
Look at this: http://www.asp.net/web-api/overview/formats-and-model-binding/content-negotiation
After reading all the solutions posted here. This is how I solved it:
// How to embedded a "Text file" inside of a C# project
// and read it as a resource from c# code:
//
// (1) Add Text File to Project. example: 'myfile.txt'
//
// (2) Change Text File Properties:
// Build-action: EmbeddedResource
// Logical-name: myfile.txt
// (note only 1 dot permitted in filename)
//
// (3) from c# get the string for the entire embedded file as follows:
//
// string myfile = GetEmbeddedResourceFile("myfile.txt");
public static string GetEmbeddedResourceFile(string filename) {
var a = System.Reflection.Assembly.GetExecutingAssembly();
using (var s = a.GetManifestResourceStream(filename))
using (var r = new System.IO.StreamReader(s))
{
string result = r.ReadToEnd();
return result;
}
return "";
}
I had this issue and I fixed it using the following steps You need to completely uninstall python3-p using:
sudo apt-get --purge autoremove python3-pip
Then resintall the package with:
sudo apt install python3-pip
To confirm that everything works, run:
pip3 -V
After this you can now use pip3 to manage any python package of your interest. Eg
pip3 install NumPy
Note that if you rely on sleep taking exactly 50 ms, you won't get that. It will just be about it.
Nowadays you should use importlib.
The docs actually provide a recipe for that, and it goes like:
import sys
import importlib.util
file_path = 'pluginX.py'
module_name = 'pluginX'
spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
# check if it's all there..
def bla(mod):
print(dir(mod))
bla(module)
This way you can access the members (e.g, a function "hello
") from your module pluginX.py
-- in this snippet being called module
-- under its namespace; E.g, module.hello()
.
If you want to import the members (e.g, "hello
") you can include module
/pluginX
in the in-memory list of modules:
sys.modules[module_name] = module
from pluginX import hello
hello()
Importing a package (e.g., pluginX/__init__.py
) under your current dir is actually straightforward:
import importlib
pkg = importlib.import_module('pluginX')
# check if it's all there..
def bla(mod):
print(dir(mod))
bla(pkg)
Write this code
<?php
if(isset($_POST['submit'])){
echo 'Hello World';
}
?>
<html>
<body>
<form method="post">
<input type="text" name="studentname">
<input type="submit" name="submit" value="click">
</form>
</body>
</html>
This question specifically mentions a single column, so the currently accepted answer works. However, it doesn't generalize to multiple columns. For those interested in a general solution, use the following:
df.replace({False: 0, True: 1}, inplace=True)
This works for a DataFrame that contains columns of many different types, regardless of how many are boolean.
This works well for specific articles where the text is all wrapped in <p>
tags. Since the web is an ugly place, it's not always the case.
Often, websites will have text scattered all over, wrapped in different types of tags (e.g. maybe in a <span>
or a <div>
, or an <li>
).
To find all text nodes in the DOM, you can use soup.find_all(text=True)
.
This is going to return some undesired text, like the contents of <script>
and <style>
tags. You'll need to filter out the text contents of elements you don't want.
blacklist = [
'style',
'script',
# other elements,
]
text_elements = [t for t in soup.find_all(text=True) if t.parent.name not in blacklist]
If you are working with a known set of tags, you can tag the opposite approach:
whitelist = [
'p'
]
text_elements = [t for t in soup.find_all(text=True) if t.parent.name in whitelist]
If anyone is facing this issue in Mysql there is no need to change varchar to nvarchar you can just change the collation of the column to utf8
Angular 4 introduce InjectToken, and they also create a token for document called DOCUMENT. I think this is the official solution and it works in AoT.
I use the same logic to create a small library called ngx-window-token to prevent doing this over and over.
I have used it in other project and build in AoT without issues.
Here is how I used it in other package
Here is the plunker
In your module
imports: [ BrowserModule, WindowTokenModule ]
In your component
constructor(@Inject(WINDOW) _window) { }
Here's a simple approach that works well with Angular.
<ul>
<li ng-class="{ active: isActive('/View1') }"><a href="#/View1">View 1</a></li>
<li ng-class="{ active: isActive('/View2') }"><a href="#/View2">View 2</a></li>
<li ng-class="{ active: isActive('/View3') }"><a href="#/View3">View 3</a></li>
</ul>
Within your AngularJS controller:
$scope.isActive = function (viewLocation) {
var active = (viewLocation === $location.path());
return active;
};
This thread has a number of other similar answers.
The canonical T-SQL (SqlServer) answer is to use a DELETE
with JOIN
as such
DELETE o
FROM Orders o
INNER JOIN Customers c
ON o.CustomerId = c.CustomerId
WHERE c.FirstName = 'sklivvz'
This will delete all orders which have a customer with first name Sklivvz.
In /etc/subversion/servers
you are setting http-proxy-host
, which has nothing to do with svn://
which connects to a different server usually running on port 3690 started by svnserve
command.
If you have access to the server, you can setup svn+ssh://
as explained here.
Update: You could also try using connect-tunnel
, which uses your HTTPS proxy server to tunnel connections:
connect-tunnel -P proxy.company.com:8080 -T 10234:svn.example.com:3690
Then you would use
svn checkout svn://localhost:10234/path/to/trunk
Piping to 'wc' could be better IF the last line ends with a newline (I know that in this case, it will)
However, if the last line does not end with a newline 'wc -l' gives back a false result.
For example:
$ echo "asd" | wc -l
Will return 1
and
$ echo -n "asd" | wc -l
Will return 0
So what I often use is grep <anything> -c
$ echo "asd" | grep "^.*$" -c
1
$ echo -n "asd" | grep "^.*$" -c
1
This is closer to reality than what wc -l
will return.
I found the problem. Instead of adding a class (.cs)
file by mistake I had added a Web API Controller
class which added a configuration file in my solution. And that configuration file was looking for the mentioned DLL (Microsoft.Web.Infrastructure 1.0.0.0).
It worked when I removed that file, cleaned the application and then published.
DPI should not be stored in an bitmap image file, as most sources of data for bitmaps render it meaningless.
A bitmap image is stored as pixels. Pixels have no inherent size in any respect. It's only at render time - be it monitor, printer, or automated crossstitching machine - that DPI matters.
A 800x1000 pixel bitmap image, printed at 100 dpi, turns into a nice 8x10" photo. Printed at 200 dpi, the EXACT SAME bitmap image turns into a 4x5" photo.
Capture an image with a digital camera, and what does DPI mean? It's certainly not the size of the area focused onto the CCD imager - that depends on the distance, and with NASA returning images of galaxies that are 100,000 light years across, and 2 million light years apart, in the same field of view, what kind of DPI do you get from THAT information?
Don't fall victim to the idea of the DPI of a bitmap image - it's a mistake. A bitmap image has no physical dimensions (save for a few micrometers of storage space in RAM or hard drive). It's only a displayed image, or a printed image, that has a physical size in inches, or millimeters, or furlongs.
I believe that you are trying to connect to a something using SSL but that something is providing a certificate which is not verified by root certification authorities such as verisign.. In essence by default secure connections can only be established if the person trying to connect knows the counterparties keys or some other verndor such as verisign can step in and say that the public key being provided is indeed right..
ALL OS's trust a handful of certification authorities and smaller certificate issuers need to be certified by one of the large certifiers making a chain of certifiers if you get what I mean...
Anyways coming back to the point.. I had a similiar problem when programming a java applet and a java server ( Hopefully some day I will write a complete blogpost about how I got all the security to work :) )
In essence what I had to do was to extract the public keys from the server and store it in a keystore inside my applet and when I connected to the server I used this key store to create a trust factory and that trust factory to create the ssl connection. There are alterante procedures as well such as adding the key to the JVM's trusted host and modifying the default trust store on start up..
I did this around two months back and dont have source code on me right now.. use google and you should be able to solve this problem. If you cant message me back and I can provide you the relevent source code for the project .. Dont know if this solves your problem since you havent provided the code which causes these exceptions. Furthermore I was working wiht applets thought I cant see why it wont work on Serverlets...
P.S I cant get source code before the weekend since external SSH is disabled in my office :(
array_walk()
can be used with trim()
to trim array
<?php
function trim_value(&$value)
{
$value = trim($value);
}
$fruit = array('apple','banana ', ' cranberry ');
var_dump($fruit);
array_walk($fruit, 'trim_value');
var_dump($fruit);
?>
See 2nd example at http://www.php.net/manual/en/function.trim.php
I had the same problem and this is how I solved it. I had a duplicate property with the same name in my ViewModel. One Property was in BaseViewModel and another is in derived Model.
public class BaseviewModel{
public int UserId { get; set; }
}
public class Model : BaseViewModel
{
public int UserId { get; set; }
}
I changed that to
public class BaseviewModel{
public int UserId { get; set; }
}
public class Model : BaseViewModel
{
public int User_Id { get; set; }
}
Now it is working fine.
Some comments:
Jet/ACE files are organized in data pages, which means there is a certain amount of slack space when your record boundaries are not aligned with your data pages.
Row-level locking will greatly reduce the number of possible records, since it forces one record per data page.
In Jet 4, the data page size was increased to 4KBs (from 2KBs in Jet 3.x). As Jet 4 was the first Jet version to support Unicode, this meant that you could store 1GB of double-byte data (i.e., 1,000,000,000 double-byte characters), and with Unicode compression turned on, 2GBs of data. So, the number of records is going to be affected by whether or not you have Unicode compression on.
Since we don't know how much room in a Jet/ACE file is taken up by headers and other metadata, nor precisely how much room index storage takes, the theoretical calculation is always going to be under what is practical.
To get the most efficient possible storage, you'd want to use code to create your database rather than the Access UI, because Access creates certain properties that pure Jet does not need. This is not to say there are a lot of these, as properties set to the Access defaults are usually not set at all (the property is created only when you change it from the default value -- this can be seen by cycling through a field's properties collection, i.e., many of the properties listed for a field in the Access table designer are not there in the properties collection because they haven't been set), but you might want to limit yourself to Jet-specific data types (hyperlink fields are Access-only, for instance).
I just wasted an hour mucking around with this using Rnd() to populate 4 fields defined as type byte, with composite PK on the four fields, and it took forever to append enough records to get up to any significant portion of 2GBs. At over 2 million records, the file was under 80MBs. I finally quit after reaching just 700K 7 MILLION records and the file compacted to 184MBs. The amount of time it would take to get up near 2GBs is just more than I'm willing to invest!
DateTime? NextChoiceDate = new DateTime();
DateTIme? NextSwitchDate = new DateTime();
if(NextChoiceDate.Value.Date == NextSwitchDate.Value.Date)
{
Console.WriteLine("Equal");
}
You can use this if you are using nullable DateFields.
With Spring you can do:
String path = new UrlPathHelper().getPathWithinApplication(request);
For me the Anonymous User access was fine at the server level, but varied at just one of my "virtual" folders.
Took me quite a bit of foundering about and then some help from a colleague to learn that IIS has "authentication" settings at the virtual folder level too - hopefully this helps someone else with my predicament.
There's not really a good way to do this, usually you see an extra item in the enum, i.e.
enum foobar {foo, bar, baz, quz, FOOBAR_NR_ITEMS};
So then you can do:
int fuz[FOOBAR_NR_ITEMS];
Still not very nice though.
But of course you do realize that just the number of items in an enum is not safe, given e.g.
enum foobar {foo, bar = 5, baz, quz = 20};
the number of items would be 4, but the integer values of the enum values would be way out of the array index range. Using enum values for array indexing is not safe, you should consider other options.
edit: as requested, made the special entry stick out more.
You have to roll your own.
You start with a total of 0. Then you consider for every integer in the array, add it to a total. Then when you're out of integers, you have the sum.
If there were no integers, then the total is 0.
What you have is piping the text "cat test"
into the loop.
You just want:
cat test | \
while read CMD; do
echo $CMD
done
To run multiple commands just add &&
between two commands like this: command1 && command2
And if you want to run them in two different terminals then you do it like this:
gnome-terminal -e "command1" && gnome-terminal -e "command2"
This will open 2 terminals with command1
and command2
executing in them.
Hope this helps you.
For .Net core i had many problems using SSH.net and also its deprecated. I tried a few other libraries, even for other programming languages. But i found a very good alternative. https://stackoverflow.com/a/64443701/8529170
System.out.println(new String(new byte[]{ (byte)0x63 }, "US-ASCII"));
Note especially that converting bytes to Strings always involves an encoding. If you do not specify it, you'll be using the platform default encoding, which means the code can break when running in different environments.
var root = document.createElement("div");
root.innerHTML = "My name is <b>Bob</b>, I'm <b>20</b> years old, I like <b>programming</b>.";
var texts = [].map.call( root.querySelectorAll("b"), function(v){
return v.textContent || v.innerText || "";
});
//["Bob", "20", "programming"]
Use scanf("%d",&rows)
instead of scanf("%s",input)
This allow you to get direcly the integer value from stdin without need to convert to int.
If the user enter a string containing a non numeric characters then you have to clean your stdin before the next scanf("%d",&rows)
.
your code could look like this:
#include <stdio.h>
#include <stdlib.h>
int clean_stdin()
{
while (getchar()!='\n');
return 1;
}
int main(void)
{
int rows =0;
char c;
do
{
printf("\nEnter an integer from 1 to 23: ");
} while (((scanf("%d%c", &rows, &c)!=2 || c!='\n') && clean_stdin()) || rows<1 || rows>23);
return 0;
}
Explanation
1)
scanf("%d%c", &rows, &c)
This means expecting from the user input an integer and close to it a non numeric character.
Example1: If the user enter aaddk
and then ENTER
, the scanf will return 0. Nothing capted
Example2: If the user enter 45
and then ENTER
, the scanf will return 2 (2 elements are capted). Here %d
is capting 45
and %c
is capting \n
Example3: If the user enter 45aaadd
and then ENTER
, the scanf will return 2 (2 elements are capted). Here %d
is capting 45
and %c
is capting a
2)
(scanf("%d%c", &rows, &c)!=2 || c!='\n')
In the example1: this condition is TRUE
because scanf return 0
(!=2
)
In the example2: this condition is FALSE
because scanf return 2
and c == '\n'
In the example3: this condition is TRUE
because scanf return 2
and c == 'a' (!='\n')
3)
((scanf("%d%c", &rows, &c)!=2 || c!='\n') && clean_stdin())
clean_stdin()
is always TRUE
because the function return always 1
In the example1: The (scanf("%d%c", &rows, &c)!=2 || c!='\n')
is TRUE
so the condition after the &&
should be checked so the clean_stdin()
will be executed and the whole condition is TRUE
In the example2: The (scanf("%d%c", &rows, &c)!=2 || c!='\n')
is FALSE
so the condition after the &&
will not checked (because what ever its result is the whole condition will be FALSE
) so the clean_stdin()
will not be executed and the whole condition is FALSE
In the example3: The (scanf("%d%c", &rows, &c)!=2 || c!='\n')
is TRUE
so the condition after the &&
should be checked so the clean_stdin()
will be executed and the whole condition is TRUE
So you can remark that clean_stdin()
will be executed only if the user enter a string containing non numeric character.
And this condition ((scanf("%d%c", &rows, &c)!=2 || c!='\n') && clean_stdin())
will return FALSE
only if the user enter an integer
and nothing else
And if the condition ((scanf("%d%c", &rows, &c)!=2 || c!='\n') && clean_stdin())
is FALSE
and the integer
is between and 1
and 23
then the while
loop will break else the while
loop will continue
I had this problem, too.
Possible causes in my case: I had deleted a duplicated view twice and a view model. I reverted one of the deletes and then the InitializeComponent error appeared. I took these steps.
class Class1(object):
pass
class Class2(Class1):
pass
Class2 is a sub-class of Class1
I had the same problem, I've fixed it very simple by updating my JDK version. If you don't have JDK installed or not updated, please Go here and install/update it. Mostly your problem will be fixed.
CAUSE: "Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app." In this case, "ACCESS_FINE_LOCATION" is a "dangerous permission and for that reason, you get this 'java.lang.SecurityException: "gps" location provider requires ACCESS_FINE_LOCATION permission.' error (https://developer.android.com/training/permissions/requesting.html).
SOLUTION: Implementing the code provided at https://developer.android.com/training/permissions/requesting.html under the "Request the permissions you need" and "Handle the permissions request response" headings.
This is very simple to understand :-
id is used when we have to apply CSS property to one attribute only.
class is used when we have to use CSS property in many locations within the same page or different.
General :- for unique structure like staring div and buttons layout we use id .
for same CSS throughout the page or project we use class
id is light and class is little heavy
How do I initialize the base (super) class?
class SuperClass(object): def __init__(self, x): self.x = x class SubClass(SuperClass): def __init__(self, y): self.y = y
Use a super
object to ensure you get the next method (as a bound method) in the method resolution order. In Python 2, you need to pass the class name and self
to super to lookup the bound __init__
method:
class SubClass(SuperClass):
def __init__(self, y):
super(SubClass, self).__init__('x')
self.y = y
In Python 3, there's a little magic that makes the arguments to super
unnecessary - and as a side benefit it works a little faster:
class SubClass(SuperClass):
def __init__(self, y):
super().__init__('x')
self.y = y
Hardcoding the parent like this below prevents you from using cooperative multiple inheritance:
class SubClass(SuperClass):
def __init__(self, y):
SuperClass.__init__(self, 'x') # don't do this
self.y = y
Note that __init__
may only return None
- it is intended to modify the object in-place.
__new__
There's another way to initialize instances - and it's the only way for subclasses of immutable types in Python. So it's required if you want to subclass str
or tuple
or another immutable object.
You might think it's a classmethod because it gets an implicit class argument. But it's actually a staticmethod. So you need to call __new__
with cls
explicitly.
We usually return the instance from __new__
, so if you do, you also need to call your base's __new__
via super
as well in your base class. So if you use both methods:
class SuperClass(object):
def __new__(cls, x):
return super(SuperClass, cls).__new__(cls)
def __init__(self, x):
self.x = x
class SubClass(object):
def __new__(cls, y):
return super(SubClass, cls).__new__(cls)
def __init__(self, y):
self.y = y
super(SubClass, self).__init__('x')
Python 3 sidesteps a little of the weirdness of the super calls caused by __new__
being a static method, but you still need to pass cls
to the non-bound __new__
method:
class SuperClass(object):
def __new__(cls, x):
return super().__new__(cls)
def __init__(self, x):
self.x = x
class SubClass(object):
def __new__(cls, y):
return super().__new__(cls)
def __init__(self, y):
self.y = y
super().__init__('x')
What are disadvantages of the following solution? Seems to be faster and shorter.
var options = {
set0: ['Option 1','Option 2'],
set1: ['First Option','Second Option','Third Option']
};
var list = "<li>" + options.set0.join("</li><li>") + "</li>";
document.getElementById("list").innerHTML = list;
db.collection_name.aggregate([
{ '$match' : { } },
{ '$sort' : { '_id' : -1 } },
{ '$facet' : {
metadata: [ { $count: "total" } ],
data: [ { $skip: 1 }, { $limit: 10 },{ '$project' : {"_id":0} } ] // add projection here wish you re-shape the docs
} }
] )
Instead of using two queries to find the total count and skip the matched record.
$facet is the best and optimized way.
If you are able to see the project in Eclipse project explorer but unable to see the project while adding the project to the web server, follow project properties -> Project Facets, make sure Dynamic Web Module & Java were ticked.
The set
statement doesn't treat spaces the way you expect; your variable is really named Pathname[space]
and is equal to [space]C:\Program Files
.
Remove the spaces from both sides of the =
sign, and put the value in double quotes:
set Pathname="C:\Program Files"
Also, if your command prompt is not open to C:\, then using cd
alone can't change drives.
Use
cd /d %Pathname%
or
pushd %Pathname%
instead.
Because the interpreter is not a shell where you provide commands, it's - well - an interpreter. The things that you give to it are Python code.
The syntax of Python is such that exit
, by itself, cannot possibly be anything other than a name for an object. Simply referring to an object can't actually do anything (except what the read-eval-print loop normally does; i.e. display a string representation of the object).
If a non-static method is member of a class, you have to define it like that:
def Method(self, atributes..)
So, I suppose your 'e' is instance of some class with implemented method that tries to execute and has too much arguments.
To create an instance of a class from another project in the solution, you can get the assembly indicated by the name of any class (for example BaseEntity) and create a new instance:
var newClass = System.Reflection.Assembly.GetAssembly(typeof(BaseEntity)).CreateInstance("MyProject.Entities.User");
The problem is non-trivial when it comes to host objects or any kind of object that's more complex than a bag of values
Another thing to keep in mind: Object graphs that contain cycles. It's usually not difficult to deal with - simply keep a Set
of already-visited source objects - but often forgotten.
You probably should write a deep-merge function that only expects primitive values and simple objects - at most those types that the structured clone algorithm can handle - as merge sources. Throw if it encounters anything it cannot handle or just assign by reference instead of deep merging.
In other words, there is no one-size-fits-all algorithm, you either have to roll your own or look for a library method that happens to cover your use-cases.
The best option: os.system('pause')
<-- this will actually display a message saying 'press any key to continue' whereas adding just raw_input('')
will print no message, just the cursor will be available.
not related to answer:
os.system("some cmd command")
is a really great command as the command can execute any batch file/cmd commands.
import datetime
datetime.datetime.now().strftime ("%Y%m%d")
20151015
For the time
from time import gmtime, strftime
showtime = strftime("%Y-%m-%d %H:%M:%S", gmtime())
print showtime
2015-10-15 07:49:18
This should work:
string url = "http://example.com/file?a=1&b=2&c=string%20param";
string querystring = url.Substring(url.IndexOf('?'));
System.Collections.Specialized.NameValueCollection parameters =
System.Web.HttpUtility.ParseQueryString(querystring);
According to MSDN. Not the exact collectiontype you are looking for, but nevertheless useful.
Edit: Apparently, if you supply the complete url to ParseQueryString
it will add 'http://example.com/file?a' as the first key of the collection. Since that is probably not what you want, I added the substring to get only the relevant part of the url.
file='path/test.xml'
with open(file, 'w') as filetowrite:
filetowrite.write('new content')
Open the file in 'w' mode, you will be able to replace its current text save the file with new contents.
You can also convert the URI to file and then to bytes if you want to upload the photo to your server.
Check out : https://www.stackoverflow.com/a/49575321
**just fire bootstrap modal close button click event**
var app = angular.module('myApp', []);
app.controller('myCtrl',function($scope,$http){
$('#btnClose').click();// this is bootstrap modal close button id that fire click event
})
--------------------------------------------------------------------------------
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" id="btnClose" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
just set modal 'close button' id as i set btnClose, for closing modal in angular you have to just fire that close button click event as i did $('#btnClose').click()
The Color
structure is immutable (as all structures should really be), meaning that the values of its properties cannot be changed once that particular instance has been created.
Instead, you need to create a new instance of the structure with the property values that you want. Since you want to create a color using its component RGB values, you need to use the FromArgb
method:
Color myColor = Color.FromArgb(100, 150, 75);
The other answers are all correct, but surprisingly all leaving out the theoretical aspect here: return types can be different, but they can only restrict the type used in the super class because of the Liskov Substitution Principle.
It is super simple: when you have "client" code that calls some method:
int foo = someBar.bar();
then the above has to work (and return something that is an int
no matter which implementation of bar()
is invoked).
Meaning: if there is a Bar subclass that overrides bar()
then you still have to return something that doesn't break "caller code".
In other words: assume that the base bar()
is supposed to return int. Then a subclass could return short
- but not long
because callers will be fine dealing with a short
value, but not a long
!
You can check the String.match
() or the String.indexOf()
methods.
Found this "plug-and-play" function here. Worked like a charm!
import subprocess
def myrun(cmd):
"""from http://blog.kagesenshi.org/2008/02/teeing-python-subprocesspopen-output.html
"""
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout = []
while True:
line = p.stdout.readline()
stdout.append(line)
print line,
if line == '' and p.poll() != None:
break
return ''.join(stdout)
Here's an elegant array formula (which I found here http://www.excel-easy.com/examples/count-unique-values.html) that does the trick nicely:
Type
=SUM(1/COUNTIF(List,List))
and confirm with CTRL-SHIFT-ENTER
You can try this:
((BigDecimal) volume).intValue();
I use java.math.BigDecimal
convert to int
(primitive type).
It is worked for me.
sed
The -i
flag works differently on macOS sed
than in GNU sed
.
Here's the way to use it on macOS / OS X:
sed -i '' '8i\
8 This is Line 8' FILE
See man 1 sed
for more info.
127.0.0.1 restricts access on every interface on port 8000 except development computer. change it to 0.0.0.0:8000 this will allow connection from curl.
geopoint = {'latitude':41.123,'longitude':71.091}
# working examples.
print(f'{geopoint["latitude"]} {geopoint["longitude"]}') # from above answer
print('{geopoint[latitude]} {geopoint[longitude]}'.format(geopoint=geopoint)) # alternate for format method (including dict name in string).
print('%(latitude)s %(longitude)s'%geopoint) # thanks @tcll
I won't refer too your example as it is quite simple for a general answer (for example it doesn't contain templated functions ,which force you to implement them on the header) , what I follow as a rule of thumb is the pimpl idiom
It has quite some benefits as you get faster compilation times and the syntactic sugar :
class->member
instead of class.member
The only drawback is the extra pointer you pay.
INDEXES
- to find data easily
UNIQUE INDEX
- duplicate values are not allowed
Syntax for INDEX
CREATE INDEX INDEX_NAME ON TABLE_NAME(COLUMN);
Syntax for UNIQUE INDEX
CREATE UNIQUE INDEX INDEX_NAME ON TABLE_NAME(COLUMN);
From what the error message complains about, it sounds like you should rather try to fix the source code. The compiler complains about difference in declaration, similar to for instance
void foo(int i);
...
void foo(double d) {
...
}
and this is not valid C code, hence the compiler complains.
Maybe your problem is that there is no prototype available when the function is used the first time and the compiler implicitly creates one that will not be static. If so the solution is to add a prototype somewhere before it is first used.
Yes, there are a number of ways that you can do this. The "fastest" way would be to add CSS to the div similar to the following
#term-defs {
height: 300px;
overflow: scroll; }
This will force the div to be scrollable, but this might not get the best effect. Another route would be to absolute fix the position of the items at the top, you can play with this by doing something like this.
#top {
position: fixed;
top: 0;
left: 0;
z-index: 999;
width: 100%;
height: 23px;
}
This will fix it to the top, on top of other content with a height of 23px.
The final implementation will depend on what effect you really want.
I would suggest making the div
s a little smaller and adding a margin of a percentage.
<div style="width:100%; height: 200px; background-color: grey;">_x000D_
<div style="width: 23%; float:left; margin: 1%; background-color: red;">A</div>_x000D_
<div style="width: 23%; float:left; margin: 1%; background-color: orange;">B</div>_x000D_
<div style="width: 23%; float:left; margin: 1%; background-color: green;">C</div>_x000D_
<div style="width: 23%; float:left; margin: 1%; background-color: blue;">D</div>_x000D_
</div>
_x000D_
You should use
date = datetime(int(year), int(month), 1)
Or change
from datetime import datetime
to
import datetime
If you use NetBeans IDE right click form then
Properties ->Code -> check out Generate Center
how about in vuejs how is it applicable?
function onClick() {_x000D_
var pdf = new jsPDF('p', 'pt', 'letter');_x000D_
pdf.canvas.height = 72 * 11;_x000D_
pdf.canvas.width = 72 * 8.5;_x000D_
_x000D_
pdf.fromHTML(document.body);_x000D_
_x000D_
pdf.save('test.pdf');_x000D_
};_x000D_
_x000D_
var element = document.getElementById("clickbind");_x000D_
element.addEventListener("click", onClick);
_x000D_
<h1>Dsdas</h1>_x000D_
_x000D_
<a id="clickbind" href="#">Click</a>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script>
_x000D_
<span>
elements are inline elements, as such layout properties such as width
or margin
don't work. You can fix that by either changing the <span>
to a block element (such as <div>
), or by using padding instead.
Note that making a span
element a block element by adding display: block;
is redundant, as a span
is by definition a otherwise style-less inline element whereas div
is an otherwise style-less block element. So the correct solution is to use a div
instead of a block-span
.
For starters:
<p align='center'>
<table width='100%'>
<tr>
<td align='center'><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>
Note, if the width of the input button is 100%, you wont need the attribute "align='center'" anymore.
This would be the optimal solution:
<p align='center'>
<table width='100%'>
<tr>
<td><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>
Here's another solution: http://jsfiddle.net/6WvUY/7/.
HTML:
<div class="container">
<div class="row">
<div class="col-sm-6">
<img src="//placehold.it/600x300" alt="Logo" class="img-responsive"/>
</div>
<div class="col-sm-6">
<h3>Some Text</h3>
</div>
</div>
</div>
CSS:
.row {
display: table;
}
.row > div {
float: none;
display: table-cell;
}
The performance impact depends on the way you lock. You can find a good list of optimizations here: http://www.thinkingparallel.com/2007/07/31/10-ways-to-reduce-lock-contention-in-threaded-programs/
Basically you should try to lock as little as possible, since it puts your waiting code to sleep. If you have some heavy calculations or long lasting code (e.g. file upload) in a lock it results in a huge performance loss.
The line (or lines) between the lines beginning <<<<<<<
and ======
here:
<<<<<<< HEAD:file.txt
Hello world
=======
... is what you already had locally - you can tell because HEAD
points to your current branch or commit. The line (or lines) between the lines beginning =======
and >>>>>>>
:
=======
Goodbye
>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt
... is what was introduced by the other (pulled) commit, in this case 77976da35a11
. That is the object name (or "hash", "SHA1sum", etc.) of the commit that was merged into HEAD
. All objects in git, whether they're commits (version), blobs (files), trees (directories) or tags have such an object name, which identifies them uniquely based on their content.
Try width: max-content
to adjust the width of the div by it's content.
<!DOCTYPE html>
<html>
<head>
<style>
div.ex1 {
width:500px;
margin: auto;
border: 3px solid #73AD21;
}
div.ex2 {
width: max-content;
margin: auto;
border: 3px solid #73AD21;
}
</style>
</head>
<body>
<div class="ex1">This div element has width 500px;</div>
<br>
<div class="ex2">Width by content size</div>
</body>
</html>
<!-- xaml code-->
<Grid>
<ComboBox Name="cmbData" SelectedItem="{Binding SelectedstudentInfo, Mode=OneWayToSource}" HorizontalAlignment="Left" Margin="225,150,0,0" VerticalAlignment="Top" Width="120" DisplayMemberPath="name" SelectedValuePath="id" SelectedIndex="0" />
<Button VerticalAlignment="Center" Margin="0,0,150,0" Height="40" Width="70" Click="Button_Click">OK</Button>
</Grid>
//student Class
public class Student
{
public int Id { set; get; }
public string name { set; get; }
}
//set 2 properties in MainWindow.xaml.cs Class
public ObservableCollection<Student> studentInfo { set; get; }
public Student SelectedstudentInfo { set; get; }
//MainWindow.xaml.cs Constructor
public MainWindow()
{
InitializeComponent();
bindCombo();
this.DataContext = this;
cmbData.ItemsSource = studentInfo;
}
//method to bind cobobox or you can fetch data from database in MainWindow.xaml.cs
public void bindCombo()
{
ObservableCollection<Student> studentList = new ObservableCollection<Student>();
studentList.Add(new Student { Id=0 ,name="==Select=="});
studentList.Add(new Student { Id = 1, name = "zoyeb" });
studentList.Add(new Student { Id = 2, name = "siddiq" });
studentList.Add(new Student { Id = 3, name = "James" });
studentInfo=studentList;
}
//button click to get selected student MainWindow.xaml.cs
private void Button_Click(object sender, RoutedEventArgs e)
{
Student student = SelectedstudentInfo;
if(student.Id ==0)
{
MessageBox.Show("select name from dropdown");
}
else
{
MessageBox.Show("Name :"+student.name + "Id :"+student.Id);
}
}
This is th privileges issue in your database users. first check and grant permission to user 'marco' in localhost
Select "File" -> "Project Structure".
Under "Project Settings" select "Project"
From there you can select the "Project SDK".
In Reactive forms. Binding can be done in the component file and usage of ngValue. For more details please go through the following link
https://angular.io/api/forms/SelectControlValueAccessor
import {Component} from '@angular/core';
import {FormControl, FormGroup} from '@angular/forms';
@Component({
selector: 'example-app',
template: `
<form [formGroup]="form">
<select formControlName="state">
<option *ngFor="let state of states" [ngValue]="state">
{{ state.abbrev }}
</option>
</select>
</form>
<p>Form value: {{ form.value | json }}</p>
<!-- {state: {name: 'New York', abbrev: 'NY'} } -->
`,
})
export class ReactiveSelectComp {
states = [
{name: 'Arizona', abbrev: 'AZ'},
{name: 'California', abbrev: 'CA'},
{name: 'Colorado', abbrev: 'CO'},
{name: 'New York', abbrev: 'NY'},
{name: 'Pennsylvania', abbrev: 'PA'},
];
form = new FormGroup({
state: new FormControl(this.states[3]),
});
}