Lattice solution with additional settings which I needed:
library(lattice)
distribution<-function(x) {2^(-x*2)}
X<-seq(0,10,0.00001)
xyplot(distribution(X)~X,type="l", col = rgb(red = 255, green = 90, blue = 0, maxColorValue = 255), cex.lab = 3.5, cex.axis = 3.5, lwd=2 )
X<-seq(0,10,0.00001)
col = rgb(red = 255, green = 90, blue = 0, maxColorValue = 255)
lwd = 2
cex.lab = 3.5, cex.axis = 3.5
If N is big enough, you're going to get some similar-looking colors. There's only so many of them in the world.
Why not just evenly distribute them through the spectrum, like so:
IEnumerable<Color> CreateUniqueColors(int nColors)
{
int subdivision = (int)Math.Floor(Math.Pow(nColors, 1/3d));
for(int r = 0; r < 255; r += subdivision)
for(int g = 0; g < 255; g += subdivision)
for(int b = 0; b < 255; b += subdivision)
yield return Color.FromArgb(r, g, b);
}
If you want to mix up the sequence so that similar colors aren't next to each other, you could maybe shuffle the resulting list.
Am I underthinking this?
There is no rocket science in deleting items from array. To delete items from any array you need to use splice
: $scope.items.splice(index, 1);
. Here is an example:
HTML
<!DOCTYPE html>
<html data-ng-app="demo">
<head>
<script data-require="[email protected]" data-semver="1.1.5" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div data-ng-controller="DemoController">
<ul>
<li data-ng-repeat="item in items">
{{item}}
<button data-ng-click="removeItem($index)">Remove</button>
</li>
</ul>
<input data-ng-model="newItem"><button data-ng-click="addItem(newItem)">Add</button>
</div>
</body>
</html>
JavaScript
"use strict";
var demo = angular.module("demo", []);
function DemoController($scope){
$scope.items = [
"potatoes",
"tomatoes",
"flour",
"sugar",
"salt"
];
$scope.addItem = function(item){
$scope.items.push(item);
$scope.newItem = null;
}
$scope.removeItem = function(index){
$scope.items.splice(index, 1);
}
}
Using CURL:
SOAP_USER='myusername'
PASSWORD='mypassword'
AUTHENTICATION="$SOAP_USER:$PASSWORD"
URL='http://mysoapserver:8080/meeting/aws'
SOAPFILE=getCurrentMeetingStatus.txt
TIMEOUT=5
CURL request:
curl --user "${AUTHENTICATION}" --header 'Content-Type: text/xml;charset=UTF-8' --data @"${SOAPFILE}" "${URL}" --connect-timeout $TIMEOUT
I use this to verify response:
http_code=$(curl --write-out "%{http_code}\n" --silent --user "${AUTHENTICATION}" --header 'Content-Type: text/xml;charset=UTF-8' --data @"${SOAPFILE}" "${URL}" --connect-timeout $TIMEOUT --output /dev/null)
if [[ $http_code -gt 400 ]]; # 400 and 500 Client and Server Error codes http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
then
echo "Error: HTTP response ($http_code) getting URL: $URL"
echo "Please verify parameters/backend. Username: $SOAP_USER Password: $PASSWORD Press any key to continue..."
read entervalue || continue
fi
Try this.
<asp:Button id="myButton" runat="server" style="display:none" Text="Click Me" />
<script type="text/javascript">
function ShowButton() {
var buttonID = '<%= myButton.ClientID %>';
var button = document.getElementById(buttonID);
if(button) { button.style.display = 'inherit'; }
}
</script>
Don't use server-side code to do this because that would require a postback. Instead of using Visibility="false", you can just set a CSS property that hides the button. Then, in javascript, switch that property back whenever you want to show the button again.
The ClientID is used because it can be different from the server ID if the button is inside a Naming Container control. These include Panels of various sorts.
inside OnCreate method :-
{
Button b = (Button)findViewById(R.id.button1);
b.setOnClickListener((View.OnClickListener)this);
b = (Button)findViewById(R.id.button2);
b.setOnClickListener((View.OnClickListener)this);
}
@Override
public void OnClick(View v){
switch(v.getId()){
case R.id.button1:
//whatever
break;
case R.id.button2:
//whatever
break;
}
This seems to be answered - #include <fstream>
.
The message means :-
incomplete type
- the class has not been defined with a full class. The compiler has seen statements such as class ifstream;
which allow it to understand that a class exists, but does not know how much memory the class takes up.
The forward declaration allows the compiler to make more sense of :-
void BindInput( ifstream & inputChannel );
It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.
The has initializer
seems a bit extraneous, but is saying that the incomplete object is being created.
Do note that on newer Apache versions the RewriteLog
and RewriteLogLevel
have been removed, and in fact will now trigger an error when trying to start Apache (at least on my XAMPP installation with Apache 2.4.2):
AH00526: Syntax error on line xx of path/to/config/file.conf: Invalid command 'RewriteLog', perhaps misspelled or defined by a module not included in the server configuration`
Instead, you're now supposed to use the general LogLevel
directive, with a level of trace1
up to trace8
. 'debug' didn't display any rewrite messages in the log for me.
Example: LogLevel warn rewrite:trace3
For the official documentation, see here.
Of course this also means that now your rewrite logs will be written in the general error log file and you'll have to sort them out yourself.
(This is for posts, not pages - the principle is same. The permalink hook is different by exact use case)
I just had the same issue and created a more convenient way to do that - where you don't have to re-edit your functions.php
all the time, or fiddle around with your server settings on each addition (I do not like both).
TLTR
You can add a filter on the actual WP permalink function you need (for me it was post_link
, because I needed that page alias in an archive/category list), and dynamically read the referenced ID from the alias post itself.
This is ok, because the post is an alias, so you won't need the content anyways.
First step is to open the alias post and put the ID of the referenced post as content (and nothing else):
Next, open your functions.php
and add:
function prefix_filter_post_permalink($url, $post) {
// if the content of the post to get the permalink for is just a number...
if (is_numeric($post->post_content)) {
// instead, return the permalink for the post that has this ID
return get_the_permalink((int)$post->post_content);
}
return $url;
}
add_filter('post_link', 'prefix_filter_post_permalink', 10, 2 );
That's it
Now, each time you need to create an alias post, just put the ID of the referenced post as the content, and you're done.
This will just change the permalink. Title, excerpt and so on will be shown as-is, which is usually desired. More tweaking to your needs is on you, also, the "is it a number" part in the PHP
code is far from ideal, but like this for making the point readable.
How to address your textbox depends on the HTML-code:
<!-- 1 --><input type="textbox" id="Tue" />
<!-- 2 --><input type="textbox" name="Tue" />
If you use the 'id' attribute:
var textbox = document.getElementById('Tue');
for 'name':
var textbox = document.getElementsByName('Tue')[0]
(Note that getElementsByName() returns all elements with the name as array, therefore we use [0] to access the first one)
Then, use the 'value' attribute:
textbox.value = 'Foobar';
May I add something. If you are using currency you should use Scale(2), and you should probably figure out a round method.
Besides the solutions presented already, you could use the Apache Commons Lang library:
if(StringUtils.startsWithAny(newStr4, new String[] {"Mon","Tues",...})) {
//whatever
}
Update: the introduction of varargs at some point makes the call simpler now:
StringUtils.startsWithAny(newStr4, "Mon", "Tues",...)
As we all know that IPv4 address for
localhost
is127.0.0.1
(loopback address).
Actually, any IPv4 address in 127.0.0.0/8
is a loopback address.
In IPv6, the direct analog of the loopback range is ::1/128
. So ::1
(long form 0:0:0:0:0:0:0:1
) is the one and only IPv6 loopback address.
While the hostname localhost
will normally resolve to 127.0.0.1
or ::1
, I have seen cases where someone has bound it to an IP address that is not a loopback address. This is a bit crazy ... but sometimes people do it.
I say "this is crazy" because you are liable to break applications assumptions by doing this; e.g. an application may attempt to do a reverse lookup on the loopback IP and not get the expected result. In the worst case, an application may end up sending sensitive traffic over an insecure network by accident ... though you probably need to make other mistakes as well to "achieve" that.
Blocking 0.0.0.0
makes no sense. In IPv4 it is never routed. The equivalent in IPv6 is the ::
address (long form 0:0:0:0:0:0:0:0
) ... which is also never routed.
The 0.0.0.0
and ::
addresses are reserved to mean "any address". So, for example a program that is providing a web service may bind to 0.0.0.0
port 80 to accept HTTP connections via any of the host's IPv4 addresses. These addresses are not valid as a source or destination address for an IP packet.
Finally, some comments were asking about ::/128
versus ::/0
versus ::
.
What is this difference?
Strictly speaking, the first two are CIDR notation not IPv6 addresses. They are actually specifying a range of IP addresses. A CIDR consists of a IP address and an additional number that specifies the number of bits in a netmask. The two together specify a range of addresses; i.e. the set of addresses formed by ignoring the bits masked out of the given address.
So:
::
means just the IPv6 address 0:0:0:0:0:0:0:0
::/128
means 0:0:0:0:0:0:0:0
with a netmask consisting of 128 bits. This gives a network range with exactly one address in it.::/0
means 0:0:0:0:0:0:0:0
with a netmask consisting of 0 bits. This gives a network range with 2128 addresses in it.; i.e. it is the entire IPv6 address space!For more information, read the Wikipedia pages on IPv4 & IPv6 addresses, and CIDR notation:
You can try this.
$(document).ready(function(){
alert();
$('#rep??ortVariablesTable tbody').append( '<tr><td>lll</td><td>lll</td></tr>');
});
NOTE: Before trying this code, please find this line in the below code:
private static String DB_NAME ="YourDbName"; // Database name
DB_NAME here is the name of your database. It is assumed that you have a copy of the database in the assets folder, so for example, if your database name is ordersDB, then the value of DB_NAME will be ordersDB,
private static String DB_NAME ="ordersDB";
Keep the database in assets folder and then follow the below:
DataHelper class:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DataBaseHelper extends SQLiteOpenHelper {
private static String TAG = "DataBaseHelper"; // Tag just for the LogCat window
private static String DB_NAME ="YourDbName"; // Database name
private static int DB_VERSION = 1; // Database version
private final File DB_FILE;
private SQLiteDatabase mDataBase;
private final Context mContext;
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
DB_FILE = context.getDatabasePath(DB_NAME);
this.mContext = context;
}
public void createDataBase() throws IOException {
// If the database does not exist, copy it from the assets.
boolean mDataBaseExist = checkDataBase();
if(!mDataBaseExist) {
this.getReadableDatabase();
this.close();
try {
// Copy the database from assests
copyDataBase();
Log.e(TAG, "createDatabase database created");
} catch (IOException mIOException) {
throw new Error("ErrorCopyingDataBase");
}
}
}
// Check that the database file exists in databases folder
private boolean checkDataBase() {
return DB_FILE.exists();
}
// Copy the database from assets
private void copyDataBase() throws IOException {
InputStream mInput = mContext.getAssets().open(DB_NAME);
OutputStream mOutput = new FileOutputStream(DB_FILE);
byte[] mBuffer = new byte[1024];
int mLength;
while ((mLength = mInput.read(mBuffer)) > 0) {
mOutput.write(mBuffer, 0, mLength);
}
mOutput.flush();
mOutput.close();
mInput.close();
}
// Open the database, so we can query it
public boolean openDataBase() throws SQLException {
// Log.v("DB_PATH", DB_FILE.getAbsolutePath());
mDataBase = SQLiteDatabase.openDatabase(DB_FILE, null, SQLiteDatabase.CREATE_IF_NECESSARY);
// mDataBase = SQLiteDatabase.openDatabase(DB_FILE, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
return mDataBase != null;
}
@Override
public synchronized void close() {
if(mDataBase != null) {
mDataBase.close();
}
super.close();
}
}
Write a DataAdapter class like:
import java.io.IOException;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
public class TestAdapter {
protected static final String TAG = "DataAdapter";
private final Context mContext;
private SQLiteDatabase mDb;
private DataBaseHelper mDbHelper;
public TestAdapter(Context context) {
this.mContext = context;
mDbHelper = new DataBaseHelper(mContext);
}
public TestAdapter createDatabase() throws SQLException {
try {
mDbHelper.createDataBase();
} catch (IOException mIOException) {
Log.e(TAG, mIOException.toString() + " UnableToCreateDatabase");
throw new Error("UnableToCreateDatabase");
}
return this;
}
public TestAdapter open() throws SQLException {
try {
mDbHelper.openDataBase();
mDbHelper.close();
mDb = mDbHelper.getReadableDatabase();
} catch (SQLException mSQLException) {
Log.e(TAG, "open >>"+ mSQLException.toString());
throw mSQLException;
}
return this;
}
public void close() {
mDbHelper.close();
}
public Cursor getTestData() {
try {
String sql ="SELECT * FROM myTable";
Cursor mCur = mDb.rawQuery(sql, null);
if (mCur != null) {
mCur.moveToNext();
}
return mCur;
} catch (SQLException mSQLException) {
Log.e(TAG, "getTestData >>"+ mSQLException.toString());
throw mSQLException;
}
}
}
Now you can use it like:
TestAdapter mDbHelper = new TestAdapter(urContext);
mDbHelper.createDatabase();
mDbHelper.open();
Cursor testdata = mDbHelper.getTestData();
mDbHelper.close();
EDIT: Thanks to JDx
For Android 4.1 (Jelly Bean), change:
DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
to:
DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
in the DataHelper class, this code will work on Jelly Bean 4.2 multi-users.
EDIT: Instead of using hardcoded path, we can use
DB_PATH = context.getDatabasePath(DB_NAME).getAbsolutePath();
which will give us the full path to the database file and works on all Android versions
First : npm install mongoose-timestamp
Next: let Timestamps = require('mongoose-timestamp')
Next: let MySchema = new Schema
Next: MySchema.plugin(Timestamps)
Next : const Collection = mongoose.model('Collection',MySchema)
Then you can use the Collection.createdAt
or Collection.updatedAt
anywhere your want.
Created on: Date Of The Week Month Date Year 00:00:00 GMT
Time is in this format.
To summarize the conversation in the comments:
There is no need to use simplejson
library, the same library is included with Python as the json
module.
There is no need to decode a response from UTF8 to unicode, the simplejson
/ json
.loads()
method can handle UTF8 encoded data natively.
pycurl
has a very archaic API. Unless you have a specific requirement for using it, there are better choices.
requests
offers the most friendly API, including JSON support. If you can, replace your call with:
import requests
return requests.get(url).json()
You can create a button in window1 and double click on it. It will create a new click handler, where inside you can write something like this:
var window2 = new Window2();
window2.Show();
$('selector').attr('id')
will return the id of the first matched element. Reference.
If your matched set contains more than one element, you can use the conventional .each
iterator to return an array containing each of the ids:
var retval = []
$('selector').each(function(){
retval.push($(this).attr('id'))
})
return retval
Or, if you're willing to get a little grittier, you can avoid the wrapper and use the .map
shortcut.
return $('.selector').map(function(index,dom){return dom.id})
maybe you need to download toolchain. This error occurs when you don't have right version of swift compiler.
There are a couple of options I can think of.
array[100]
without having to walk through 1-99
first. And it might not be that handy for you to use either.It is hard to say what option would be best in your situation. Simply creating a large array is ofcourse one of the easiest solutions and shouldn't give you much problems unless it's really large.
Install mysysgit. (Same as Greg Hewgill's answer.)
Install Tortoisegit. (Tortoisegit requires mysysgit or something similiar like Cygwin.)
After TortoiseGit is installed, right-click on a folder, select Git Clone..., then enter the Url of the repository, then click Ok.
This answer is not any better than just installing mysysgit, but you can avoid the dreaded command line. :)
I've successfully done this for my website.
Only exception is, the SeaMonkey browser requires HTML code inserted in your <head>
; whereas, the other browsers will still display the favicon.ico without any HTML insertion. Also, any browser other than IE may use other types of images, not just the .ico format. I hope this helps.
input = {"A":"a", "B":"b", "C":"c"}
output = {k:v for (k,v) in input.items() if key_satifies_condition(k)}
I am reading a book (Effective Python) by Brett Slatkin and he shows another way to iterate over a list and also know the index of the current item in the list but he suggests that it is better not to use it and to use enumerate
instead.
I know you asked what enumerate means, but when I understood the following, I also understood how enumerate
makes iterating over a list while knowing the index of the current item easier (and more readable).
list_of_letters = ['a', 'b', 'c']
for i in range(len(list_of_letters)):
letter = list_of_letters[i]
print (i, letter)
The output is:
0 a
1 b
2 c
I also used to do something, even sillier before I read about the enumerate
function.
i = 0
for n in list_of_letters:
print (i, n)
i += 1
It produces the same output.
But with enumerate
I just have to write:
list_of_letters = ['a', 'b', 'c']
for i, letter in enumerate(list_of_letters):
print (i, letter)
write .htaccess
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
final Pattern pattern = Pattern.compile("tag\\](.+?)\\[/tag");
final Matcher matcher = pattern.matcher("[tag]String I want to extract[/tag]");
matcher.find();
System.out.println(matcher.group(1));
Try this:
find /var/tmp -mtime +2 -a -mtime -8 -ls
to find files older than 2 days but not older than 8 days.
//Do this
int IS_NULL_PTR(char *k){
memset(&k, k, sizeof k);
if(k) { return 71; } ;
return 72;
}
int PRINT_PTR_SAFE(char *KR){
char *E=KR;;
if (IS_NULL_PTR(KR)==71){
printf("%s\r\n",KR);
} else {
printf("%s","(null)\r\n");
}
}
int main(int argc,char *argv[]){
int i=0;
char *A=malloc(sizeof(char)*9);
;strcpy(A,"hello world");
for (i=((int)(A))-10;i<1e+40;i++){
PRINT_PTR_SAFE(i);
}
}
//Then watch the show!
//Edit as you wish. Just credit me if you really want more of this.
Expressions:
objects
and operators
.<object><operator><object>
2.0 + 3
is an expression which evaluates to 5.0
and has a type float
associated with it.
Statements
Statements are composed of expression(s). It can span multiple lines.
A colleague of mine experienced this issue today. We tried many of the recommendations here and none worked except the solution described below.
Project builds fine but Intellisense fails to recognize certain types and marks particular using
statements as invalid.
Change the 'Solutions Platform' (in VS 2017 this is the dropdown next to the Solution Configuration dropdown and has values such as x86, x64, AnyCPU, Mixed Platforms, etc.) to AnyCPU.
The platform for your project may vary, but it seems as though some references may not be valid for all platforms.
Since struct instances are allocated on stack, and class instances are allocated on heap, structs can sometimes be drastically faster.
However, you should always measure it yourself and decide based on your unique use case.
Consider the following example, which demonstrates 2 strategies of wrapping Int
data type using struct
and class
. I am using 10 repeated values are to better reflect real world, where you have multiple fields.
class Int10Class {
let value1, value2, value3, value4, value5, value6, value7, value8, value9, value10: Int
init(_ val: Int) {
self.value1 = val
self.value2 = val
self.value3 = val
self.value4 = val
self.value5 = val
self.value6 = val
self.value7 = val
self.value8 = val
self.value9 = val
self.value10 = val
}
}
struct Int10Struct {
let value1, value2, value3, value4, value5, value6, value7, value8, value9, value10: Int
init(_ val: Int) {
self.value1 = val
self.value2 = val
self.value3 = val
self.value4 = val
self.value5 = val
self.value6 = val
self.value7 = val
self.value8 = val
self.value9 = val
self.value10 = val
}
}
func + (x: Int10Class, y: Int10Class) -> Int10Class {
return IntClass(x.value + y.value)
}
func + (x: Int10Struct, y: Int10Struct) -> Int10Struct {
return IntStruct(x.value + y.value)
}
Performance is measured using
// Measure Int10Class
measure("class (10 fields)") {
var x = Int10Class(0)
for _ in 1...10000000 {
x = x + Int10Class(1)
}
}
// Measure Int10Struct
measure("struct (10 fields)") {
var y = Int10Struct(0)
for _ in 1...10000000 {
y = y + Int10Struct(1)
}
}
func measure(name: String, @noescape block: () -> ()) {
let t0 = CACurrentMediaTime()
block()
let dt = CACurrentMediaTime() - t0
print("\(name) -> \(dt)")
}
Code can be found at https://github.com/knguyen2708/StructVsClassPerformance
UPDATE (27 Mar 2018):
As of Swift 4.0, Xcode 9.2, running Release build on iPhone 6S, iOS 11.2.6, Swift Compiler setting is -O -whole-module-optimization
:
class
version took 2.06 secondsstruct
version took 4.17e-08 seconds (50,000,000 times faster)(I no longer average multiple runs, as variances are very small, under 5%)
Note: the difference is a lot less dramatic without whole module optimization. I'd be glad if someone can point out what the flag actually does.
UPDATE (7 May 2016):
As of Swift 2.2.1, Xcode 7.3, running Release build on iPhone 6S, iOS 9.3.1, averaged over 5 runs, Swift Compiler setting is -O -whole-module-optimization
:
class
version took 2.159942142sstruct
version took 5.83E-08s (37,000,000 times faster)Note: as someone mentioned that in real-world scenarios, there will be likely more than 1 field in a struct, I have added tests for structs/classes with 10 fields instead of 1. Surprisingly, results don't vary much.
ORIGINAL RESULTS (1 June 2014):
(Ran on struct/class with 1 field, not 10)
As of Swift 1.2, Xcode 6.3.2, running Release build on iPhone 5S, iOS 8.3, averaged over 5 runs
class
version took 9.788332333sstruct
version took 0.010532942s (900 times faster)OLD RESULTS (from unknown time)
(Ran on struct/class with 1 field, not 10)
With release build on my MacBook Pro:
class
version took 1.10082 secstruct
version took 0.02324 sec (50 times faster)In Visual Studio:
Tools -> Nuget Package Manager -> Package Manager Console.
In PM:
Install-Package NuGet.CommandLine
Close Visual Studio and open it again.
if the database is maintained by you then simply create a new database and import the data from the old one. the collation problem is solved!!!!!
so simple :
outline-color : blue !important;
the whole CSS for my react-boostrap button is:
.custom-btn { font-size:1.9em; background: #2f5bff; border: 2px solid #78e4ff; border-radius: 3px; padding: 50px 70px; outline-color : blue !important; text-transform: uppercase; user-select: auto; -moz-box-shadow: inset 0 0 4px rgba(0,0,0,0.2); -webkit-box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.2); -webkit-border-radius: 3px; -moz-border-radius: 3px; }
Visual Studio 2015 RC, has LocalDb 12 installed, similar instructions to before but still shouldn't be required to know 'magic', before hand to use this, the default instance should have been turned on ... Rant complete, no for solution:
cmd> sqllocaldb start
Which will display
LocalDB instance "MSSQLLocalDB" started.
Your instance name might differ. Either way pop over to VS and open Server Explorer, right click Data Connections, choose Add, choose SQL Server, in the server name type:
(localdb)\MSSQLLocalDB
Without entering in a DB name, click 'Test Connection'.
Here, instead of making navigation bar transparent, remove any color attributes from the navigation bar to make the background visible.
Strangely, I came across this thinking that I needed a transparent color, but all I needed is to remove the color attributes.
.some-class{
background-color: #fafafa;
}
to
.some-class{
}
$("#DateOfBirth").datepicker({
yearRange: "-100:+0",
changeMonth: true,
changeYear: true,
});
yearRange: '1950:2013', // specifying a hard coded year range or this way
yearRange: "-100:+0", // last hundred years
It will help to show drop down for year and month selection.
Rather than defining contact_email
within app.config
, define it in a parameters
entry:
parameters:
contact_email: [email protected]
You should find the call you are making within your controller now works.
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
I also found that it failed when I tried to load the XIB with a name like @"MyFile.xib". When I just used @"MyFile" it worked - apparently it always adds the extension. But the error message just said it couldn't find MyFIle.xib in the bundle - if it had said MyFile.xib.xib, that would have been a big clue.
Hey if you want to apply Material theme for only android 5.0 then you can add this theme in it
<style name="AppHomeTheme" parent="@android:style/Theme.Material.Light">
<!-- customize the color palette -->
<item name="android:colorPrimary">@color/blue_dark_bg</item>
<item name="android:colorPrimaryDark">@color/blue_status_bar</item>
<item name="android:colorAccent">@color/blue_color_accent</item>
<item name="android:textColor">@android:color/white</item>
<item name="android:textColorPrimary">@android:color/white</item>
<item name="android:actionMenuTextColor">@android:color/black</item>
</style>
Here below line is responsibly for text color of Actionbar of Material design.
<item name="android:textColorPrimary">@android:color/white</item>
I know this post is really old, but I have to reply because although BalusC's answer is marked as correct, it's not completely correct.
You have to write the query adding "[]" to foo like this:
foo[]=val1&foo[]=val2&foo[]=val3
If I recall correctly, 'make' uses timestamps (file modification time) to determine whether or not a target is up to date. A common way to force a re-build is to update that timestamp, using the 'touch' command. You could try invoking 'touch' in your makefile to update the timestamp of one of the targets (perhaps one of those sub-makefiles), which might force Make to execute that command.
If you've included the file correctly and file exists and still getting error:
Then make sure:
Your included file contains the class and is not defined within any namespace.
If the class is in a namespace then:
instead of new YourClass()
you've to do new YourNamespace\YourClass()
I had this problem. Accidentally I deleted this
xmlns:tools="http://schemas.android.com/tools"
which started causing build errors all over the project in my XML files as well as my Java files. As soon as I retyped what I deleted, it worked again :)
create two tabs, one with the formulas and then a second where you paste link the entire table. the second tab should have no problems when sorting!
ul li{
display: inline;
}
For more see the basic list options and a basic horizontal list at listamatic. (thanks to Daniel Straight below for the links).
Also, as pointed out in the comments, you probably want styling on the ul and whatever elements go inside the li's and the li's themselves to get things to look nice.
I've been working on a function to work within a library for a client, and have been having a lot of trouble keeping the UI responsive during the sorts (even with only a few hundred results).
The function has to resort the entire table each AJAX pagination, as new data may require injection further up. This is what I had so far:
table
is the ID of the table being sorted.sort-attribute
, sort-direction
and the column attribute column
are all pre-set.Using some of the details above I managed to improve performance a bit.
function sorttable(table) {
var context = $('#' + table), tbody = $('#' + table + ' tbody'), sortfield = $(context).data('sort-attribute'), c, dir = $(context).data('sort-direction'), index = $(context).find('thead th[data-column="' + sortfield + '"]').index();
if (!sortfield) {
sortfield = $(context).data('id-attribute');
};
switch (dir) {
case "asc":
tbody.find('tr').sort(function (a, b) {
var sortvala = parseFloat($(a).find('td:eq(' + index + ')').text());
var sortvalb = parseFloat($(b).find('td:eq(' + index + ')').text());
// if a < b return 1
return sortvala < sortvalb ? 1
// else if a > b return -1
: sortvala > sortvalb ? -1
// else they are equal - return 0
: 0;
}).appendTo(tbody);
break;
case "desc":
default:
tbody.find('tr').sort(function (a, b) {
var sortvala = parseFloat($(a).find('td:eq(' + index + ')').text());
var sortvalb = parseFloat($(b).find('td:eq(' + index + ')').text());
// if a < b return 1
return sortvala > sortvalb ? 1
// else if a > b return -1
: sortvala < sortvalb ? -1
// else they are equal - return 0
: 0;
}).appendTo(tbody);
break;
}
In principle the code works perfectly, but it's painfully slow... are there any ways to improve performance?
BUILDING Again on Nathan and JB's Answer:
How To Launch App From url w/o Extra Click If you prefer a solution that does not include the interim step of clicking a link, the following can be used. With this javascript, I was able to return a Httpresponse object from Django/Python that successfully launches an app if it is installed or alternatively launches the app store in the case of a time out. Note I also needed to adjust the timeout period from 500 to 100 in order for this to work on an iPhone 4S. Test and tweak to get it right for your situation.
<html>
<head>
<meta name="viewport" content="width=device-width" />
</head>
<body>
<script type="text/javascript">
// To avoid the "protocol not supported" alert, fail must open another app.
var appstorefail = "itms://itunes.apple.com/us/app/facebook/id284882215?mt=8&uo=6";
var loadedAt = +new Date;
setTimeout(
function(){
if (+new Date - loadedAt < 2000){
window.location = appstorefail;
}
}
,100);
function LaunchApp(){
window.open("unknown://nowhere","_self");
};
LaunchApp()
</script>
</body>
</html>
The interface
keyword indicates that you are declaring a traditional interface class in Java.
The @interface
keyword is used to declare a new annotation type.
See docs.oracle tutorial on annotations for a description of the syntax.
See the JLS if you really want to get into the details of what @interface
means.
DECLARE @STR VARCHAR(400)
DECLARE @specialchars VARCHAR(50) = '%[~,@,#,$,%,&,*,(,),!^?:]%'
SET @STR = '1, 45 4,3 68.00-'
WHILE PATINDEX( @specialchars, @STR ) > 0
---Remove special characters using Replace function
SET @STR = Replace(Replace(REPLACE( @STR, SUBSTRING( @STR, PATINDEX( @specialchars, @STR ), 1 ),''),'-',''), ' ','')
SELECT @STR
What worked for me was stopping the Internet Information Services (IIS). If you are using Windows 7, click on your Start button and in your search box, type "iis". Click on "Internet Information Services (IIS) Manager". When the window pops up, and assuming you've got none of the icons selected, you should just be able to click Stop on the right action pane. My XAMPP Apache started right up. Hope it all worked out for you.
For people using Tiny Core Linux, you also need to install libtool-dev
as it has the *.m4 files needed for libtoolize
.
I had a similar problem, and being the newbie that I am it took me a while to figure out but I learned the user must have a login in SSMS. I created the logins with the following parameters:
I'm not saying this is the best way to do it, just what worked for me. Hope this helps
If you are using "n" library @ https://github.com/tj/n . Do the following
echo $NODE_PATH
If node path is empty, then
sudo n latest - sudo is optional depending on your system
After switching Node.js versions using n, npm may not work properly.
curl -0 -L https://npmjs.com/install.sh | sudo sh
echo NODE_PATH
You should see your Node Path now. Else, it might be something else
Based on the link provided by @better_use_mkstemp, here's a fiddle where nested iframe resizes to fill parent div: http://jsfiddle.net/orlenko/HNyJS/
Html:
<div id="content">
<iframe src="http://www.microsoft.com" name="frame2" id="frame2" frameborder="0" marginwidth="0" marginheight="0" scrolling="auto" onload="" allowtransparency="false"></iframe>
</div>
<div id="block"></div>
<div id="header"></div>
<div id="footer"></div>
Relevant parts of CSS:
div#content {
position: fixed;
top: 80px;
left: 40px;
bottom: 25px;
min-width: 200px;
width: 40%;
background: black;
}
div#content iframe {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
height: 100%;
width: 100%;
}
If you set the AllowsTransparency
property on the Window
(even without setting any transparency values) the border disappears and you can only resize via the grip.
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="640" Height="480"
WindowStyle="None"
AllowsTransparency="True"
ResizeMode="CanResizeWithGrip">
<!-- Content -->
</Window>
Result looks like:
Any browsers not supported Date.now, you can use this for get current date time:
currentTime = Date.now() || +new Date()
If you are using eclipse try:
Window > Preferences > Android > Launch
Default emulator options: -dns-server 8.8.8.8,8.8.4.4
I figured out myself.
cmp
calls ComputeBetasAndNuHat
which returns a list which has objective
as minusloglik
So I can change the function cmp
to get this value.
Have you taken a look at this Java Tutorial?
Further, I'd advise you to stay the heck away from playing with this kind of stuff in real software. It's good to play with it so you know what it is, but concurrency has pitfalls all over the place. It's better to use higher level abstractions and synchronized collections or JMS queues if you are building software for other people.
That is at least what I do. I'm not a concurrency expert so I stay away from handling threads by hand wherever possible.
I have an use case where nothing else helped as the solution from Aubin. I adapted the method and changed it by removing and adding an item to the tables' item list as it works in the end only reliable with this hack, the column visible toggle did the job only the first time.
I reported it also in the Jira task: https://javafx-jira.kenai.com/browse/RT-22463
public <T> void tableItemsRefresh(final ObservableList<T> items) {
if (items == null || items.size() == 0)
return;
int idx = items.size() -1;
final T item = items.get(idx);
items.remove(idx);
new Timer().schedule(new TimerTask() {
@Override
public void run() {
Platform.runLater(new Runnable() {
@Override
public void run() {
items.add(item);
}
});
}
}, 100);
}
I also had this problem. To sort out the problem of spaces in the middle of the string this line of code always works:
String field = field.replaceAll("\\s+", "");
if you are using Android device monitor and android emulator : I have accessed following way: Data/Media/0/
That's the for each loop syntax. It is looping through each object in the collection returned by objectListing.getObjectSummaries()
.
I'm using db2 7.1 and SQuirrel. This is the only query that worked for me.
select * from SYSIBM.tables where table_schema = 'my_schema' and table_type = 'BASE TABLE';
Check the parse_string
function http://php.net/manual/en/function.parse-str.php
It will return all the variables from a query string, including arrays.
Example from php.net:
<?php
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str);
echo $first; // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz
parse_str($str, $output);
echo $output['first']; // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz
?>
I've been working on improving the excellent solution from speedplane, and came up with this. It manages the height, including setting the margin such that the text should be centered correctly vertically.
This uses the same function to get the width, as it seems to work the best, but it uses a different function to get the height, as the height isn't provided anywhere. There are some corrections that need to be made, but I figured out a way to do that, while looking pleasing to the eye.
import android.content.Context;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.TextView;
public class FontFitTextView extends TextView {
public FontFitTextView(Context context) {
super(context);
initialize();
}
public FontFitTextView(Context context, AttributeSet attrs) {
super(context, attrs);
initialize();
}
private void initialize() {
mTestPaint = new Paint();
mTestPaint.set(this.getPaint());
//max size defaults to the initially specified text size unless it is too small
}
/* Re size the font so the specified text fits in the text box
* assuming the text box is the specified width.
*/
private void refitText(String text, int textWidth,int textHeight)
{
if (textWidth <= 0)
return;
int targetWidth = textWidth - this.getPaddingLeft() - this.getPaddingRight();
int targetHeight = textHeight - this.getPaddingTop() - this.getPaddingBottom();
float hi = Math.min(targetHeight,100);
float lo = 2;
final float threshold = 0.5f; // How close we have to be
Rect bounds = new Rect();
mTestPaint.set(this.getPaint());
while((hi - lo) > threshold) {
float size = (hi+lo)/2;
mTestPaint.setTextSize(size);
mTestPaint.getTextBounds(text, 0, text.length(), bounds);
if((mTestPaint.measureText(text)) >= targetWidth || (1+(2*(size+(float)bounds.top)-bounds.bottom)) >=targetHeight)
hi = size; // too big
else
lo = size; // too small
}
// Use lo so that we undershoot rather than overshoot
this.setTextSize(TypedValue.COMPLEX_UNIT_PX,(float) lo);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
int height = getMeasuredHeight();
refitText(this.getText().toString(), parentWidth,height);
this.setMeasuredDimension(parentWidth, height);
}
@Override
protected void onTextChanged(final CharSequence text, final int start, final int before, final int after) {
refitText(text.toString(), this.getWidth(),this.getHeight());
}
@Override
protected void onSizeChanged (int w, int h, int oldw, int oldh) {
if (w != oldw) {
refitText(this.getText().toString(), w,h);
}
}
//Attributes
private Paint mTestPaint;
}
One general way to construct set in iterative way like this:
aset = {e for e in alist}
The easiest thing i did was,
changed my Indentation to Tabs
and it resolved my problem.
You can do the same,
to Spaces
as well as per your need.
Mentioned the snapshot of the same.
As said before, with JPA, in order to have the chance to have extra columns, you need to use two OneToMany associations, instead of a single ManyToMany relationship. You can also add a column with autogenerated values; this way, it can work as the primary key of the table, if useful.
For instance, the implementation code of the extra class should look like that:
@Entity
@Table(name = "USER_SERVICES")
public class UserService{
// example of auto-generated ID
@Id
@Column(name = "USER_SERVICES_ID", nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long userServiceID;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "USER_ID")
private User user;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "SERVICE_ID")
private Service service;
// example of extra column
@Column(name="VISIBILITY")
private boolean visibility;
public long getUserServiceID() {
return userServiceID;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Service getService() {
return service;
}
public void setService(Service service) {
this.service = service;
}
public boolean getVisibility() {
return visibility;
}
public void setVisibility(boolean visibility) {
this.visibility = visibility;
}
}
Try
import sys
print(sys.version)
This prints the full version information string. If you only want the python version number, then Bastien Léonard's solution is the best. You might want to examine the full string and see if you need it or portions of it.
Keep in mind that international users may be using a decimal separator other than .
in which case values can get mixed up or just become nil when using intValue
on a string.
For example, in the UK 1.23
is written 1,23
, so the number 1.777
would be input by user as 1,777
, which, as .intValue
, will be 1777
not 1
(truncated).
I've made a macro that will convert input text to an NSNumber based on a locale argument which can be nil (if nil it uses device current locale).
#define stringToNumber(__string, __nullable_locale) (\
(^NSNumber *(void){\
NSLocale *__locale = __nullable_locale;\
if (!__locale) {\
__locale = [NSLocale currentLocale];\
}\
NSString *__string_copy = [__string stringByReplacingOccurrencesOfString:__locale.groupingSeparator withString:@""];\
__string_copy = [__string_copy stringByReplacingOccurrencesOfString:__locale.decimalSeparator withString:@"."];\
return @([__string_copy doubleValue]);\
})()\
)
According to Apple documents for swift 4.1 you can use this struct so easily to create a 2D array:
Code sample:
struct Matrix {
let rows: Int, columns: Int
var grid: [Double]
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
grid = Array(repeating: 0.0, count: rows * columns)
}
func indexIsValid(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
subscript(row: Int, column: Int) -> Double {
get {
assert(indexIsValid(row: row, column: column), "Index out of range")
return grid[(row * columns) + column]
}
set {
assert(indexIsValid(row: row, column: column), "Index out of range")
grid[(row * columns) + column] = newValue
}
}
}
With latest ARC for GET request with authentication need to add a raw header named Authorization:authtoken.
Please find the screen shot Get request with authentication and query params
To add Query param click on drop down arrow on left side of URL box.
You can do this in IE:
<script language="VBScript">
Sub myAlert(title, content)
MsgBox content, 0, title
End Sub
</script>
<script type="text/javascript">
myAlert("My custom title", "Some content");
</script>
(Although, I really wish you couldn't.)
Assuming you have people is List of object
Map<String, String> phoneBook=people.stream()
.collect(toMap(Person::getName, Person::getAddress));
Now you need two steps :
1)
people =removeDuplicate(people);
2)
Map<String, String> phoneBook=people.stream()
.collect(toMap(Person::getName, Person::getAddress));
Here is method to remove duplicate
public static List removeDuplicate(Collection<Person> list) {
if(list ==null || list.isEmpty()){
return null;
}
Object removedDuplicateList =
list.stream()
.distinct()
.collect(Collectors.toList());
return (List) removedDuplicateList;
}
Adding full example here
package com.example.khan.vaquar;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class RemovedDuplicate {
public static void main(String[] args) {
Person vaquar = new Person(1, "Vaquar", "Khan");
Person zidan = new Person(2, "Zidan", "Khan");
Person zerina = new Person(3, "Zerina", "Khan");
// Add some random persons
Collection<Person> duplicateList = Arrays.asList(vaquar, zidan, zerina, vaquar, zidan, vaquar);
//
System.out.println("Before removed duplicate list" + duplicateList);
//
Collection<Person> nonDuplicateList = removeDuplicate(duplicateList);
//
System.out.println("");
System.out.println("After removed duplicate list" + nonDuplicateList);
;
// 1) solution Working code
Map<Object, Object> k = nonDuplicateList.stream().distinct()
.collect(Collectors.toMap(s1 -> s1.getId(), s1 -> s1));
System.out.println("");
System.out.println("Result 1 using method_______________________________________________");
System.out.println("k" + k);
System.out.println("_____________________________________________________________________");
// 2) solution using inline distinct()
Map<Object, Object> k1 = duplicateList.stream().distinct()
.collect(Collectors.toMap(s1 -> s1.getId(), s1 -> s1));
System.out.println("");
System.out.println("Result 2 using inline_______________________________________________");
System.out.println("k1" + k1);
System.out.println("_____________________________________________________________________");
//breacking code
System.out.println("");
System.out.println("Throwing exception _______________________________________________");
Map<Object, Object> k2 = duplicateList.stream()
.collect(Collectors.toMap(s1 -> s1.getId(), s1 -> s1));
System.out.println("");
System.out.println("k2" + k2);
System.out.println("_____________________________________________________________________");
}
public static List removeDuplicate(Collection<Person> list) {
if (list == null || list.isEmpty()) {
return null;
}
Object removedDuplicateList = list.stream().distinct().collect(Collectors.toList());
return (List) removedDuplicateList;
}
}
// Model class
class Person {
public Person(Integer id, String fname, String lname) {
super();
this.id = id;
this.fname = fname;
this.lname = lname;
}
private Integer id;
private String fname;
private String lname;
// Getters and Setters
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
@Override
public String toString() {
return "Person [id=" + id + ", fname=" + fname + ", lname=" + lname + "]";
}
}
Results :
Before removed duplicate list[Person [id=1, fname=Vaquar, lname=Khan], Person [id=2, fname=Zidan, lname=Khan], Person [id=3, fname=Zerina, lname=Khan], Person [id=1, fname=Vaquar, lname=Khan], Person [id=2, fname=Zidan, lname=Khan], Person [id=1, fname=Vaquar, lname=Khan]]
After removed duplicate list[Person [id=1, fname=Vaquar, lname=Khan], Person [id=2, fname=Zidan, lname=Khan], Person [id=3, fname=Zerina, lname=Khan]]
Result 1 using method_______________________________________________
k{1=Person [id=1, fname=Vaquar, lname=Khan], 2=Person [id=2, fname=Zidan, lname=Khan], 3=Person [id=3, fname=Zerina, lname=Khan]}
_____________________________________________________________________
Result 2 using inline_______________________________________________
k1{1=Person [id=1, fname=Vaquar, lname=Khan], 2=Person [id=2, fname=Zidan, lname=Khan], 3=Person [id=3, fname=Zerina, lname=Khan]}
_____________________________________________________________________
Throwing exception _______________________________________________
Exception in thread "main" java.lang.IllegalStateException: Duplicate key Person [id=1, fname=Vaquar, lname=Khan]
at java.util.stream.Collectors.lambda$throwingMerger$0(Collectors.java:133)
at java.util.HashMap.merge(HashMap.java:1253)
at java.util.stream.Collectors.lambda$toMap$58(Collectors.java:1320)
at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
at java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
at com.example.khan.vaquar.RemovedDuplicate.main(RemovedDuplicate.java:48)
0 will get printed.
As in C++ true refers to 1 and false refers to 0.
In case, you want to print false instead of 0,then you have to sets the boolalpha format flag for the str stream.
When the boolalpha format flag is set, bool values are inserted/extracted by their textual representation: either true or false, instead of integral values.
#include <iostream>
int main()
{
std::cout << std::boolalpha << false << std::endl;
}
output:
false
(for Xcode 8.x / Xcode 9.x read at the bottom)
Beware of the following issue in in Xcode 7.x, which might be a source of confusion:
Interface Builder does not handle auto-sizing cell set-up properly. Even if your constraints are absolutely valid, IB will still complain and give you confusing suggestions and errors. The reason is that IB is unwilling to change the row's height as your constraints dictate (so that the cell fits around your content). Instead, it keeps the row's height fixed and starts suggesting you change your constraints, which you should ignore.
For example, imagine you've set up everything fine, no warnings, no errors, all works.
Now if you change the font size (in this example I'm changing the description label font size from 17.0 to 18.0).
Because the font size increased, the label now wants to occupy 3 rows (before that it was occupying 2 rows).
If Interface Builder worked as expected, it would resize the cell's height to accommodate the new label height. However what actually happens is that IB displays the red auto-layout error icon and suggest that you modify hugging/compression priorities.
You should ignore these warnings. What you can* do instead is to manually change the row's height in (select Cell > Size Inspector > Row Height).
I was changing this height one click at a time (using the up/down stepper) until the red arrow errors disappear! (you will actually get yellow warnings, at which point just go ahead and do 'update frames', it should all work).
* Note that you don't actually have to resolve these red errors or yellow warnings in Interface Builder - at runtime, everything will work correctly (even if IB shows errors/warnings). Just make sure that at runtime in the console log you're not getting any AutoLayout errors.
In fact trying to always update row height in IB is super annoying and sometimes close to impossible (because of fractional values).
To prevent the annoying IB warnings/errors, you can select the views involved and in Size Inspector
for the property Ambiguity
choose Verify Position Only
Xcode 8.x / Xcode 9.x seems to (sometimes) be doing things differently than Xcode 7.x, but still incorrectly. For example even when compression resistance priority
/ hugging priority
are set to required (1000), Interface Builder might stretch or clip a label to fit the cell (instead of resizing cell height to fit around the label). And in such a case it might not even show any AutoLayout warnings or errors. Or sometimes it does exactly what Xcode 7.x did, described above.
Note: You don't need to check if your service is running, CheckIfServiceIsRunning()
, because bindService()
will start it if it isn't running.
Also: if you rotate the phone you don't want it to bindService()
again, because onCreate()
will be called again. Be sure to define onConfigurationChanged()
to prevent this.
devnull is right;
sudo update-alternatives --config x-terminal-emulator
Yes - it means you're using \n
as the line break instead of \r\n
. Notepad only understands the latter.
(Note that Environment.NewLine
suggested by others is fine if you want the platform default - but if you're serving from Mono and definitely want \r\n
, you should specify it explicitly.)
Overview of the services used by all sessions provides the distionary view v$session
(or gv$session
for RAC databases) in the column SERVICE_NAME
.
To limit the information to the connected session use the SID from the view V$MYSTAT
:
select SERVICE_NAME from gv$session where sid in (
select sid from V$MYSTAT)
If the name is SYS$USERS
the session is connected to a default service, i.e. in the connection string no explicit service_name was specified.
To see what services are available in the database use following queries:
select name from V$SERVICES;
select name from V$ACTIVE_SERVICES;
Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Terminal Server\TSAppAllowList] "fDisabledAllowList"=dword:00000001
1.2 Right click on the file and click Merge, Yes, Ok.
remoteapplicationmode:i:1 remoteapplicationname:s:This will be the optional description of the app remoteapplicationprogram:s:Relative or absolute path to the app (Example: taskmgr or C:\Windows\system32\taskmgr.exe) remoteapplicationcmdline:s:Here you'd put any optional application parameters
remoteapplicationmode:i:1 remoteapplicationname:s: remoteapplicationprogram:s:mspaint remoteapplicationcmdline:s:
2.2 Enter your username and password and connect.
3. Now you can use your RemoteApp without any issues as if it was running on your local machine
StringBuffer is mutable. It can change in terms of length and content. StringBuffers are thread-safe, meaning that they have synchronized methods to control access so that only one thread can access a StringBuffer object's synchronized code at a time. Thus, StringBuffer objects are generally safe to use in a multi-threaded environment where multiple threads may be trying to access the same StringBuffer object at the same time.
StringBuilder The StringBuilder class is very similar to StringBuffer, except that its access is not synchronized so that it is not thread-safe. By not being synchronized, the performance of StringBuilder can be better than StringBuffer. Thus, if you are working in a single-threaded environment, using StringBuilder instead of StringBuffer may result in increased performance. This is also true of other situations such as a StringBuilder local variable (ie, a variable within a method) where only one thread will be accessing a StringBuilder object.
If you aren't sure how to run a rake task, first find out first what tasks you have and it will also list the commands to run the tasks.
Run rake --tasks
on the terminal.
It will list the tasks like the following:
rake gobble:dev:prime
rake gobble:dev:reset_number_of_kits
rake gobble:dev:scrub_prod_data
You can then run your task with: rake gobble:dev:prime
as listed.
ES6
Arrow functions:In javascript the =>
is the symbol of an arrow function expression. A arrow function expression does not have its own this
binding and therefore cannot be used as a constructor function. for example:
var words = 'hi from outside object';_x000D_
_x000D_
let obj = {_x000D_
words: 'hi from inside object',_x000D_
talk1: () => {console.log(this.words)},_x000D_
talk2: function () {console.log(this.words)}_x000D_
}_x000D_
_x000D_
obj.talk1(); // doesn't have its own this binding, this === window_x000D_
obj.talk2(); // does have its own this binding, this is obj
_x000D_
{}
and the return
statementFor example:
let times2 = val => val * 2; _x000D_
// It is on the same line and returns an expression therefore the {} are ommited and the expression returns implictly_x000D_
// there also is only one argument, therefore the parentheses around the argument are omitted_x000D_
_x000D_
console.log(times2(3));
_x000D_
I have implemented a tiny benchmark (please find the code on Gist) to evaluate the pandas' concat
and append
. I updated the code snippet and the results after the comment by ssk08
- thanks alot!
The benchmark ran on a Mac OS X 10.13 system with Python 3.6.2 and pandas 0.20.3.
+--------+---------------------------------+---------------------------------+ | | ignore_index=False | ignore_index=True | +--------+---------------------------------+---------------------------------+ | size | append | concat | append/concat | append | concat | append/concat | +--------+--------+--------+---------------+--------+--------+---------------+ | small | 0.4635 | 0.4891 | 94.77 % | 0.4056 | 0.3314 | 122.39 % | +--------+--------+--------+---------------+--------+--------+---------------+ | medium | 0.5532 | 0.6617 | 83.60 % | 0.3605 | 0.3521 | 102.37 % | +--------+--------+--------+---------------+--------+--------+---------------+ | large | 0.9558 | 0.9442 | 101.22 % | 0.6670 | 0.6749 | 98.84 % | +--------+--------+--------+---------------+--------+--------+---------------+
Using ignore_index=False
append
is slightly faster, with ignore_index=True
concat
is slightly faster.
tl;dr
No significant difference between concat
and append
.
It is very simple. Just go to Edit=>Line=>Reindent
this code works with me
ImageView carView = (ImageView) v.findViewById(R.id.car_icon);
byte[] decodedString = Base64.decode(picture, Base64.NO_WRAP);
InputStream input=new ByteArrayInputStream(decodedString);
Bitmap ext_pic = BitmapFactory.decodeStream(input);
carView.setImageBitmap(ext_pic);
What are you using to compile this? If there's an undefined reference error, usually it's because the .o file (which gets created from the .cpp file) doesn't exist and your compiler/build system is not able to link it.
Also, in your card.cpp, the function should be Card::Card()
instead of void Card
. The Card::
is scoping; it means that your Card()
function is a member of the Card class (which it obviously is, since it's the constructor for that class). Without this, void Card is just a free function. Similarly,
void Card(Card::Rank rank, Card::Suit suit)
should be
Card::Card(Card::Rank rank, Card::Suit suit)
Also, in deck.cpp, you are saying #include "Deck.h"
even though you referred to it as deck.h. The includes are case sensitive.
I know, its old a post to answer but like I came across searching for the same post, someone else might turn here as well
By adding : colour in ggplot function , I could achieve the lines with different colors related to the group present in the plot.
ggplot(data=Set6, aes(x=Semana, y=Net_Sales_in_pesos, group = Agencia_ID, colour = as.factor(Agencia_ID)))
and
geom_line()
Reflection gives you the ability to write more generic code. It allows you to create an object at runtime and call its method at runtime. Hence the program can be made highly parameterized. It also allows introspecting the object and class to detect its variables and method exposed to the outer world.
To @Cerebrus solution: for H2 for strings "+" is not supported. So:
REPLACE(string, CHAR(13) || CHAR(10), 'replacementString')
Very interesting question.
I don't see any difference w.r.t safety or versatility, since you can do the same thing with pointer or reference. I also don't think there is any visible difference in performance since references are implemented by pointers.
But I think using reference is better because it is consistent with the standard library. For example, chaining in iostream is done by reference rather than pointer.
Instead of taking the HttpServletRequest
object in every method, keep in controllers' context by auto-wiring via the constructor. Then you can access from all methods of the controller.
public class OAuth2ClientController {
@Autowired
private OAuth2ClientService oAuth2ClientService;
private HttpServletRequest request;
@Autowired
public OAuth2ClientController(HttpServletRequest request) {
this.request = request;
}
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<String> createClient(@RequestBody OAuth2Client client) {
System.out.println(request.getRequestURI());
System.out.println(request.getHeader("Content-Type"));
return ResponseEntity.ok();
}
}
The code that worked for me is:
ThisWorkbook.Sheets("sheetName").Activate
The simplest answer is:
On whichever method you declare @Transactional
the boundary of transaction starts and boundary ends when method completes.
If you are using JPA call then all commits are with in this transaction boundary.
Lets say you are saving entity1, entity2 and entity3. Now while saving entity3 an exception occur, then as enitiy1 and entity2 comes in same transaction so entity1 and entity2 will be rollback with entity3.
Transaction :
- entity1.save
- entity2.save
- entity3.save
Any exception will result in rollback of all JPA transactions with DB.Internally JPA transaction are used by Spring.
By default, Xcode sets the bundle identifier to the bundle/company identifier that you set during project creation + project name.
This is similar to what you see in the Project > Summary screen.
But you can change this in the Project > Info screen. (This is the Info.plist.)
I saw this thread when I was trying to split a file in files with 100 000 lines. A better solution than sed for that is:
split -l 100000 database.sql database-
It will give files like:
database-aaa
database-aab
database-aac
...
you'd use another join, something along these lines:
SELECT toD.dom_url AS ToURL,
fromD.dom_url AS FromUrl,
rvw.*
FROM reviews AS rvw
LEFT JOIN domain AS toD
ON toD.Dom_ID = rvw.rev_dom_for
LEFT JOIN domain AS fromD
ON fromD.Dom_ID = rvw.rev_dom_from
EDIT:
All you're doing is joining in the table multiple times. Look at the query in the post: it selects the values from the Reviews tables (aliased as rvw), that table provides you 2 references to the Domain table (a FOR and a FROM).
At this point it's a simple matter to left join the Domain table to the Reviews table. Once (aliased as toD) for the FOR, and a second time (aliased as fromD) for the FROM.
Then in the SELECT list, you will select the DOM_URL fields from both LEFT JOINS of the DOMAIN table, referencing them by the table alias for each joined in reference to the Domains table, and alias them as the ToURL and FromUrl.
For more info about aliasing in SQL, read here.
https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
var unixTimeZero = Date.parse('01 Jan 1970 00:00:00 GMT');
var javaScriptRelease = Date.parse('04 Dec 1995 00:12:00 GMT');
console.log(unixTimeZero);
// expected output: 0
console.log(javaScriptRelease);
// expected output: 818035920000
You can use the TelephonyManager
to do this:
TelephonyManager tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
String number = tm.getLine1Number();
The documentation for getLine1Number()
says this method will return null
if the number is "unavailable", but it does not say when the number might be unavailable.
You'll need to give your application permission to make this query by adding the following to your Manifest:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
(You shouldn't use TelephonyManager.getDefault()
to get the TelephonyManager
as that is a private undocumented API call and may change in future.)
Here is very sample solution for check class (hasClass) in Javascript:
const mydivclass = document.querySelector('.mydivclass');
// if 'hasClass' is exist on 'mydivclass'
if(mydivclass.classList.contains('hasClass')) {
// do something if 'hasClass' is exist.
}
Disclaimer: I am from 42matters, who provides this data already on https://42matters.com/api , feel free to check it out or drop us a line.
As lenik mentioned there are open-source libraries that already help with obtaining some data from GPlay. If you want to build one yourself you can try to parse the Google Play App page, but you should pay attention to the following:
So that in mind getting one page metadata is a matter of fetching the page html and parsing it properly. With JSoup you can try:
HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(crawlUrl);
HttpResponse rsp = httpClient.execute(request);
int statusCode = rsp.getStatusLine().getStatusCode();
if (statusCode == 200) {
String content = EntityUtils.toString(rsp.getEntity());
Document doc = Jsoup.parse(content);
//parse content, whatever you need
Element price = doc.select("[itemprop=price]").first();
}
For that very simple use case that should get you started. However, the moment you want to do more interesting stuff, things get complicated:
The list goes on. If you don't want to do all this by yourself, you can consider 42matters API, which supports lookup and search, top google charts, advanced queries and filters. And this for 35 languages and more than 50 countries.
[2]:
I found one way to supply credentials for a https connection on the command line. You just need to specify the complete URL to git pull and include the credentials there:
git pull https://username:[email protected]/my/repository
You do not need to have the repository cloned with the credentials before, this means your credentials don't end up in .git/config
. (But make sure your shell doesn't betray you and stores the command line in a history file.)
It doesn't make any sense to have a named overloaded constructor in an anonymous class, as there would be no way to call it, anyway.
Depending on what you are actually trying to do, just accessing a final local variable declared outside the class, or using an instance initializer as shown by Arne, might be the best solution.
Yes, you can store and view images in Firebase. You can use a filepicker to get the image file. Then you can host the image however you want, I prefer Amazon s3. Once the image is hosted you can display the image using the URL generated for the image.
Hope this helps.
In Swift 3.x, you can set highlighted image when button is selected in the following way:
// Normal state
button.setImage(UIImage(named: "normalImage"), for: .normal)
// Highlighted state (before button is selected)
button.setImage(UIImage(named: "pressedImage"), for: .highlighted)
// Selected state
button.setImage(UIImage(named: "selectedImage"), for: .selected)
// Highlighted state (after button is selected)
button.setImage(UIImage(named: "pressedAfterBeingSelectedImage"),
for: UIControlState.selected.union(.highlighted))
I had a user control which sat on page in a free form way, not constrained by another container, and the contents within the user control would not auto size but expand to the full size of what the user control was handed.
To get the user control to simply size to its content, for height only, I placed it into a grid with on row set to auto size such as this:
<Grid Margin="0,60,10,200">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<controls1:HelpPanel x:Name="HelpInfoPanel"
Visibility="Visible"
Width="570"
HorizontalAlignment="Right"
ItemsSource="{Binding HelpItems}"
Background="#FF313131" />
</Grid>
Python is strongly typed. There are no implicit type conversions.
You have to do one of these:
"asd%d" % 9
"asd" + str(9)
That'd be .delay()
.
If you are doing AJAX stuff tho, you really shouldn't just auto write "done" you should really wait for a response and see if it's actually done.
There are two ways to write case statements, you seem to be using a combination of the two
case a.updatedDate
when 1760 then 'Entered on' + a.updatedDate
when 1710 then 'Viewed on' + a.updatedDate
else 'Last Updated on' + a.updateDate
end
or
case
when a.updatedDate = 1760 then 'Entered on' + a.updatedDate
when a.updatedDate = 1710 then 'Viewed on' + a.updatedDate
else 'Last Updated on' + a.updateDate
end
are equivalent. They may not work because you may need to convert date types to varchars to append them to other varchars.
To generate a certificate on the Apple provisioning profile website, firstly you have to generate keys on your mac, then upload the public key. Apple will generate your certificates with this key. When you download your certificates, tu be able to use them you need to have the private key.
The error "XCode could not find a valid private-key/certificate pair for this profile in your keychain." means you don't have the private key.
Maybe because your Mac was reinstalled, maybe because this key was generated on another Mac. So to be able to use your certificates, you need to find this key and install it on the keychain.
If you can not find it you can generate new keys restart this process on the provisioning profile website and get new certificates you will able to use.
In order to accomplish this, it is best to design fragment construct to receive that data and save that data in its bundle arguments.
class FragmentA extends Fragment{
public static FragmentA newInstance(YourDataClass data) {
FragmentA f = new FragmentA();
Bundle b = new Bundle();
b.putString("data", data);
f.setArguments(b);
return f;
}
}
In order to start the fragment from the class, you can do the following
Fragment newFragment = FragmentA.newInstance(objectofyourclassdata);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
However, the data class must be parceable or serializable.
For full information on fragments and best practices on use of fragments, please spend some time on official docs, it is super useful, at least my experience
https://developer.android.com/guide/components/fragments#java
Sure, use the .format method. E.g.,
print('{:10s} {:3d} {:7.2f}'.format('xxx', 123, 98))
print('{:10s} {:3d} {:7.2f}'.format('yyyy', 3, 1.0))
print('{:10s} {:3d} {:7.2f}'.format('zz', 42, 123.34))
will print
xxx 123 98.00
yyyy 3 1.00
zz 42 123.34
You can adjust the field sizes as desired. Note that .format
works independently of print
to format a string. I just used print to display the strings. Brief explanation:
10s
format a string with 10 spaces, left justified by default
3d
format an integer reserving 3 spaces, right justified by default
7.2f
format a float, reserving 7 spaces, 2 after the decimal point, right justfied by default.
There are many additional options to position/format strings (padding, left/right justify etc), String Formatting Operations will provide more information.
Update for f-string mode. E.g.,
text, number, other_number = 'xxx', 123, 98
print(f'{text:10} {number:3d} {other_number:7.2f}')
For right alignment
print(f'{text:>10} {number:3d} {other_number:7.2f}')
On Windows 10, to create the virtual environment, I replace "pip mkvirtualenv myproject" by "mkvirtualenv myproject" and that works well.
You can do (pre-Java 8):
List<Enum> enumValues = Arrays.asList(Enum.values());
or
List<Enum> enumValues = new ArrayList<Enum>(EnumSet.allOf(Enum.class));
Using Java 8 features, you can map each constant to its name:
List<String> enumNames = Stream.of(Enum.values())
.map(Enum::name)
.collect(Collectors.toList());
> C:\java -X
-Xmixed mixed mode execution (default)
-Xint interpreted mode execution only
-Xbootclasspath:<directories and zip/jar files separated by ;>
set search path for bootstrap classes and resources
-Xbootclasspath/a:<directories and zip/jar files separated by ;>
append to end of bootstrap class path
-Xbootclasspath/p:<directories and zip/jar files separated by ;>
prepend in front of bootstrap class path
-Xnoclassgc disable class garbage collection
-Xincgc enable incremental garbage collection
-Xloggc:<file> log GC status to a file with time stamps
-Xbatch disable background compilation
-Xms<size> set initial Java heap size
-Xmx<size> set maximum Java heap size
-Xss<size> set java thread stack size
-Xprof output cpu profiling data
-Xfuture enable strictest checks, anticipating future default
-Xrs reduce use of OS signals by Java/VM (see documentation)
-Xcheck:jni perform additional checks for JNI functions
-Xshare:off do not attempt to use shared class data
-Xshare:auto use shared class data if possible (default)
-Xshare:on require using shared class data, otherwise fail.
The -X
options are non-standard and subject to change without notice.
(copy-paste)
I suggest to use jQuery:
$('#mydiv')
.css('cursor', 'pointer')
.click(
function(){
alert('Click event is fired');
}
)
.hover(
function(){
$(this).css('background', '#ff00ff');
},
function(){
$(this).css('background', '');
}
);
Every execution of exec
spawns a new process with its own environment. So your second invocation is not connected to the first in any way. It will just change its own working directory and then exit (i.e. it's effectively a no-op).
If you want to compose requests, you'll need to do this within a single call to exec
. Bash allows multiple commands to be specified on a single line if they're separated by semicolons; Windows CMD may allow the same, and if not there's always batch scripts.
As Piotr says, if this example is actually what you're trying to achieve, you can perform the same thing much more efficiently, effectively and platform-safely with the following:
String[] filenames = new java.io.File("C:/").list();
My solution was to use excel (2010).
In a new worksheet, select a cell, then:
Data -> From Other Sources -> From SQL Server
put in the server name, select table, etc,
When you get to the "Import Data" dialog,
click on Properties in the "Connection Properties" dialog,
select the "Definition" tab.
And there Excel nicely displays the Connection String for copying
(or even Export Connection File...)
In javascript there are no block-level scopes
only function-level scopes
:
Read this article about javaScript Scoping and Hoisting.
var deferred = $q.defer();
deferred.count = i;
console.log(deferred.count); // 0,1,2,3,4,5 --< all deferred objects
// some code
.success(function(data){
console.log(deferred.count); // 5,5,5,5,5,5 --< only the last deferred object
deferred.resolve(data);
})
var deferred= $q.defer();
inside a for loop it's hoisted to the top of the function, it means that javascript declares this variable on the function scope outside of the for loop
.closure scope
even after functions are executed.angular.forEach
:Here is a demo plunker: http://plnkr.co/edit/NGMp4ycmaCqVOmgohN53?p=preview
UploadService.uploadQuestion = function(questions){
var promises = [];
angular.forEach(questions , function(question) {
var promise = $http({
url : 'upload/question',
method: 'POST',
data : question
});
promises.push(promise);
});
return $q.all(promises);
}
Array#map
:Here is a demo plunker: http://plnkr.co/edit/KYeTWUyxJR4mlU77svw9?p=preview
UploadService.uploadQuestion = function(questions){
var promises = questions.map(function(question) {
return $http({
url : 'upload/question',
method: 'POST',
data : question
});
});
return $q.all(promises);
}
Tensorflow 2.x support's Eager Execution by default hence Session is not supported.
If you're using the mysql native driver (common since php 5.3), and the mysqli extension, you can accomplish this with an asynchronous query:
<?php
// Here's an example query that will take a long time to execute.
$sql = "
select *
from information_schema.tables t1
join information_schema.tables t2
join information_schema.tables t3
join information_schema.tables t4
join information_schema.tables t5
join information_schema.tables t6
join information_schema.tables t7
join information_schema.tables t8
";
$mysqli = mysqli_connect('localhost', 'root', '');
$mysqli->query($sql, MYSQLI_ASYNC | MYSQLI_USE_RESULT);
$links = $errors = $reject = [];
$links[] = $mysqli;
// wait up to 1.5 seconds
$seconds = 1;
$microseconds = 500000;
$timeStart = microtime(true);
if (mysqli_poll($links, $errors, $reject, $seconds, $microseconds) > 0) {
echo "query finished executing. now we start fetching the data rows over the network...\n";
$result = $mysqli->reap_async_query();
if ($result) {
while ($row = $result->fetch_row()) {
// print_r($row);
if (microtime(true) - $timeStart > 1.5) {
// we exceeded our time limit in the middle of fetching our result set.
echo "timed out while fetching results\n";
var_dump($mysqli->close());
break;
}
}
}
} else {
echo "timed out while waiting for query to execute\n";
var_dump($mysqli->close());
}
The flags I'm giving to mysqli_query accomplish important things. It tells the client driver to enable asynchronous mode, while forces us to use more verbose code, but lets us use a timeout(and also issue concurrent queries if you want!). The other flag tells the client not to buffer the entire result set into memory.
By default, php configures its mysql client libraries to fetch the entire result set of your query into memory before it lets your php code start accessing rows in the result. This can take a long time to transfer a large result. We disable it, otherwise we risk that we might time out while waiting for the buffering to complete.
Note that there's two places where we need to check for exceeding a time limit:
You can accomplish similar in the PDO and regular mysql extension. They don't support asynchronous queries, so you can't set a timeout on the query execution time. However, they do support unbuffered result sets, and so you can at least implement a timeout on the fetching of the data.
For many queries, mysql is able to start streaming the results to you almost immediately, and so unbuffered queries alone will allow you to somewhat effectively implement timeouts on certain queries. For example, a
select * from tbl_with_1billion_rows
can start streaming rows right away, but,
select sum(foo) from tbl_with_1billion_rows
needs to process the entire table before it can start returning the first row to you. This latter case is where the timeout on an asynchronous query will save you. It will also save you from plain old deadlocks and other stuff.
ps - I didn't include any timeout logic on the connection itself.
1. Resource description “Resources” refers to the information returned by an API.
2. Endpoints and methods The endpoints indicate how you access the resource, while the method indicates the allowed interactions (such as GET, POST, or DELETE) with the resource.
Additional info: 3. Parameters Parameters are options you can pass with the endpoint (such as specifying the response format or the amount returned) to influence the response.
4. Request example The request example includes a sample request using the endpoint, showing some parameters configured.
5. Response example and schema The response example shows a sample response from the request example; the response schema defines all possible elements in the response.
Source- Reference link
If you're trying to kill -9 it, you have the correct PID, and nothing happens, then you don't have permissions to kill the process.
Solution:
$ sudo kill -9 PID
Okay, sure enough Mac OS/X does give an error message for this case:
$ kill -9 196
-bash: kill: (196) - Operation not permitted
So, if you're not getting an error message, you somehow aren't getting the right PID.
With RubyMotion / RedPotion, paste this into your TableScreen:
def tableView(_, willDisplayHeaderView: view, forSection: section)
view.textLabel.textColor = rmq.color.your_text_color
view.contentView.backgroundColor = rmq.color.your_background_color
end
Works like a charm!
There isn't any need to write this much. Just put your desired field separator with the -F
option in the AWK command and the column number you want to print segregated as per your mentioned field separator.
echo "1: " | awk -F: '{print $1}'
1
echo "1#2" | awk -F# '{print $1}'
1
From Laravel 6, Now It's working with the following command:
composer create-project --prefer-dist laravel/laravel:^7.0 blog
I would apply this rule to all input fields of type text, so it doesn't need to be duplicated later:
input[type=text]::-ms-clear { display: none; }
One can even get less specific by using just:
::-ms-clear { display: none; }
I have used the later even before adding this answer, but thought that most people would prefer to be more specific than that. Both solutions work fine.
Try TextFX ? TextFX Html Tidy ? Tidy: reindent XML
If you can't try with Eclipse, do right button, source, and correct indent.
If object and dynamical keys: "applications\":{\"1\":\"Element1\",\"2\":\"Element2\"}
Object.keys(myObject).map(function (key, index) {
return myObject[key]
}).join(', ')
The problem based on Chrome is not about the xml namespace which is xmlns="http://www.w3.org/1999/xhtml"
. Without the namesspace attribute, it won't work with IE either.
Because of the security restriction, you have to add the --allow-file-access-from-files
flag when you start the chrome. I think linux/*nix users can do that easily via the terminal but for windows users, you have to open the properties of the Chrome shortcut and add it in the target destination as below;
Right-Click -> Properties -> Target
Here is a sample full path with the flags which I use on my machine;
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files
I hope showing this step-by-step will help windows users for the problem, this is why I've added this post.
There is also another solution to the problem by implementing a layer-list that will act as the background for the LinearLayoout.
Add background_with_shadow.xml file to res/drawable
. Containing:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item >
<shape
android:shape="rectangle">
<solid android:color="@android:color/darker_gray" />
<corners android:radius="5dp"/>
</shape>
</item>
<item android:right="1dp" android:left="1dp" android:bottom="2dp">
<shape
android:shape="rectangle">
<solid android:color="@android:color/white"/>
<corners android:radius="5dp"/>
</shape>
</item>
</layer-list>
Then add the the layer-list as background in your LinearLayout.
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/background_with_shadow"/>
The only solution that works for me in all cases (even if values are strings) is the following :
var enumToString = function(enumType, enumValue) {
for (var enumMember in enumType) {
if (enumType[enumMember]==enumValue) return enumMember
}
}
This can be easily done by using rd
command with two parameters:
rd <folder> /Q /S
/Q - Quiet mode, do not ask if ok to remove a directory tree with /S
/S - Removes all directories and files in the specified directory in addition to the directory itself. Used to remove a directory tree.
you can make it using js file and ajax call. while validating data using js file we can read the text of selected dropdown
$("#dropdownid").val(); for value
$("#dropdownid").text(); for selected value
catch these into two variables and take it as inputs to ajax call for a php file
$.ajax
({
url:"callingphpfile.php",//url of fetching php
method:"POST", //type
data:"val1="+value+"&val2="+selectedtext,
success:function(data) //return the data
{
}
and in php you can get it as
if (isset($_POST["val1"])) {
$val1= $_POST["val1"] ;
}
if (isset($_POST["val2"])) {
$selectedtext= $_POST["val1"];
}
IN HTML 5 action=""
IS NOT SUPPORTED SO DON'T DO THIS. BAD PRACTICE.
If instead you completely negate action altogether it will submit to the same page by default, I believe this is the best practice:
<form>This will submit to the current page</form>
If you are sumbitting the form using php you may want to consider the following. read more about it here.
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Alternatively you could use #
bear in mind though that this will act like an anchor and scroll to the top of the page.
<form action="#">
text doesn't work with len function.
ntext, text, and image data types will be removed in a future version of Microsoft SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead. For more information, see Using Large-Value Data Types.
For example: you populated your UIPickerView with array values, then you wanted
to select a certain array value in the first load of pickerView like "Arizona". Note that the word "Arizona" is at index 2. This how to do it :) Enjoy coding.
NSArray *countryArray =[NSArray arrayWithObjects:@"Alabama",@"Alaska",@"Arizona",@"Arkansas", nil];
UIPickerView *countryPicker=[[UIPickerView alloc]initWithFrame:self.view.bounds];
countryPicker.delegate=self;
countryPicker.dataSource=self;
[countryPicker selectRow:2 inComponent:0 animated:YES];
[self.view addSubview:countryPicker];
This is the sort of thing I'd normally use a scripting language for. It's very useful to have the ability to perform these sorts of transformations very simply using something like Ruby/Perl/Python (insert your favorite scripting language here).
I wouldn't normally use Java for this since it's too heavyweight in terms of development cycle/typing etc.
Note that if you want to be particular in manipulating XML, it's advisable to read the file as XML and manipulate it as such (the above scripting languages have very useful and simple APIs for doing this sort of work). A simple text search/replace can invalidate your file in terms of character encoding etc. As always, it depends on the complexity of your search/replace requirements.
Use the group collection of the Match object, indexing it with the capturing group name, e.g.
foreach (Match m in mc){
MessageBox.Show(m.Groups["link"].Value);
}
If it is "pretty large" file, then access the lines sequentially and don't read the whole file into memory:
with open('largeFile', 'r') as inF:
for line in inF:
if 'myString' in line:
# do_something
You can use the Build Class to get the device information.
For example:
String myDeviceModel = android.os.Build.MODEL;
alternative way:
mail -N
d *
quit
-N
Inhibits the initial display of message headers when reading mail or editing a mail folder.
d *
delete all mails
Yes, I couldn't see how to use 'default' in the migration generator command either but was able to specify a default value for a new string column as follows by amending the generated migration file before applying "rake db:migrate":
class AddColumnToWidgets < ActiveRecord::Migration
def change
add_column :widgets, :colour, :string, default: 'red'
end
end
This adds a new column called 'colour' to my 'Widget' model and sets the default 'colour' of new widgets to 'red'.
I'd recommend you go with REST first - if you're using Java look at JAX-RS and the Jersey implementation. REST is much simpler and easy to interop in many languages.
As others have said in this thread, the problem with SOAP is its complexity when the other WS-* specifications come in and there are countless interop issues if you stray into the wrong parts of WSDL, XSDs, SOAP, WS-Addressing etc.
The best way to judge the REST v SOAP debate is look on the internet - pretty much all the big players in the web space, google, amazon, ebay, twitter et al - tend to use and prefer RESTful APIs over the SOAP ones.
The other nice approach to going with REST is that you can reuse lots of code and infratructure between a web application and a REST front end. e.g. rendering HTML versus XML versus JSON of your resources is normally pretty easy with frameworks like JAX-RS and implicit views - plus its easy to work with RESTful resources using a web browser
If you're using PHP, I recommend using the PHP SDK for Firebase: Firebase Admin SDK. For an easy configuration you can follow these steps:
Get the project credentials json file from Firebase (Initialize the sdk) and include it in your project.
Install the SDK in your project. I use composer:
composer require kreait/firebase-php ^4.35
Try any example from the Cloud Messaging session in the SDK documentation:
use Kreait\Firebase;
use Kreait\Firebase\Messaging\CloudMessage;
$messaging = (new Firebase\Factory())
->withServiceAccount('/path/to/firebase_credentials.json')
->createMessaging();
$message = CloudMessage::withTarget(/* see sections below */)
->withNotification(Notification::create('Title', 'Body'))
->withData(['key' => 'value']);
$messaging->send($message);
I'm not sure exactly what you want, but I think it's along the lines of:
SELECT `Item`, `qty`-`BAL_QTY` as `qty` FROM ((SELECT Item, SUM(`QTY`) as qty FROM `master_table` GROUP BY `ITEM`) as A NATURAL JOIN `stock_table`) as B
The modern way:
pip install -U requests[socks]
then
import requests
resp = requests.get('http://go.to',
proxies=dict(http='socks5://user:pass@host:port',
https='socks5://user:pass@host:port'))
This is going to sound stupid but I had a similar problem with a site being developed in VS2010 and hosted in the VS Dev Server. The page in question had a scriptmanager to create the connection to a wcf service. I added an extra method to the service and this error started appearing.
What fixed it for me was changing from 'Auto-assign Port' to 'Specific port' with a different port number in the oroject Web settings.
I wish I knew why...
This is working
<form name="myform" ng-submit="create()">
<input type="number"
name="price_field"
ng-model="price"
require
ng-pattern="/^\d{0,9}(\.\d{1,9})?$/">
<span ng-show="myform.price_field.$error.pattern">Not valid number!</span>
<input type="submit" class="btn">
</form>
You can use a .Net environment Visual studio, Take a look at the differences with the PC version.
A lighter editor would be Visual Code
Alternatives :
Installing the Mono Project runtime . It allows you to re-compile the code and run it on a Mac, but this requires various alterations to the codebase, as the fuller .Net Framework is not available. (Also, WPF applications aren't supported here either.)
Virtual machine (VMWare Fusion perhaps)
Update your codebase to .Net Core, (before choosing this option take a look at this migration process)
.Net Core 3.1 is an open-source, free and available on Window, MacOs and Linux
As of September 14, a release candidate 1 of .Net Core 5.0 has been deployed on Window, MacOs and Linux.
[1] : Release candidate (RC) : releases providing early access to complete features. These releases are supported for production use when they have a go-live license
When you declare:
new Vue({
el: '#app',
data () {
return {}
}
)}
That is typically your root Vue instance that the rest of the application descends from. This hangs off the root element declared in an html document, for example:
<html>
...
<body>
<div id="app"></div>
</body>
</html>
The other syntax is declaring a component which can be registered and reused later. For example, if you create a single file component like:
// my-component.js
export default {
name: 'my-component',
data () {
return {}
}
}
You can later import this and use it like:
// another-component.js
<template>
<my-component></my-component>
</template>
<script>
import myComponent from 'my-component'
export default {
components: {
myComponent
}
data () {
return {}
}
...
}
</script>
Also, be sure to declare your data
properties as functions, otherwise they are not going to be reactive.
Here's an example using 'readlines(sizehint)' to read a chunk of lines at a time. DNS pointed out that solution. I wrote this example because the other examples here are single-line oriented.
def getlineno(filename, lineno):
if lineno < 1:
raise TypeError("First line is line 1")
f = open(filename)
lines_read = 0
while 1:
lines = f.readlines(100000)
if not lines:
return None
if lines_read + len(lines) >= lineno:
return lines[lineno-lines_read-1]
lines_read += len(lines)
print getlineno("nci_09425001_09450000.smi", 12000)
It's fine just to cast your int to Foo:
int i = 1;
Foo f = (Foo)i;
If you try to cast a value that's not defined it will still work. The only harm that may come from this is in how you use the value later on.
If you really want to make sure your value is defined in the enum, you can use Enum.IsDefined:
int i = 1;
if (Enum.IsDefined(typeof(Foo), i))
{
Foo f = (Foo)i;
}
else
{
// Throw exception, etc.
}
However, using IsDefined costs more than just casting. Which you use depends on your implemenation. You might consider restricting user input, or handling a default case when you use the enum.
Also note that you don't have to specify that your enum inherits from int; this is the default behavior.
From the man page:
-h, --no-filename
Suppress the prefixing of file names on output. This is the default when there
is only one file (or only standard input) to search.
CryptoSwift is very interesting project but for now it has some AES speed limitations. Be carefull if you need to do some serious crypto - it might be worth to go through the pain of bridge implemmenting CommonCrypto.
BigUps to Marcin for pureSwift implementation
For all those people stuck with this problem, but still couldn't solve it: I stumbled upon the same error and found the _id
field being empty.
I described it here in more detail. Still have not found a solution except changing the fields in _id
to not-ID fields which is a dirty hack to me. I'm probably going to file a bug report for mongoose. Any help would be appreciated!
Edit: I updated my thread. I filed a ticket and they confirmed the missing _id
problem. It is going to be fixed in the 4.x.x version which has a release candidate available right now. The rc is not recommended for productive use!
I had a similar problem and was able to solve it by addressing my mysql with 127.0.0.1
instead of localhost
.
This probably means I've got something wrong in my hosts setup, but this quick fix get's me going for right now.
The values()
method returns a QuerySet containing dictionaries:
<QuerySet [{'comment_id': 1}, {'comment_id': 2}]>
The values_list()
method returns a QuerySet containing tuples:
<QuerySet [(1,), (2,)]>
If you are using values_list()
with a single field, you can use flat=True
to return a QuerySet of single values instead of 1-tuples:
<QuerySet [1, 2]>
For everyone who is stuck with .NET 2.0, like me, try the following way (applicable to the example in the OP):
ConfigItemList.ConvertAll<string>(delegate (ConfigItemType ci)
{
return ci.Name;
}).ToArray();
where ConfigItemList is your list variable.
Use the system
function.
system("myfile.sh"); // myfile.sh should be chmod +x
You need to make the x-factor into an ordered
factor with the ordering you want, e.g
x <- data.frame("variable"=letters[1:5], "value"=rnorm(5)) ## example data
x <- x[with(x,order(-value)), ] ## Sorting
x$variable <- ordered(x$variable, levels=levels(x$variable)[unclass(x$variable)])
ggplot(x, aes(x=variable,y=value)) + geom_bar() +
scale_y_continuous("",formatter="percent") + coord_flip()
I don't know any better way to do the ordering operation. What I have there will only work if there are no duplicate levels for x$variable
.
Can i just point out what you are all trying to set and int where its expecting a drawable.
should you not be doing the following?
imageview.setImageDrawable(this.getResources().getDrawable(R.drawable.icon_image));
imageview.setImageDrawable(getApplicationContext().getResources().getDrawable(R.drawable.icon_profile_image));
The size
attribute works, as well
<input size="25" type="text">
UPDATE: This is no longer necessary with Python3.4. It installs pip3 as part of the stock install.
I ended up posting this same question on the python mailing list, and got the following answer:
# download and install setuptools
curl -O https://bootstrap.pypa.io/ez_setup.py
python3 ez_setup.py
# download and install pip
curl -O https://bootstrap.pypa.io/get-pip.py
python3 get-pip.py
Which solved my question perfectly. After adding the following for my own:
cd /usr/local/bin
ln -s ../../../Library/Frameworks/Python.framework/Versions/3.3/bin/pip pip
So that I could run pip directly, I was able to:
# use pip to install
pip install pyserial
or:
# Don't want it?
pip uninstall pyserial
I got the exact same problem ... To fix it, I just removed my Android Private Libs in "build path" and clicked ok ... and when i opened op the "build path" again eclipse had added them by itself again, and then it worked for me ;)...
To call a controller function in parent scope from inside an isolate scope directive, use dash-separated
attribute names in the HTML like the OP said.
Also if you want to send a parameter to your function, call the function by passing an object:
<test color1="color1" update-fn="updateFn(msg)"></test>
var app = angular.module('dr', []);
app.controller("testCtrl", function($scope) {
$scope.color1 = "color";
$scope.updateFn = function(msg) {
alert(msg);
}
});
app.directive('test', function() {
return {
restrict: 'E',
scope: {
color1: '=',
updateFn: '&'
},
// object is passed while making the call
template: "<button ng-click='updateFn({msg : \"Hello World!\"})'>
Click</button>",
replace: true,
link: function(scope, elm, attrs) {
}
}
});
Change your object.
var top_brands = [
{ key: 'Adidas', value: 100 },
{ key: 'Nike', value: 50 }
];
var $brand_options = $("#top-brands");
$.each(top_brands, function(brand) {
$brand_options.append(
$("<option />").val(brand.key).text(brand.key + " " + brand.value)
);
});
As a rule of thumb:
'Adidas'
, 'Nike'
, 100
and 50
are data.There are no semantics in {Nike: 50}
. What's "Nike"? What's 50?
{key: 'Nike', value: 50}
is a little better, since now you can iterate an array of these objects and values are at predictable places. This makes it easy to write code that handles them.
Better still would be {vendor: 'Nike', itemsSold: 50}
, because now values are not only at predictable places, they also have meaningful names. Technically that's the same thing as above, but now a person would also understand what the values are supposed to mean.
The accepted answer has to load the whole file into memory, which doesn't work nicely for large files. The following solution writes the file contents with the new data inserted into the right line to a temporary file in the same directory (so on the same file system), only reading small chunks from the source file at a time. It then overwrites the source file with the contents of the temporary file in an efficient way (Python 3.8+).
from pathlib import Path
from shutil import copyfile
from tempfile import NamedTemporaryFile
sourcefile = Path("/path/to/source").resolve()
insert_lineno = 152 # The line to insert the new data into.
insert_data = "..." # Some string to insert.
with sourcefile.open(mode="r") as source:
destination = NamedTemporaryFile(mode="w", dir=str(sourcefile.parent))
lineno = 1
while lineno < insert_lineno:
destination.file.write(source.readline())
lineno += 1
# Insert the new data.
destination.file.write(insert_data)
# Write the rest in chunks.
while True:
data = source.read(1024)
if not data:
break
destination.file.write(data)
# Finish writing data.
destination.flush()
# Overwrite the original file's contents with that of the temporary file.
# This uses a memory-optimised copy operation starting from Python 3.8.
copyfile(destination.name, str(sourcefile))
# Delete the temporary file.
destination.close()
EDIT 2020-09-08: I just found an answer on Code Review that does something similar to above with more explanation - it might be useful to some.
ACID and BASE are consistency models for RDBMS and NoSQL respectively. ACID transactions are far more pessimistic i.e. they are more worried about data safety. In the NoSQL database world, ACID transactions are less fashionable as some databases have loosened the requirements for immediate consistency, data freshness and accuracy in order to gain other benefits, like scalability and resiliency.
BASE stands for -
Therefore BASE relaxes consistency to allow the system to process request even in an inconsistent state.
Example: No one would mind if their tweet were inconsistent within their social network for a short period of time. It is more important to get an immediate response than to have a consistent state of users' information.
Try this code
public static String pathRoot = "/sdcard/system/temp/";
public static String readFromFile(Context contect, String nameFile) {
String aBuffer = "";
try {
File myFile = new File(pathRoot + nameFile);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
String aDataRow = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow;
}
myReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return aBuffer;
}
You can also use Guava's ByteStream
to copy the files from the assets folder to the SD card. This is the solution I ended up with which copies files recursively from the assets folder to the SD card:
/**
* Copies all assets in an assets directory to the SD file system.
*/
public class CopyAssetsToSDHelper {
public static void copyAssets(String assetDir, String targetDir, Context context)
throws IOException {
AssetManager assets = context.getAssets();
String[] list = assets.list(assetDir);
for (String f : Objects.requireNonNull(list)) {
if (f.indexOf(".") > 1) { // check, if this is a file
File outFile = new File(context.getExternalFilesDir(null),
String.format("%s/%s", targetDir, f));
File parentFile = outFile.getParentFile();
if (!Objects.requireNonNull(parentFile).exists()) {
if (!parentFile.mkdirs()) {
throw new IOException(String.format("Could not create directory %s.",
parentFile));
}
}
try (InputStream fin = assets.open(String.format("%s/%s", assetDir, f));
OutputStream fout = new FileOutputStream(outFile)) {
ByteStreams.copy(fin, fout);
}
} else { // This is a directory
copyAssets(String.format("%s/%s", assetDir, f), String.format("%s/%s", targetDir, f),
context);
}
}
}
}
Here's a slightly updated version of Chris Herring's solution, taking into account that you can use innerHTML
as well instead of a creating a new text node:
function insertCss( code ) {
var style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet) {
// IE
style.styleSheet.cssText = code;
} else {
// Other browsers
style.innerHTML = code;
}
document.getElementsByTagName("head")[0].appendChild( style );
}
random.seed(a, version)
in python is used to initialize the pseudo-random number generator (PRNG).
PRNG is algorithm that generates sequence of numbers approximating the properties of random numbers. These random numbers can be reproduced using the seed value. So, if you provide seed value, PRNG starts from an arbitrary starting state using a seed.
Argument a
is the seed value. If the a value is None
, then by default, current system time is used.
and version
is An integer specifying how to convert the a parameter into a integer. Default value is 2.
import random
random.seed(9001)
random.randint(1, 10) #this gives output of 1
# 1
If you want the same random number to be reproduced then provide the same seed again
random.seed(9001)
random.randint(1, 10) # this will give the same output of 1
# 1
If you don't provide the seed, then it generate different number and not 1 as before
random.randint(1, 10) # this gives 7 without providing seed
# 7
If you provide different seed than before, then it will give you a different random number
random.seed(9002)
random.randint(1, 10) # this gives you 5 not 1
# 5
So, in summary, if you want the same random number to be reproduced, provide the seed. Specifically, the same seed.
If you just need to read the data.
encrypt(str.data(),str.size());
If you need a read/write copy of the data put it into a vector. (Don;t dynamically allocate space that's the job of vector).
std::vector<byte> source(str.begin(),str.end());
encrypt(&source[0],source.size());
Of course we are all assuming that byte is a char!!!
No, what you are looking for would be called a parent selector. CSS has none; they have been proposed multiple times but I know of no existing or forthcoming standard including them. You are correct that you would need to use something like jQuery or use additional class annotations to achieve the effect you want.
Here are some similar questions with similar results:
Should be probably changed to
firstName = firstName.trim().replaceAll("\\.", "");
Ideally, margins in CSS containers should collapse, so you can define a parent container which sets its margins(s) to the minimum you want, and then use the margin(s) you want for the child, and the content of the child will use the larger margins between the parent and child margin:
if the child margin(s) are smaller than the parent margin(s)+its padding(s), then the child margins(s) will have no effect.
if the child margin(s) are larger than the parent margin(s)+its padding(s), then the parent padding(s) should be increased to fit.
This is still frequently not working as intended in CSS: currently CSS allows margin(s) of a child to collapse into the margin(s) of the parent (extending them if necesary), only if the parent defines NO padding and NO border and no intermediate sibling content exist in the parent between the child and the begining of the content box of the parent; however there may be floatting or positioned sibling elements, which are ignored for computing margins, unless they use "clear:" to also extend the parent's content-box and compltely fit their own content vertically in it (only the parent's height of the content-box is increased for the top-to-bottom or bottom-to-top block-direction of its content box, or only the parent's width for the left-to-right or right-to-left block-direction; the inline-direction of the parent's content-box plays no role) .
So if the parent defines only 1px of padding, or only 1px of border, then this stops the child from collapsing its margin into the parent's margin. Instead the child margins will take effect from the content box of the parent (or the border box of the intermediate sibling content if there's any one). This means that any non-null border or non-null padding in the parent is treated by the child as if this was a sibling content in the same parent.
So this simple solution should work: use an additional parent without any border or padding to set the minimum margin to nest the child element in it; you can still add borders or paddings to the child (if needed) where you'll defining its own secondary margin (collapsing into the parent(s) margins) !
Note that a child element may collapse its margin(s) into several levels of parents ! This means that you can define several minimums (e.g. for the minimum between 3 values, use two levels of parents to contain the child).
Sometimes 3 or more values are needed to account for: the viewport width, the document width, the section container width, the presence or absence of external floats stealing space in the container, and the minimum width needed for the child content itself. All these widths may be variable and may depend as well on the kind of browser used (including its accessibility settings, such as text zoom, or "Hi-DPI" adjustments of sizes in renderers depending on capabilities of the target viewing device, or sometimes because there's a user-tunable choice of layouts such as personal "skins" or other user's preferences, or the set of available fonts on the final rendering host, which means that exact font sizes are hard to predict safely, to match exact sizes in "pixels" for images or borders ; as well users have a wide variety of screen sizes or paper sizes if printing, and orientations ; scrolling is also not even available or possible to compensate, and truncation of overflowing contents is most often undesirable; as well using excessive "clears" is wasting space and makes the rendered document much less accessible).
We need to save space, without packing too much info and keeping clarity fore readers, and ease of navigation : a layout is a constant tradeoff, between saving space and showing more information at once to avoid additional scrolling or navigation to other pages, and keeping the packed info displayed easy to navigate or interact with).
But HTML is often not enough flexible for all goals, and even if it offers some advanced features, they becomes difficult to author or to maintain/change the documents (or the infos they contain), or readapt the content later for other goals or presentations. Keeping things simple avoids this issue and if we use these simple tricks that have nearly no cost and are easy to understand, we should use them (this will always save lot of precious time, including for web designers).
The problem is arising as unsigned char is a 4 byte number not a 1 byte number as many think, so change it to
union {
unsigned int integer;
char byte[4];
} temp32bitint;
and cast while printing, to prevent promoting to 'int' (which C does by default)
printf("%u, %u \n", (unsigned char)Buffer[0], (unsigned char)Buffer[1]);
May this one help a little more
Let suppose if you want to make the bar button in a separate file(for modular approach) and want to give selector back to your viewcontroller, you can do like this :-
your Utility File
class GeneralUtility {
class func customeNavigationBar(viewController: UIViewController,title:String){
let add = UIBarButtonItem(title: "Play", style: .plain, target: viewController, action: #selector(SuperViewController.buttonClicked(sender:)));
viewController.navigationController?.navigationBar.topItem?.rightBarButtonItems = [add];
}
}
Then make a SuperviewController class and define the same function on it.
class SuperViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@objc func buttonClicked(sender: UIBarButtonItem) {
}
}
and In our base viewController(which inherit your SuperviewController class) override the same function
import UIKit
class HomeViewController: SuperViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
GeneralUtility.customeNavigationBar(viewController: self,title:"Event");
}
@objc override func buttonClicked(sender: UIBarButtonItem) {
print("button clicked")
}
}
Now just inherit the SuperViewController in whichever class you want this barbutton.
Thanks for the read
Your problem is in the Date
property that truncates DateTime
to date only. You could put the conversion like this:
DateTime myDateTime = DateTime.Now;
string sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss");
set class "no-sort" in th of the table then add css .no-sort { pointer-events: none !important; cursor: default !important;background-image: none !important; } by this it will hide the arrow updown and disble event in the head.
I would highly recommend using a library for attributed strings. It makes it much easier when you want, for example, one string with four different colors and four different fonts. Here is my favorite. It is called SwiftyAttributes
If you wanted to make a string with four different colors and different fonts using SwiftyAttributes:
let magenta = "Hello ".withAttributes([
.textColor(.magenta),
.font(.systemFont(ofSize: 15.0))
])
let cyan = "Sir ".withAttributes([
.textColor(.cyan),
.font(.boldSystemFont(ofSize: 15.0))
])
let green = "Lancelot".withAttributes([
.textColor(.green),
.font(.italicSystemFont(ofSize: 15.0))
])
let blue = "!".withAttributes([
.textColor(.blue),
.font(.preferredFont(forTextStyle: UIFontTextStyle.headline))
])
let finalString = magenta + cyan + green + blue
finalString
would show as
If you want an synchronous request set the async
property to false
for the request. Check out the jQuery AJAX Doc
You just need to return
from the main function at some point. The error message says that the function is defined to return a value but you are not returning anything.
/* .... */
if (Date1 == Date2)
fprintf (stderr , "Indicating that the first date is equal to second date.\n");
return 0;
}
select * from test
where CAST(AddTime as datetime) between '2013/4/4' and '2014/4/4'
-- if data type is different
Within your <jre location>\lib\security\java.policy
try adding:
grant {
permission java.security.AllPermission;
};
And see if it allows you. If so, you will have to add more granular permissions.
See:
Java 8 Documentation for java.policy files
and
http://java.sun.com/developer/onlineTraining/Programming/JDCBook/appA.html
There is really no advantage in using Object.create(...)
over new object
.
Those advocating this method generally state rather ambiguous advantages: "scalability", or "more natural to JavaScript" etc.
However, I have yet to see a concrete example that shows that Object.create
has any advantages over using new
. On the contrary there are known problems with it. Sam Elsamman describes what happens when there are nested objects and Object.create(...)
is used:
var Animal = {
traits: {},
}
var lion = Object.create(Animal);
lion.traits.legs = 4;
var bird = Object.create(Animal);
bird.traits.legs = 2;
alert(lion.traits.legs) // shows 2!!!
This occurs because Object.create(...)
advocates a practice where data is used to create new objects; here the Animal
datum becomes part of the prototype of lion
and bird
, and causes problems as it is shared. When using new the prototypal inheritance is explicit:
function Animal() {
this.traits = {};
}
function Lion() { }
Lion.prototype = new Animal();
function Bird() { }
Bird.prototype = new Animal();
var lion = new Lion();
lion.traits.legs = 4;
var bird = new Bird();
bird.traits.legs = 2;
alert(lion.traits.legs) // now shows 4
Regarding, the optional property attributes that are passed into Object.create(...)
, these can be added using Object.defineProperties(...)
.
You need to put the JSP file in /index.jsp
instead of in /WEB-INF/jsp/index.jsp
. This way the whole servlet is superflous by the way.
WebContent
|-- META-INF
|-- WEB-INF
| `-- web.xml
`-- index.jsp
If you're absolutely positive that you need to invoke a servlet this strange way, then you should map it on an URL pattern of /index.jsp
instead of /index
. You only need to change it to get the request dispatcher from request
instead of from config
and get rid of the whole init()
method.
In case you actually intend to have a "home page servlet" (and thus not a welcome file — which has an entirely different purpose; namely the default file which sould be served when a folder is being requested, which is thus not specifically the root folder), then you should be mapping the servlet on the empty string URL pattern.
<servlet-mapping>
<servlet-name>index</servlet-name>
<url-pattern></url-pattern>
</servlet-mapping>
See also Difference between / and /* in servlet mapping url pattern.
In my case, for tensorflow 2.4.0, none of the previous answer works unless you install tensorflow-cpu
pip install tensorflow-cpu
Also make sure that you don't declare it an array and then try to assign something else to the array like a string, float, integer. I had that problem. If you do some echos of output I was seeing what I wanted the first time, but not after another pass of the same code.
Multipal image uplode with other taBLE $sql1 = "INSERT INTO event(title) VALUES('$title')";
$result1 = mysqli_query($connection,$sql1) or die(mysqli_error($connection));
$lastid= $connection->insert_id;
foreach ($_FILES["file"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK ){
$name = $lastid.$_FILES['file']['name'][$key];
$target_dir = "photo/";
$sql2 = "INSERT INTO photos(image,eventid) VALUES ('".$target_dir.$name."','".$lastid."')";
$result2 = mysqli_query($connection,$sql2) or die(mysqli_error($connection));
move_uploaded_file($_FILES['file']['tmp_name'][$key],$target_dir.$name);
}
}
And how to fetch
$query = "SELECT * FROM event ";
$result = mysqli_query($connection,$query) or die(mysqli_error());
if($result->num_rows > 0) {
while($r = mysqli_fetch_assoc($result)){
$eventid= $r['id'];
$sqli="select id,image from photos where eventid='".$eventid."'";
$resulti=mysqli_query($connection,$sqli);
$image_json_array = array();
while($row = mysqli_fetch_assoc($resulti)){
$image_id = $row['id'];
$image_name = $row['image'];
$image_json_array[] = array("id"=>$image_id,"name"=>$image_name);
}
$msg1[] = array ("imagelist" => $image_json_array);
}
in ajax $(document).ready(function(){ $('#addCAT').validate({ rules:{name:required:true}submitHandler:function(form){var formurl = $(form).attr('action'); $.ajax({ url: formurl,type: "POST",data: new FormData(form),cache: false,processData: false,contentType: false,success: function(data) {window.location.href="{{ url('admin/listcategory')}}";}}); } })})
If you only need to support Safari, you can do it like this:
input.currency:before {
content: attr(data-symbol);
float: left;
color: #aaa;
}
and an input field like
<input class="currency" data-symbol="€" type="number" value="12.9">
This way you don't need an extra tag and keep the symbol information in the markup.
You can create a cell and put the following code in it:
%%html
<style>
div.input {
display:none;
}
</style>
Running this cell will hide all input cells. To show them back, you can use the menu to clear all outputs.
Otherwise you can try notebook extensions like below:
https://github.com/ipython-contrib/IPython-notebook-extensions/wiki/Home_3x
You can pass program arguments on the command line and get them in your Java app like this:
public static void main(String[] args) {
String pathToXml = args[0];
....
}
Alternatively you pass a system property by changing the command line to:
java -Dpath-to-xml=enwiki-20111007-pages-articles.xml -jar wiki2txt
and your main class to:
public static void main(String[] args) {
String pathToXml = System.getProperty("path-to-xml");
....
}