Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english
This is not about the difference between Window.ContentRendered
and Window.Loaded
but about what how the Window.Loaded
event can be used:
I use it to avoid splash screens in all applications which need a long time to come up.
// initializing my main window
public MyAppMainWindow()
{
InitializeComponent();
// Set the event
this.ContentRendered += MyAppMainWindow_ContentRendered;
}
private void MyAppMainWindow_ContentRendered(object sender, EventArgs e)
{
// ... comes up quick when the controls are loaded and rendered
// unset the event
this.ContentRendered -= MyAppMainWindow_ContentRendered;
// ... make the time comsuming init stuff here
}
This command works for me:
./mysql -u root -p
(PS: I'm working on mac through terminal)
Here are some common options ordered from simple (one-liner) to complex (huge library). If you are interested in performance, see the micro benchmarks below.
One very simple solution is to use the BigInteger
's hex representation:
new BigInteger(1, someByteArray).toString(16);
Note that since this handles numbers not arbitrary byte-strings it will omit leading zeros - this may or may not be what you want (e.g. 000AE3
vs 0AE3
for a 3 byte input). This is also very slow, about 100x slower compared to option 2.
Using the %X
placeholder, String.format()
is able to encode most primitive types (short
, int
, long
) to hex:
String.format("%X", ByteBuffer.wrap(eightByteArray).getLong());
If you exclusively have 4 bytes arrays you can use the toHexString
method of the Integer class:
Integer.toHexString(ByteBuffer.wrap(fourByteArray).getInt());
The same works with 8 byte arrays and Long
Long.toHexString(ByteBuffer.wrap(eightByteArray).getLong());
Here is a full featured, copy & pasteable code snippet supporting upper/lowercase and endianness. It is optimized to minimize memory complexity and maximize performance and should be compatible with all modern Java versions (5+).
private static final char[] LOOKUP_TABLE_LOWER = new char[]{0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66};
private static final char[] LOOKUP_TABLE_UPPER = new char[]{0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46};
public static String encode(byte[] byteArray, boolean upperCase, ByteOrder byteOrder) {
// our output size will be exactly 2x byte-array length
final char[] buffer = new char[byteArray.length * 2];
// choose lower or uppercase lookup table
final char[] lookup = upperCase ? LOOKUP_TABLE_UPPER : LOOKUP_TABLE_LOWER;
int index;
for (int i = 0; i < byteArray.length; i++) {
// for little endian we count from last to first
index = (byteOrder == ByteOrder.BIG_ENDIAN) ? i : byteArray.length - i - 1;
// extract the upper 4 bit and look up char (0-A)
buffer[i << 1] = lookup[(byteArray[index] >> 4) & 0xF];
// extract the lower 4 bit and look up char (0-A)
buffer[(i << 1) + 1] = lookup[(byteArray[index] & 0xF)];
}
return new String(buffer);
}
public static String encode(byte[] byteArray) {
return encode(byteArray, false, ByteOrder.BIG_ENDIAN);
}
The full source code with Apache v2 license and decoder can be found here.
While working on my previous project, I created this little toolkit for working with bytes in Java. It has no external dependencies and is compatible with Java 7+. It includes, among others, a very fast and well tested HEX en/decoder:
import at.favre.lib.bytes.Bytes;
...
Bytes.wrap(someByteArray).encodeHex()
You can check it out on Github: bytes-java.
Of course there is the good 'ol commons codecs. (warning opinion ahead) While working on the project outlined above I analyzed the code and was quite disappointed; a lot of duplicate unorganized code, obsolete and exotic codecs probably only useful for very few and quite over engineered and slow implementations of popular codecs (specifically Base64). I therefore would make an informed decision if you want to use it or an alternative. Anyways, if you still want to use it, here is a code snippet:
import org.apache.commons.codec.binary.Hex;
...
Hex.encodeHexString(someByteArray));
More often than not you already have Guava as a dependency. If so just use:
import com.google.common.io.BaseEncoding;
...
BaseEncoding.base16().lowerCase().encode(someByteArray);
If you use the Spring framework with Spring Security you can use the following:
import org.springframework.security.crypto.codec.Hex
...
new String(Hex.encode(someByteArray));
If you already use the security framework Bouncy Castle you can use its Hex
util:
import org.bouncycastle.util.encoders.Hex;
...
Hex.toHexString(someByteArray);
In previous Java (8 and below) versions the Java code for JAXB was included as runtime dependency. Since Java 9 and Jigsaw modularisation your code cannot access other code outside of it's module without explicit declaration. So be aware if you get an exception like:
java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException
when running on a JVM with Java 9+. If so then switch implementations to any of the alternatives above. See also this question.
Here are results from a simple JMH micro benchmark encoding byte arrays of different sizes. The values are operations per second, so higher is better. Note that micro benchmarks very often do not represent real world behavior, so take these results with a grain of salt.
| Name (ops/s) | 16 byte | 32 byte | 128 byte | 0.95 MB |
|----------------------|-----------:|-----------:|----------:|--------:|
| Opt1: BigInteger | 2,088,514 | 1,008,357 | 133,665 | 4 |
| Opt2/3: Bytes Lib | 20,423,170 | 16,049,841 | 6,685,522 | 825 |
| Opt4: Apache Commons | 17,503,857 | 12,382,018 | 4,319,898 | 529 |
| Opt5: Guava | 10,177,925 | 6,937,833 | 2,094,658 | 257 |
| Opt6: Spring | 18,704,986 | 13,643,374 | 4,904,805 | 601 |
| Opt7: BC | 7,501,666 | 3,674,422 | 1,077,236 | 152 |
| Opt8: JAX-B | 13,497,736 | 8,312,834 | 2,590,940 | 346 |
Specs: JDK 8u202, i7-7700K, Win10, 24GB Ram. See the full benchmark here.
public void FromCamera() {
Log.i("camera", "startCameraActivity()");
File file = new File(path);
Uri outputFileUri = Uri.fromFile(file);
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, 1);
}
public void FromCard() {
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 2);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2 && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
bitmap = BitmapFactory.decodeFile(picturePath);
image.setImageBitmap(bitmap);
if (bitmap != null) {
ImageView rotate = (ImageView) findViewById(R.id.rotate);
}
} else {
Log.i("SonaSys", "resultCode: " + resultCode);
switch (resultCode) {
case 0:
Log.i("SonaSys", "User cancelled");
break;
case -1:
onPhotoTaken();
break;
}
}
}
protected void onPhotoTaken() {
// Log message
Log.i("SonaSys", "onPhotoTaken");
taken = true;
imgCapFlag = true;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
bitmap = BitmapFactory.decodeFile(path, options);
image.setImageBitmap(bitmap);
}
I'm not sure but:
If you call the delete method with a non transient object, this means first fetched the object from the DB. So it is normal to see a select statement. Perhaps in the end you see 2 select + 1 delete?
If you call the delete method with a transient object, then it is possible that you have a cascade="delete"
or something similar which requires to retrieve first the object so that "nested actions" can be performed if it is required.
Edit: Calling delete() with a transient instance means doing something like that:
MyEntity entity = new MyEntity();
entity.setId(1234);
session.delete(entity);
This will delete the row with id 1234, even if the object is a simple pojo not retrieved by Hibernate, not present in its session cache, not managed at all by Hibernate.
If you have an entity association Hibernate probably have to fetch the full entity so that it knows if the delete should be cascaded to associated entities.
The answer to the question specifically asked is no. But have you been looking at mocking frameworks? I use MOQ but there's millions of them out there and they allow you to implement/stub (partially or fully) interfaces in-line. Eg.
public void ThisWillWork()
{
var source = new DummySource[0];
var mock = new Mock<DummyInterface>();
mock.SetupProperty(m => m.A, source.Select(s => s.A));
mock.SetupProperty(m => m.B, source.Select(s => s.C + "_" + s.D));
DoSomethingWithDummyInterface(mock.Object);
}
Create your shell script as login.sh
in your $HOME folder.
Paste the following one-line script into Script Editor:
do shell script "$HOME/login.sh"
Then save it as an application.
Finally add the application to your login items.
If you want to make the script output visual, you can swap step 2 for this:
tell application "Terminal"
activate
do script "$HOME/login.sh"
end tell
If multiple commands are needed something like this can be used:
tell application "Terminal"
activate
do script "cd $HOME"
do script "./login.sh" in window 1
end tell
var array = new Array();_x000D_
_x000D_
array.push('123');_x000D_
array.push('456');_x000D_
array.push('789');_x000D_
_x000D_
var _searchedIndex = $.inArray('456',array);_x000D_
alert(_searchedIndex );_x000D_
if(_searchedIndex >= 0){_x000D_
array.splice(_searchedIndex,1);_x000D_
alert(array );_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
_x000D_
Fix could be as simple as clicking run/skip all breakpoints. Worked for me.
Same article on my blog(I like formatting more)
I wrote small article which describe how to make access to your android database thread safe.
Assuming you have your own SQLiteOpenHelper.
public class DatabaseHelper extends SQLiteOpenHelper { ... }
Now you want to write data to database in separate threads.
// Thread 1
Context context = getApplicationContext();
DatabaseHelper helper = new DatabaseHelper(context);
SQLiteDatabase database = helper.getWritableDatabase();
database.insert(…);
database.close();
// Thread 2
Context context = getApplicationContext();
DatabaseHelper helper = new DatabaseHelper(context);
SQLiteDatabase database = helper.getWritableDatabase();
database.insert(…);
database.close();
You will get following message in your logcat and one of your changes will not be written.
android.database.sqlite.SQLiteDatabaseLockedException: database is locked (code 5)
This is happening because every time you create new SQLiteOpenHelper object you are actually making new database connection. If you try to write to the database from actual distinct connections at the same time, one will fail. (from answer above)
To use database with multiple threads we need to make sure we are using one database connection.
Let’s make singleton class Database Manager which will hold and return single SQLiteOpenHelper object.
public class DatabaseManager {
private static DatabaseManager instance;
private static SQLiteOpenHelper mDatabaseHelper;
public static synchronized void initializeInstance(SQLiteOpenHelper helper) {
if (instance == null) {
instance = new DatabaseManager();
mDatabaseHelper = helper;
}
}
public static synchronized DatabaseManager getInstance() {
if (instance == null) {
throw new IllegalStateException(DatabaseManager.class.getSimpleName() +
" is not initialized, call initialize(..) method first.");
}
return instance;
}
public SQLiteDatabase getDatabase() {
return new mDatabaseHelper.getWritableDatabase();
}
}
Updated code which write data to database in separate threads will look like this.
// In your application class
DatabaseManager.initializeInstance(new MySQLiteOpenHelper());
// Thread 1
DatabaseManager manager = DatabaseManager.getInstance();
SQLiteDatabase database = manager.getDatabase()
database.insert(…);
database.close();
// Thread 2
DatabaseManager manager = DatabaseManager.getInstance();
SQLiteDatabase database = manager.getDatabase()
database.insert(…);
database.close();
This will bring you another crash.
java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase
Since we are using only one database connection, method getDatabase() return same instance of SQLiteDatabase object for Thread1 and Thread2. What is happening, Thread1 may close database, while Thread2 is still using it. That’s why we have IllegalStateException crash.
We need to make sure no-one is using database and only then close it. Some folks on stackoveflow recommended to never close your SQLiteDatabase. This will result in following logcat message.
Leak found
Caused by: java.lang.IllegalStateException: SQLiteDatabase created and never closed
public class DatabaseManager {
private int mOpenCounter;
private static DatabaseManager instance;
private static SQLiteOpenHelper mDatabaseHelper;
private SQLiteDatabase mDatabase;
public static synchronized void initializeInstance(SQLiteOpenHelper helper) {
if (instance == null) {
instance = new DatabaseManager();
mDatabaseHelper = helper;
}
}
public static synchronized DatabaseManager getInstance() {
if (instance == null) {
throw new IllegalStateException(DatabaseManager.class.getSimpleName() +
" is not initialized, call initializeInstance(..) method first.");
}
return instance;
}
public synchronized SQLiteDatabase openDatabase() {
mOpenCounter++;
if(mOpenCounter == 1) {
// Opening new database
mDatabase = mDatabaseHelper.getWritableDatabase();
}
return mDatabase;
}
public synchronized void closeDatabase() {
mOpenCounter--;
if(mOpenCounter == 0) {
// Closing database
mDatabase.close();
}
}
}
Use it as follows.
SQLiteDatabase database = DatabaseManager.getInstance().openDatabase();
database.insert(...);
// database.close(); Don't close it directly!
DatabaseManager.getInstance().closeDatabase(); // correct way
Every time you need database you should call openDatabase() method of DatabaseManager class. Inside this method, we have a counter, which indicate how many times database is opened. If it equals to one, it means we need to create new database connection, if not, database connection is already created.
The same happens in closeDatabase() method. Every time we call this method, counter is decreased, whenever it goes to zero, we are closing database connection.
Now you should be able to use your database and be sure it's thread safe.
Why not do it with one method call:
File.AppendAllLines("file.txt", new[] { DateTime.Now.ToString() });
which will do the newline for you, and allow you to insert multiple lines at once if you want.
I installed using the command:
./configure --prefix=/usr \
--enable-shared \
--with-system-expat \
--with-system-ffi \
--enable-unicode=ucs4 &&
make
Now, as the root user:
make install &&
chmod -v 755 /usr/lib/libpython2.7.so.1.0
Then I tried to execute python and got the error:
/usr/local/bin/python: error while loading shared libraries: libpython2.7.so.1.0: cannot open shared object file: No such file or directory
Then, I logged out from root user and again tried to execute the Python and it worked successfully.
Do you just mean spaces or all whitespace?
For just spaces, use str_replace:
$string = str_replace(' ', '', $string);
For all whitespace (including tabs and line ends), use preg_replace:
$string = preg_replace('/\s+/', '', $string);
(From here).
there is another solution to download a web page in ajax. But I am referring to a page that must first be processed and then downloaded.
First you need to separate the page processing from the results download.
1) Only the page calculations are made in the ajax call.
$.post("CalculusPage.php", { calculusFunction: true, ID: 29, data1: "a", data2: "b" }, function(data, status) { if (status == "success") { /* 2) In the answer the page that uses the previous calculations is downloaded. For example, this can be a page that prints the results of a table calculated in the ajax call. */ window.location.href = DownloadPage.php+"?ID="+29; } } ); // For example: in the CalculusPage.php if ( !empty($_POST["calculusFunction"]) ) { $ID = $_POST["ID"]; $query = "INSERT INTO ExamplePage (data1, data2) VALUES ('".$_POST["data1"]."', '".$_POST["data2"]."') WHERE id = ".$ID; ... } // For example: in the DownloadPage.php $ID = $_GET["ID"]; $sede = "SELECT * FROM ExamplePage WHERE id = ".$ID; ... $filename="Export_Data.xls"; header("Content-Type: application/vnd.ms-excel"); header("Content-Disposition: inline; filename=$filename"); ...
I hope this solution can be useful for many, as it was for me.
if you are in the main you can do:
return 0;
or
exit(exit_code);
The exit code depends of the semantic of your code. 1 is error 0 e a normal exit.
In some other function of your program:
exit(exit_code)
will exit the program.
What I mean is, on a page the user can enter one number or thirty numbers, then he/she presses the OK button and the next page shows the array in the same order as it was entered, one element at a time.
Ok, so you need some user input first? There's a couple of methods of how to do that.
prompt()
function which displays a popup asking the user for some input.
<input type="text">
fields.
For the prompt
method, collecting your strings is a doddle:
var input = []; // initialise an empty array
var temp = '';
do {
temp = prompt("Enter a number. Press cancel or leave empty to finish.");
if (temp === "" || temp === null) {
break;
} else {
input.push(temp); // the array will dynamically grow
}
} while (1);
(Yeah it's not the prettiest loop, but it's late and I'm tired....)
The other method requires a bit more effort.
onfocus
handler to it.
<input>
s on the page and store them into an array.eg:
// if you put your dynamic text fields in a container it'll be easier to get them
var inputs = document.getElementById('inputArea').getElementsByTagName('input');
var input = [];
for (var i = 0, l = inputs.length; i < l; ++i) {
if (inputs[i].value.length) {
input.push(inputs[i].value);
}
}
After that, regardless of your method of collecting the input, you can print the numbers back on screen in a number of ways. A simple way would be like this:
var div = document.createElement('div');
for (var i = 0, l = input.length; i < l; ++i) {
div.innerHTML += input[i] + "<br />";
}
document.body.appendChild(div);
I've put this together so you can see it work at jsbin
Prompt method: http://jsbin.com/amefu
Inputs method: http://jsbin.com/iyoge
Explain what video describe to resolve problem
After Changing Password of root (Mysql Account). Accessing to phpmyadmin page will be denied because phpMyAdmin use root/''(blank) as default username/password. To resolve this problem, you need to reconfig phpmyadmin. Edit file config.inc.php in folder %wamp%\apps\phpmyadmin4.1.14 (Not in %wamp%)
$cfg['Servers'][$i]['verbose'] = 'mysql wampserver';
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'changed';
$cfg['Servers'][$i]['host'] = '127.0.0.1';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['compress'] = false;
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = false;
If you have more than 1 DB server, add "i++" to file and continue add new config as above
If numpy >= 1.5
, you can do:
# note that the filename is enclosed with double quotes,
# example "filename.txt"
numpy.savetxt("filename", a, newline=" ")
Edit
several 1D arrays with same length
a = numpy.array([1,2,3])
b = numpy.array([4,5,6])
numpy.savetxt(filename, (a,b), fmt="%d")
# gives:
# 1 2 3
# 4 5 6
several 1D arrays with variable length
a = numpy.array([1,2,3])
b = numpy.array([4,5])
with open(filename,"w") as f:
f.write("\n".join(" ".join(map(str, x)) for x in (a,b)))
# gives:
# 1 2 3
# 4 5
YourModel.objects.filter(datetime_published__year='2008',
datetime_published__month='03',
datetime_published__day='27')
// edit after comments
YourModel.objects.filter(datetime_published=datetime(2008, 03, 27))
doest not work because it creates a datetime object with time values set to 0, so the time in database doesn't match.
Answers from this thread with the highest upvotes didn't work for me as their hashing functions give different results on different machines due to PYTHOPYTHONHASHSEED
.
I adjusted all the hints from this thread and came up with a solution that works for me.
import collections
import hashlib
import json
def simplify_object(o):
if isinstance(o, dict):
ordered_dict = collections.OrderedDict(sorted(o.items()))
for k, v in ordered_dict.items():
v = simplify_object(v)
ordered_dict[str(k)] = v
o = ordered_dict
elif isinstance(o, (list, tuple, set)):
o = [simplify_object(el) for el in o]
else:
o = str(o).strip()
return o
def make_hash(o):
o = simplify_object(o)
bytes_val = json.dumps(o, sort_keys=True, ensure_ascii=True, default=str)
hash_val = hashlib.sha1(bytes_val.encode()).hexdigest()
return hash_val
I was trying to select an area of svg with a rectangle and get all the elements from it. For this, element.getBoundingClientRect() worked perfectly for me. It returns current coordinates of svg elements regardless of whether svg is scaled or transformed.
The first answer you posted (System is a built-in class...) is pretty spot on.
You can add that the System
class contains large portions which are native and that is set up by the JVM during startup, like connecting the System.out
printstream to the native output stream associated with the "standard out" (console).
It has method to find all values from map:
Map<K, V> map=getMapObjectFromXyz();
Collection<V> vs= map.values();
Iterate over vs
to do some operation
man ssh
gives me this options would could be useful.
-i identity_file Selects a file from which the identity (private key) for RSA or DSA authentication is read. The default is ~/.ssh/identity for protocol version 1, and ~/.ssh/id_rsa and ~/.ssh/id_dsa for pro- tocol version 2. Identity files may also be specified on a per- host basis in the configuration file. It is possible to have multiple -i options (and multiple identities specified in config- uration files).
So you could create an alias in your bash config with something like
alias ssh="ssh -i /path/to/private_key"
I haven't looked into a ssh configuration file, but like the -i
option this too could be aliased
-F configfile Specifies an alternative per-user configuration file. If a configuration file is given on the command line, the system-wide configuration file (/etc/ssh/ssh_config) will be ignored. The default for the per-user configuration file is ~/.ssh/config.
Using
data : JSON.stringify(obj)
in the above situation would have worked I believe.
Note: You should add json2.js library all browsers don't support that JSON object (IE7-) Difference between json.js and json2.js
try this,it may help you
import java.util.Scanner;
public class MulTwoArray {
public static void main(String[] args) {
int i, j, k;
int[][] a = new int[3][3];
int[][] b = new int[3][3];
int[][] c = new int[3][3];
Scanner sc = new Scanner(System.in);
System.out.println("Enter size of array a");
int rowa = sc.nextInt();
int cola = sc.nextInt();
System.out.println("Enter size of array b");
int rowb = sc.nextInt();
int colb = sc.nextInt();
//read and b
System.out.println("Enter elements of array a");
for (i = 0; i < rowa; ++i) {
for (j = 0; j < cola; ++j) {
a[i][j] = sc.nextInt();
}
System.out.println();
}
System.out.println("Enter elements of array b");
for (i = 0; i < rowb; ++i) {
for (j = 0; j < colb; ++j) {
b[i][j] = sc.nextInt();
}
System.out.println("\n");
}
//print a and b
System.out.println("the elements of array a");
for (i = 0; i < rowa; ++i) {
for (j = 0; j < cola; ++j) {
System.out.print(a[i][j]);
System.out.print("\t");
}
System.out.println("\n");
}
System.out.println("the elements of array b");
for (i = 0; i < rowb; ++i) {
for (j = 0; j < colb; ++j) {
System.out.print(b[i][j]);
System.out.print("\t");
}
System.out.println("\n");
}
//multiply a and b
for (i = 0; i < rowa; ++i) {
for (j = 0; j < colb; ++j) {
c[i][j] = 0;
for (k = 0; k < cola; ++k) {
c[i][j] += a[i][k] * b[k][j];
}
}
}
//print multi result
System.out.println("result of multiplication of array a and b is ");
for (i = 0; i < rowa; ++i) {
for (j = 0; j < colb; ++j) {
System.out.print(c[i][j]);
System.out.print("\t");
}
System.out.println("\n");
}
}
}
You can use the directive v-html to show it. like this:
<td v-html="desc"></td>
@dynamic is typically used (as has been said above) when a property is being dynamically created at runtime. NSManagedObject does this (why all its properties are dynamic) -- which suppresses some compiler warnings.
For a good overview on how to create properties dynamically (without NSManagedObject and CoreData:, see: http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtDynamicResolution.html#//apple_ref/doc/uid/TP40008048-CH102-SW1
To access the elements in the array, use array notation: $product['prodname']
$product->prodname
is object notation, which can only be used to access object attributes and methods.
A solution that helped me: Go to Tools > NuGet Package Manager > Manage NuGet Packaged for Solution... > Browse > Search for System.IO.Compression.ZipFile and install it
You can use the "Except" extension method (see http://msdn.microsoft.com/en-us/library/bb337804.aspx)
In your code
var difference = people.Except(exclusions);
Sorry to bring up an old thread, but here is a little manual for those who (like me!) don't see how Eli Grey's example works:
var test = new Object();
test.watch("elem", function(prop,oldval,newval){
//Your code
return newval;
});
Hope this can help someone
You go around making your webpage, and keep on putting {{data bindings}} whenever you feel you would have dynamic data. Angular will then provide you a $scope handler, which you can populate (statically or through calls to the web server).
This is a good understanding of data-binding. I think you've got that down.
For simple DOM manipulation, which doesnot involve data manipulation (eg: color changes on mousehover, hiding/showing elements on click), jQuery or old-school js is sufficient and cleaner. This assumes that the model in angular's mvc is anything that reflects data on the page, and hence, css properties like color, display/hide, etc changes dont affect the model.
I can see your point here about "simple" DOM manipulation being cleaner, but only rarely and it would have to be really "simple". I think DOM manipulation is one the areas, just like data-binding, where Angular really shines. Understanding this will also help you see how Angular considers its views.
I'll start by comparing the Angular way with a vanilla js approach to DOM manipulation. Traditionally, we think of HTML as not "doing" anything and write it as such. So, inline js, like "onclick", etc are bad practice because they put the "doing" in the context of HTML, which doesn't "do". Angular flips that concept on its head. As you're writing your view, you think of HTML as being able to "do" lots of things. This capability is abstracted away in angular directives, but if they already exist or you have written them, you don't have to consider "how" it is done, you just use the power made available to you in this "augmented" HTML that angular allows you to use. This also means that ALL of your view logic is truly contained in the view, not in your javascript files. Again, the reasoning is that the directives written in your javascript files could be considered to be increasing the capability of HTML, so you let the DOM worry about manipulating itself (so to speak). I'll demonstrate with a simple example.
<div rotate-on-click="45"></div>
First, I'd just like to comment that if we've given our HTML this functionality via a custom Angular Directive, we're already done. That's a breath of fresh air. More on that in a moment.
function rotate(deg, elem) {
$(elem).css({
webkitTransform: 'rotate('+deg+'deg)',
mozTransform: 'rotate('+deg+'deg)',
msTransform: 'rotate('+deg+'deg)',
oTransform: 'rotate('+deg+'deg)',
transform: 'rotate('+deg+'deg)'
});
}
function addRotateOnClick($elems) {
$elems.each(function(i, elem) {
var deg = 0;
$(elem).click(function() {
deg+= parseInt($(this).attr('rotate-on-click'), 10);
rotate(deg, this);
});
});
}
addRotateOnClick($('[rotate-on-click]'));
app.directive('rotateOnClick', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var deg = 0;
element.bind('click', function() {
deg+= parseInt(attrs.rotateOnClick, 10);
element.css({
webkitTransform: 'rotate('+deg+'deg)',
mozTransform: 'rotate('+deg+'deg)',
msTransform: 'rotate('+deg+'deg)',
oTransform: 'rotate('+deg+'deg)',
transform: 'rotate('+deg+'deg)'
});
});
}
};
});
Pretty light, VERY clean and that's just a simple manipulation! In my opinion, the angular approach wins in all regards, especially how the functionality is abstracted away and the dom manipulation is declared in the DOM. The functionality is hooked onto the element via an html attribute, so there is no need to query the DOM via a selector, and we've got two nice closures - one closure for the directive factory where variables are shared across all usages of the directive, and one closure for each usage of the directive in the link
function (or compile
function).
Two-way data binding and directives for DOM manipulation are only the start of what makes Angular awesome. Angular promotes all code being modular, reusable, and easily testable and also includes a single-page app routing system. It is important to note that jQuery is a library of commonly needed convenience/cross-browser methods, but Angular is a full featured framework for creating single page apps. The angular script actually includes its own "lite" version of jQuery so that some of the most essential methods are available. Therefore, you could argue that using Angular IS using jQuery (lightly), but Angular provides much more "magic" to help you in the process of creating apps.
This is a great post for more related information: How do I “think in AngularJS” if I have a jQuery background?
The above points are aimed at the OP's specific concerns. I'll also give an overview of the other important differences. I suggest doing additional reading about each topic as well.
Angular is a framework, jQuery is a library. Frameworks have their place and libraries have their place. However, there is no question that a good framework has more power in writing an application than a library. That's exactly the point of a framework. You're welcome to write your code in plain JS, or you can add in a library of common functions, or you can add a framework to drastically reduce the code you need to accomplish most things. Therefore, a more appropriate question is:
Good frameworks can help architect your code so that it is modular (therefore reusable), DRY, readable, performant and secure. jQuery is not a framework, so it doesn't help in these regards. We've all seen the typical walls of jQuery spaghetti code. This isn't jQuery's fault - it's the fault of developers that don't know how to architect code. However, if the devs did know how to architect code, they would end up writing some kind of minimal "framework" to provide the foundation (achitecture, etc) I discussed a moment ago, or they would add something in. For example, you might add RequireJS to act as part of your framework for writing good code.
Here are some things that modern frameworks are providing:
Before I further discuss Angular, I'd like to point out that Angular isn't the only one of its kind. Durandal, for example, is a framework built on top of jQuery, Knockout, and RequireJS. Again, jQuery cannot, by itself, provide what Knockout, RequireJS, and the whole framework built on top them can. It's just not comparable.
If you need to destroy a planet and you have a Death Star, use the Death star.
Building on my previous points about what frameworks provide, I'd like to commend the way that Angular provides them and try to clarify why this is matter of factually superior to jQuery alone.
In my above example, it is just absolutely unavoidable that jQuery has to hook onto the DOM in order to provide functionality. That means that the view (html) is concerned about functionality (because it is labeled with some kind of identifier - like "image slider") and JavaScript is concerned about providing that functionality. Angular eliminates that concept via abstraction. Properly written code with Angular means that the view is able to declare its own behavior. If I want to display a clock:
<clock></clock>
Done.
Yes, we need to go to JavaScript to make that mean something, but we're doing this in the opposite way of the jQuery approach. Our Angular directive (which is in it's own little world) has "augumented" the html and the html hooks the functionality into itself.
Angular gives you a straightforward way to structure your code. View things belong in the view (html), augmented view functionality belongs in directives, other logic (like ajax calls) and functions belong in services, and the connection of services and logic to the view belongs in controllers. There are some other angular components as well that help deal with configuration and modification of services, etc. Any functionality you create is automatically available anywhere you need it via the Injector subsystem which takes care of Dependency Injection throughout the application. When writing an application (module), I break it up into other reusable modules, each with their own reusable components, and then include them in the bigger project. Once you solve a problem with Angular, you've automatically solved it in a way that is useful and structured for reuse in the future and easily included in the next project. A HUGE bonus to all of this is that your code will be much easier to test.
THANK GOODNESS. The aforementioned jQuery spaghetti code resulted from a dev that made something "work" and then moved on. You can write bad Angular code, but it's much more difficult to do so, because Angular will fight you about it. This means that you have to take advantage (at least somewhat) to the clean architecture it provides. In other words, it's harder to write bad code with Angular, but more convenient to write clean code.
Angular is far from perfect. The web development world is always growing and changing and there are new and better ways being put forth to solve problems. Facebook's React and Flux, for example, have some great advantages over Angular, but come with their own drawbacks. Nothing's perfect, but Angular has been and is still awesome for now. Just as jQuery once helped the web world move forward, so has Angular, and so will many to come.
SELECT CAST(12.0910239123 AS DECIMAL(15, 2))
In your CSS add...
filter: opacity(50%);
In JavaScript use...
element.style.filter='opacity(50%)';
NB: Add vendor prefixes as required but Chromium should be fine without.
If you are using firestore (and not just storing the timestamp as a string) a date field in a document will return a Timestamp. The Timestamp object contains a toDate()
method.
Using timeago you can create a relative time quite simply:
_ago(Timestamp t) {
return timeago.format(t.toDate(), 'en_short');
}
build() {
return Text(_ago(document['mytimestamp'])));
}
Make sure to set _firestore.settings(timestampsInSnapshotsEnabled: true);
to return a Timestamp instead of a Date object.
i think doing some like this.
void printchar(char c, int n){
int i;
for(i=0;i<n;i++)
print("%c",c);
}
printchar("*",10);
I encountered the same problem using Siebel REXPIMP (registry import) when using the latest Instant Client driver. To fix the issues, use the Siebel provided Data Direct driver instead. The DLL is SEOR823.DLL
The problem is a simple typo. You named your variable 'conc' on line 2 but then referenced 'conn' on line 4.
install simplejson by
pip install simplejson
and the create a class
class Serialise(object):
def _asdict(self):
"""
Serialization logic for converting entities using flask's jsonify
:return: An ordered dictionary
:rtype: :class:`collections.OrderedDict`
"""
result = OrderedDict()
# Get the columns
for key in self.__mapper__.c.keys():
if isinstance(getattr(self, key), datetime):
result["x"] = getattr(self, key).timestamp() * 1000
result["timestamp"] = result["x"]
else:
result[key] = getattr(self, key)
return result
and inherit this class to every orm classes so that this _asdict
function gets registered to every ORM class and boom.
And use jsonify anywhere
From the jQuery documentation:
As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. For more flexible event binding, see the discussion of event delegation in .on() or .delegate().
If you are looking for a free, nice looking, cross-platform editor, try Komodo Edit. It is not as powerful as Komodo IDE, however that isn't free. See feature chart.
Another free, extensible editor is jEdit. Crossplatform as it is 100% pure Java. Not the fastest IDE on earth, but for Java actually very fast, very flexible, not that nice looking though.
Both have very sophisticated code folding, syntax highlighting (for all languages you can think of!) and are very flexible regarding configuring it for you personal needs. jEdit is BTW very easy to extend to add whatever feature you may need there (it has an ultra simple scripting language, that looks like Java, but is actually "scripted").
These responses don't tell you that gacutil resides in C:\WINDOWS\Microsoft.NET\Framework\v1.1* by the way.
I didn't have it in my v2.0 folder. But I tried dragging & dropping the DLL into the C:\WINDOWS\Assembly folder as was suggested here earlier and that was easier and does work, as long as it's a .NET library. I also tried a COM library and this failed with an error that it was expecting an assembly manifest. I know that wasn't the question here, but thought I'd mention that in case someone finds out they can't add it, that that might be why.
-Tom
An established connection was aborted by the software in your host machine
That is a boiler-plate error message, it comes out of Windows. The underlying error code is WSAECONNABORTED. Which really doesn't mean more than "connection was aborted". You have to be a bit careful about the "your host machine" part of the phrase. In the vast majority of Windows application programs, it is indeed the host that the desktop app is connected to that aborted the connection. Usually a server somewhere else.
The roles are reversed however when you implement your own server. Now you need to read the error message as "aborted by the application at the other end of the wire". Which is of course not uncommon when you implement a server, client programs that use your server are not unlikely to abort a connection for whatever reason. It can mean that a fire-wall or a proxy terminated the connection but that's not very likely since they typically would not allow the connection to be established in the first place.
You don't really know why a connection was aborted unless you have insight what is going on at the other end of the wire. That's of course hard to come by. If your server is reachable through the Internet then don't discount the possibility that you are being probed by a port scanner. Or your customers, looking for a game cheat.
def bubble_sort(l):
for passes_left in range(len(l)-1, 0, -1):
for index in range(passes_left):
if l[index] < l[index + 1]:
l[index], l[index + 1] = l[index + 1], l[index]
return l
Get a decent text editor like Notepad++ or Vim (if you're already proficient with it). Search for the table name and you should be able to highlight just the CREATE, ALTER, and INSERT commands for that table. It may be easier to navigate with your keyboard rather than a mouse. And I would make sure you're on a machine with plenty or RAM so that it will not have a problem loading the entire file at once. Once you've highlighted and copied the rows you need, it would be a good idea to back up just the copied part into it's own backup file and then import it into MySQL.
You can use IF()
where in Oracle you would have used DECODE()
.
mysql> select if(emp_id=1,'X','Y') as test, emp_id from emps;
Generally mysql uses this date format 'Y-m-d H:i:s'
If you set the trunc flag.
#include<fstream>
using namespace std;
fstream ofs;
int main(){
ofs.open("test.txt", ios::out | ios::trunc);
ofs<<"Your content here";
ofs.close(); //Using microsoft incremental linker version 14
}
I tested this thouroughly for my own needs in a common programming situation I had. Definitely be sure to preform the ".close();" operation. If you don't do this there is no telling whether or not you you trunc or just app to the begging of the file. Depending on the file type you might just append over the file which depending on your needs may not fullfill its purpose. Be sure to call ".close();" explicity on the fstream you are trying to replace.
String ss = "Pawan kavita kiyansh Patidar Patidar";
StringBuilder ress = new StringBuilder();
Map<Character, Integer> fre = ss.chars().boxed()
.collect(Collectors.toMap(k->Character.valueOf((char) k.intValue()),k->1,Integer::sum));
//fre.forEach((k, v) -> System.out.println((k + ":" + v)));
fre.entrySet().forEach(e ->{
//System.out.println(e.getKey() + ":" + e.getValue());
//ress.append(String.valueOf(e.getKey())+e.getValue());
});
fre.forEach((k,v)->{
//System.out.println("Item : " + k + " Count : " + v);
ress.append(String.valueOf(k)+String.valueOf(v));
});
System.out.println(ress.toString());
Similar to @Wolfram J's answer, here is a method to encrypt your private key with a passphrase:
gpg --output - --armor --export $KEYID | \
gpg --output private_key.asc --armor --symmetric --cipher-algo AES256
And a corresponding method to decrypt:
gpg private_key.asc
Out-File
defaults to unicode encoding which is why you are seeing the behavior you are. Use -Encoding Ascii
to change this behavior. In your case
Out-File -Encoding Ascii -append textfile.txt.
Add-Content
uses Ascii and also appends by default.
"This is a test" | Add-Content textfile.txt.
As for the lack of newline: You did not send a newline so it will not write one to file.
sed would be a better choice (stream editor)
tail -n0 -f <file> | sed -n '/search string/p'
and then if you wanted the tail command to exit once you found a particular string:
tail --pid=$(($BASHPID+1)) -n0 -f <file> | sed -n '/search string/{p; q}'
Obviously a bashism: $BASHPID will be the process id of the tail command. The sed command is next after tail in the pipe, so the sed process id will be $BASHPID+1.
Sure, simply bind multiple listeners to it.
Short cutting with jQuery
$("#id").bind("click", function() {_x000D_
alert("Event 1");_x000D_
});_x000D_
$(".foo").bind("click", function() {_x000D_
alert("Foo class");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="foo" id="id">Click</div>
_x000D_
Using SQL Server 05 I can get this to work by using:
declare @OrigValue int;
set @OrigValue = 121.25;
select replace(str(@OrigValue/3600,len(ltrim(@OrigValue/3600))+abs(sign(@OrigValue/359999)-1)) + ':' + str((@OrigValue/60)%60,2) + ':' + str(@OrigValue%60,2),' ','0')
After searching a lot, I found the following solution which is working in my cases:
.opacity_30{
background:rgb(255,255,255); /* Fallback for web browsers that don't support neither RGBa nor filter */
background: transparent\9; /* Backslash 9 hack to prevent IE 8 from falling into the fallback */
background:rgba(255,255,255,0.3); /* RGBa declaration for modern browsers */
-ms-filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#4CFFFFFF,endColorstr=#4CFFFFFF); /* IE 8 suppoerted; Sometimes Hover issues may occur, then we can use transparent repeating background image :( */
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#4CFFFFFF,endColorstr=#4CFFFFFF); /* needed for IE 6-7 */
zoom: 1; /* Hack needed for IE 6-8 */
}
/* To avoid IE more recent versions to apply opacity twice (once with rgba and once with filter), we need the following CSS3 selector hack (not supported by IE 6-8) */
.opacity_30:nth-child(n) {
filter: none;
}
*Important: To calculate ARGB(for IEs) from RGBA, we can use online tools:
I think this works, too:
int power = 1;
while(power < x)
power*=2;
And the answer is power
.
Here is a version that uses dataType html, but this is far less explicit, because i am returning an empty string to indicate an error.
Ajax call:
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'html',
data: {
email : $('#email').val()
},
success : function(data){
$('#waiting').hide(500);
$('#message').removeClass().addClass((data == '') ? 'error' : 'success')
.html(data).show(500);
if (data == '') {
$('#message').html("Format your email correcly");
$('#demoForm').show(500);
}
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#message').removeClass().addClass('error')
.text('There was an error.').show(500);
$('#demoForm').show(500);
}
});
post.php
<?php
sleep(1);
function processEmail($email) {
if (preg_match("#^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$#", $email)) {
// your logic here (ex: add into database)
return true;
}
return false;
}
if (processEmail($_POST['email'])) {
echo "<span>Your email is <strong>{$_POST['email']}</strong></span>";
}
You can use this:
var element = document.getElementById('txt');
var text = element.innerText || element.textContent;
element.innerHTML = text;
Depending on what you need, you can use either element.innerText
or element.textContent
. They differ in many ways. innerText
tries to approximate what would happen if you would select what you see (rendered html) and copy it to the clipboard, while textContent
sort of just strips the html tags and gives you what's left.
innerText
also has compatability with old IE browsers (came from there).
Press Ctrl + Space
to get a autocomplete hint.
An example (axios_example.js) using Axios in Node.js:
const axios = require('axios');
const express = require('express');
const app = express();
const port = process.env.PORT || 5000;
app.get('/search', function(req, res) {
let query = req.query.queryStr;
let url = `https://your.service.org?query=${query}`;
axios({
method:'get',
url,
auth: {
username: 'xxxxxxxxxxxxx',
password: 'xxxxxxxxxxxxx'
}
})
.then(function (response) {
res.send(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
});
var server = app.listen(port);
Be sure in your project directory you do:
npm init
npm install express
npm install axios
node axios_example.js
You can then test the Node.js REST API using your browser at: http://localhost:5000/search?queryStr=xxxxxxxxx
This is impossible because generics in Java are only considered at compile time. Thus, the Java generics are just some kind of pre-processor. However you can get the actual class of the members of the list.
Try using:
xattr -rd com.apple.quarantine directoryname
This takes care of recursively removing the pesky attribute everywhere.
That is an object, not an array. So you would do:
var json = { cool: 34.33, alsocool: 45454 };
json.supercool = 3.14159;
console.dir(json);
Unfortunately while I thought these answers may have worked for me, I struggled with a solution, as I'm using tables inside responsive tables - where the overflow-x is played with.
So, with that in mind, have a look at this link for a cleaner way, which doesn't have the weird width overflow issues. It worked for me in the end and was very easy to implement.
you can use enum constructor for enum to have primitive data type..
public enum DaysOfWeek {
MONDAY(1),
TUESDAY(2),
WEDNESDAY(3),
THURSDAY(4),
FRIDAY(5),
SATURDAY(6),
SUNDAY(7);
private int value;
private DaysOfWeek(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
private static final SparseArray<DaysOfWeek> map = new SparseArray<DaysOfWeek>();
static
{
for (DaysOfWeek daysOfWeek : DaysOfWeek.values())
map.put(daysOfWeek.value, daysOfWeek);
}
public static DaysOfWeek from(int value) {
return map.get(value);
}
}
you can use to pass int as extras then pull it from enum using its value.
I have changed min date property of date time picker by using this
$('#date').data("DateTimePicker").minDate(startDate);
I hope this one help to someone !
You are looking for -H
option in gnu grep.
find . -name '*bills*' -exec grep -H "put" {} \;
-H, --with-filename
Print the filename for each match.
I know this question is old and most answers here explains padding really well, but while trying to understand it myself I figured having a "visual" image of what is happening helped.
The processor reads the memory in "chunks" of a definite size (word). Say the processor word is 8 bytes long. It will look at the memory as a big row of 8 bytes building blocks. Every time it needs to get some information from the memory, it will reach one of those blocks and get it.
As seem in the image above, doesn't matter where a Char (1 byte long) is, since it will be inside one of those blocks, requiring the CPU to process only 1 word.
When we deal with data larger than one byte, like a 4 byte int or a 8 byte double, the way they are aligned in the memory makes a difference on how many words will have to be processed by the CPU. If 4-byte chunks are aligned in a way they always fit the inside of a block (memory address being a multiple of 4) only one word will have to be processed. Otherwise a chunk of 4-bytes could have part of itself on one block and part on another, requiring the processor to process 2 words to read this data.
The same applies to a 8-byte double, except now it must be in a memory address multiple of 8 to guarantee it will always be inside a block.
This considers a 8-byte word processor, but the concept applies to other sizes of words.
The padding works by filling the gaps between those data to make sure they are aligned with those blocks, thus improving the performance while reading the memory.
However, as stated on others answers, sometimes the space matters more then performance itself. Maybe you are processing lots of data on a computer that doesn't have much RAM (swap space could be used but it is MUCH slower). You could arrange the variables in the program until the least padding is done (as it was greatly exemplified in some other answers) but if that's not enough you could explicitly disable padding, which is what packing is.
We can't use "PHP in between JavaScript", because PHP runs on the server and JavaScript - on the client.
However we can generate JavaScript code as well as HTML, using all PHP features, including the escaping from HTML one.
Although this thread dates back to 2014, the issue can still be current to many of us. Here is how I dealt with it in a jQuery 1.12 /PHP 5.6 context:
PHP Code sample:
if (!empty($_SERVER['HTTP_ORIGIN'])) {
// Uh oh, this XHR comes from outer space...
// Use this opportunity to filter out referers that shouldn't be allowed to see this request
if (!preg_match('@\.partner\.domain\.net$@'))
die("End of the road if you're not my business partner.");
// otherwise oblige
header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
}
else {
// local request, no need to send a specific header for CORS
}
In particular, don't add an exit;
as no preflight is needed.
$(window).height();
To set anything in the middle you can use CSS.
<style>
#divCentre
{
position: absolute;
left: 50%;
top: 50%;
width: 300px;
height: 400px;
margin-left: -150px;
margin-top: -200px;
}
</style>
<div id="divCentre">I am at the centre</div>
dialog = new Dialog(getActivity(),android.R.style.Theme_Translucent_NoTitleBar);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.loading_screen);
Window window = dialog.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();
wlp.gravity = Gravity.CENTER;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_BLUR_BEHIND;
window.setAttributes(wlp);
dialog.getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
dialog.show();
try this.
When using regular expressions from RegexBuddy's library, make sure to use the same matching modes in your own code as the regex from the library. If you generate a source code snippet on the Use tab, RegexBuddy will automatically set the correct matching options in the source code snippet. If you copy/paste the regex, you have to do that yourself.
In this case, as others pointed out, you missed the case insensitivity option.
The code has the following issues:
<a4j:commandButton .../>
) does not work with attachments.a4j
tags.<a4j:commandButton .../>
to <h:commandButton .../>
.bw.write( getDomainDocument() );
to bw.write( document );
.String document = getDomainDocument();
to the first line of the try/catch
.<a4j:outputPanel.../>
(not shown) to <h:messages showDetail="false"/>
.Essentially, remove all the Ajax facilities related to the commandButton
. It is still possible to display error messages and leverage the RichFaces UI style.
I just tried these headers and got Excel 2013 on a Windows 7 PC to import the CSV file with special characters correctly. The Byte Order Mark (BOM) was the final key that made it work.
header('Content-Encoding: UTF-8'); header('Content-type: text/csv; charset=UTF-8'); header("Content-disposition: attachment; filename=filename.csv"); header("Pragma: public"); header("Expires: 0"); echo "\xEF\xBB\xBF"; // UTF-8 BOM
And yet another one which is very compact:
function ifSet(object, path) {
return path.split('.').reduce((obj, part) => obj && obj[part], object)
}
called:
let a = {b:{c:{d:{e:'found!'}}}}
ifSet(a, 'b.c.d.e') == 'found!'
ifSet(a, 'a.a.a.a.a.a') == undefined
It won't perform great since it's splitting a string (but increases readability of the call) and iterates over everything even if it's already obvious that nothing will be found (but increases readability of the function itself).
at least is faster than _.get
http://jsben.ch/aAtmc
In C++-11 you can do:
std::vector<int> v = {0, 1, 2, 3, 4, 5};
for (auto i : v)
{
// access by value, the type of i is int
std::cout << i << ' ';
}
std::cout << '\n';
See here for variations: https://en.cppreference.com/w/cpp/language/range-for
You can try this...
$(document).ready(function() {
$("button").click(function(){
var checkBoxValues = [];
$.each($("input[name='check_name']:checked"), function(){
checkBoxValues.push($(this).val());
});
console.log(checkBoxValues);
});
});
int lcmcal(int i,int y)
{
int n,x,s=1,t=1;
for(n=1;;n++)
{
s=i*n;
for(x=1;t<s;x++)
{
t=y*x;
}
if(s==t)
break;
}
return(s);
}
I'd do this one of two ways. Since you're setting your start and end dates in your t-sql code, i wouldn't ask for parameters in the stored proc
Option 1
Create Procedure [Test] AS
DECLARE @StartDate varchar(10)
DECLARE @EndDate varchar(10)
Set @StartDate = '201620' --Define start YearWeek
Set @EndDate = (SELECT CAST(DATEPART(YEAR,getdate()) AS varchar(4)) + CAST(DATEPART(WEEK,getdate())-1 AS varchar(2)))
SELECT
*
FROM
(SELECT DISTINCT [YEAR],[WeekOfYear] FROM [dbo].[DimDate] WHERE [Year]+[WeekOfYear] BETWEEN @StartDate AND @EndDate ) dimd
LEFT JOIN [Schema].[Table1] qad ON (qad.[Year]+qad.[Week of the Year]) = (dimd.[Year]+dimd.WeekOfYear)
Option 2
Create Procedure [Test] @StartDate varchar(10),@EndDate varchar(10) AS
SELECT
*
FROM
(SELECT DISTINCT [YEAR],[WeekOfYear] FROM [dbo].[DimDate] WHERE [Year]+[WeekOfYear] BETWEEN @StartDate AND @EndDate ) dimd
LEFT JOIN [Schema].[Table1] qad ON (qad.[Year]+qad.[Week of the Year]) = (dimd.[Year]+dimd.WeekOfYear)
Then run exec test '2016-01-01','2016-01-25'
PowerShell interpolates, does it not?
In PHP
echo "filesizecounter: " . $filesizecounter
can also be written as:
echo "filesizecounter: $filesizecounter"
In PowerShell something like this should suit your needs:
Write-Host "filesizecounter: $filesizecounter"
function useAdress () {
var id = $("#choose-address-table").find(".nr:first").text();
alert (id);
$("#resultas").append(id); // Testing: append the contents of the td to a div
};
then on your button:
onclick="useAdress()"
If you wanna have everything into one only piece of code, then you can mix tim's answer with the example's approach found on the API for JTextField, and you'll get something like this:
public class JTextFieldLimit extends JTextField {
private int limit;
public JTextFieldLimit(int limit) {
super();
this.limit = limit;
}
@Override
protected Document createDefaultModel() {
return new LimitDocument();
}
private class LimitDocument extends PlainDocument {
@Override
public void insertString( int offset, String str, AttributeSet attr ) throws BadLocationException {
if (str == null) return;
if ((getLength() + str.length()) <= limit) {
super.insertString(offset, str, attr);
}
}
}
}
Then there is no need to add a Document to the JTextFieldLimit due to JTextFieldLimit already have the functionality inside.
If you want to copy conditional formatting to another document you can use the "Copy to..." feature for the worksheet (click the tab with the name of the worksheet at the bottom) and copy the worksheet to the other document.
Then you can just copy what you want from that worksheet and right-click select "Paste special" -> "Paste conditional formatting only", as described earlier.
I have used the statement below on debian 10
apt-get install iputils-ping
I just ran into this issue, on the gpg CLI in Arch Linux. I needed to kill the existing "gpg-agent" process, then everything was back to normal ( a new gpg-agent should auto-launch when you invoke the gpg command, again; ...).
gpg-agent
in a terminal and/or reboot ...I have finally got this working. It expands on the solution from A. Garcia, however, since the problem lies in the hibernate type MaterializedBlob type just mapping Blob > bytea is not sufficient, we need a replacement for MaterializedBlobType which works with hibernates broken blob support. This implementation only works with bytea, but maybe the guy from the JIRA issue who wanted OID could contribute an OID implementation.
Sadly replacing these types at runtime is a pain, since they should be part of the Dialect. If only this JIRA enhanement gets into 3.6 it would be possible.
public class PostgresqlMateralizedBlobType extends AbstractSingleColumnStandardBasicType<byte[]> {
public static final PostgresqlMateralizedBlobType INSTANCE = new PostgresqlMateralizedBlobType();
public PostgresqlMateralizedBlobType() {
super( PostgresqlBlobTypeDescriptor.INSTANCE, PrimitiveByteArrayTypeDescriptor.INSTANCE );
}
public String getName() {
return "materialized_blob";
}
}
Much of this could probably be static (does getBinder() really need a new instance?), but I don't really understand the hibernate internal so this is mostly copy + paste + modify.
public class PostgresqlBlobTypeDescriptor extends BlobTypeDescriptor implements SqlTypeDescriptor {
public static final BlobTypeDescriptor INSTANCE = new PostgresqlBlobTypeDescriptor();
public <X> ValueBinder<X> getBinder(final JavaTypeDescriptor<X> javaTypeDescriptor) {
return new PostgresqlBlobBinder<X>(javaTypeDescriptor, this);
}
public <X> ValueExtractor<X> getExtractor(final JavaTypeDescriptor<X> javaTypeDescriptor) {
return new BasicExtractor<X>( javaTypeDescriptor, this ) {
protected X doExtract(ResultSet rs, String name, WrapperOptions options) throws SQLException {
return (X)rs.getBytes(name);
}
};
}
}
public class PostgresqlBlobBinder<J> implements ValueBinder<J> {
private final JavaTypeDescriptor<J> javaDescriptor;
private final SqlTypeDescriptor sqlDescriptor;
public PostgresqlBlobBinder(JavaTypeDescriptor<J> javaDescriptor, SqlTypeDescriptor sqlDescriptor) {
this.javaDescriptor = javaDescriptor; this.sqlDescriptor = sqlDescriptor;
}
...
public final void bind(PreparedStatement st, J value, int index, WrapperOptions options)
throws SQLException {
st.setBytes(index, (byte[])value);
}
}
I think everyone missed the "suddenly" part of this question. Most likely, your .jshintrc has a syntax error, so it's not including the 'browser' line. Run it through a json validator to see where the error is.
Simply we can format the date like,
var month = date.getMonth() + 1;
var day = date.getDate();
var date1 = (('' + day).length < 2 ? '0' : '') + day + '/' + (('' + month).length < 2 ? '0' : '') + month + '/' + date.getFullYear();
$("#txtDate").val($.datepicker.formatDate('dd/mm/yy', new Date(date1)));
Where "date" is a date in any format.
If you add in the style
br{
display: none;
}
Then this will work. Not sure if it will work in older versions of IE though.
The easiest way I've found to create postscripts is the following, using the setEPS()
command:
setEPS()
postscript("whatever.eps")
plot(rnorm(100), main="Hey Some Data")
dev.off()
I think you are right by saying that people cannot click half pixels, so personally, I would use rounded jQuery offset...
I wasn't quite sure where I would store the start position, so I want to elaborate on David Boikes comment. I found that I could store that variable in the ui.item object itself and retrieve it in the stop function as so:
$( "#sortable" ).sortable({
start: function(event, ui) {
ui.item.startPos = ui.item.index();
},
stop: function(event, ui) {
console.log("Start position: " + ui.item.startPos);
console.log("New position: " + ui.item.index());
}
});
str
is text representation in bytes, unicode
is text representation in characters.
You decode text from bytes to unicode and encode a unicode into bytes with some encoding.
That is:
>>> 'abc'.decode('utf-8') # str to unicode
u'abc'
>>> u'abc'.encode('utf-8') # unicode to str
'abc'
UPD Sep 2020: The answer was written when Python 2 was mostly used. In Python 3, str
was renamed to bytes
, and unicode
was renamed to str
.
>>> b'abc'.decode('utf-8') # bytes to str
'abc'
>>> 'abc'.encode('utf-8'). # str to bytes
b'abc'
Pass Today as value as mentioned below in $viewQuery property :
$web = Get-SPWeb "http://sitename"
$list = $web.Lists.TryGetList($listtitle)
write-host "Exporting '$($list.Title)' data from '$($web.Title)' site.."
$viewTitle = "Program Events" #Title property
#Add the column names from the ViewField property to a string collection
$viewFields = New-Object System.Collections.Specialized.StringCollection
$viewFields.Add("Event Date") > $null
$viewFields.Add("Title") > $null
#Query property
$viewQuery = "<Where><Geq><FieldRef Name='EventDate' /><Value IncludeTimeValue='TRUE' Type='DateTime'><Today/></Value></Geq></Where><OrderBy><FieldRef Name='EventDate' Ascending='True' /></OrderBy>"
#RowLimit property
$viewRowLimit = 30
#Paged property
$viewPaged = $true
#DefaultView property
$viewDefaultView = $false
#Create the view in the destination list
$newview = $list.Views.Add($viewTitle, $viewFields, $viewQuery, $viewRowLimit, $viewPaged, $viewDefaultView)
Write-Host ("View '" + $newview.Title + "' created in list '" + $list.Title + "' on site " + $web.Url)
$web.Dispose()
You need to add a name
attribute.
Since this is a multiple select, at the HTTP level, the client just sends multiple name/value pairs with the same name, you can observe this yourself if you use a form with method="GET": someurl?something=1&something=2&something=3
.
In the case of PHP, Ruby, and some other library/frameworks out there, you would need to add square braces ([]
) at the end of the name. The frameworks will parse that string and wil present it in some easy to use format, like an array.
Apart from manually parsing the request there's no language/framework/library-agnostic way of accessing multiple values, because they all have different APIs
For PHP you can use:
<select name="something[]" id="inscompSelected" multiple="multiple" class="lstSelected">
You can use dtype=np.int64
instead of dtype=int
select count(*)
from user_tab_columns
where table_name='MYTABLE' --use upper case
Instead of uppercase you can use lower function. Ex: select count(*) from user_tab_columns where lower(table_name)='table_name';
The ActivityManager class is the appropriate tool to see which processes are running.
To run in the background, you typically want to use a Service.
I would choose this simple solution.
Summarizing it:
#S
and sends it to the Clienth(pw)
(which is what is stored in the DB)#C
h(pw) + #S + #C
and calculates its hash, call it h(all)
username
, #C
and h(all)
h(pw)'
for the specified username
, from the DBh(all')
, like Client didh(all)
= h(all')
then h(pw)
= h(pw)'
, almost certainlyNo one can repeat the request to log in as the specified user. #S
adds a variable component to the hash, each time (it's fundamental). #C
adds additional noise in it.
This is how you do it using ASP.NET:
add .Format("{0:dd/MM/yyyy HH:mm:ss}");
@(Html.Kendo().Grid<AlphaStatic.Domain.ViewModels.AttributeHistoryViewModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(c => c.AttributeName);
columns.Bound(c => c.UpdatedDate).Format("{0:dd/MM/yyyy HH:mm:ss}");
})
.HtmlAttributes(new { @class = ".big-grid" })
.Resizable(x => x.Columns(true))
.Sortable()
.Filterable()
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.ServerOperation(false)
.Model(model =>
{
model.Id(c => c.Id);
})
.Read(read => read.Action("Read_AttributeHistory", "Attribute", new { attributeId = attributeId })))
)
For ViewPager2,
viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
}
})
where OnPageChangeCallback
is a static class with three methods:
onPageScrolled(int position, float positionOffset, @Px int positionOffsetPixels),
onPageSelected(int position),
onPageScrollStateChanged(@ScrollState int state)
You can use regular expressions for extracting the number from string. Lets check it. Suppose this is the string mixing text and numbers 'stack12345overflow569'. This one should work:
select regexp_replace('stack12345overflow569', '[[:alpha:]]|_') as numbers from dual;
which will return "12345569".
also you can use this one:
select regexp_replace('stack12345overflow569', '[^0-9]', '') as numbers,
regexp_replace('Stack12345OverFlow569', '[^a-z and ^A-Z]', '') as characters
from dual
which will return "12345569" for numbers and "StackOverFlow" for characters.
Leave your tables as they are. Just wrap the content inside the TD's with a span that has the truncation CSS applied.
/* CSS */
.truncate {
width: 50px; /*your fixed width */
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
display: block; /* this fixes your issue */
}
<!-- HTML -->
<table>
<tbody>
<tr>
<td>
<span class="truncate">
Table data to be truncated if it's too long.
</span>
</td>
</tr>
</tbody>
</table>
The contexts used for HTML Canvases have a built-in method for checking the size of a font. This method returns a TextMetrics
object, which has a width property that contains the width of the text.
function getWidthOfText(txt, fontname, fontsize){
if(getWidthOfText.c === undefined){
getWidthOfText.c=document.createElement('canvas');
getWidthOfText.ctx=getWidthOfText.c.getContext('2d');
}
var fontspec = fontsize + ' ' + fontname;
if(getWidthOfText.ctx.font !== fontspec)
getWidthOfText.ctx.font = fontspec;
return getWidthOfText.ctx.measureText(txt).width;
}
Or, as some of the other users have suggested, you can wrap it in a span
element:
function getWidthOfText(txt, fontname, fontsize){
if(getWidthOfText.e === undefined){
getWidthOfText.e = document.createElement('span');
getWidthOfText.e.style.display = "none";
document.body.appendChild(getWidthOfText.e);
}
if(getWidthOfText.e.style.fontSize !== fontsize)
getWidthOfText.e.style.fontSize = fontsize;
if(getWidthOfText.e.style.fontFamily !== fontname)
getWidthOfText.e.style.fontFamily = fontname;
getWidthOfText.e.innerText = txt;
return getWidthOfText.e.offsetWidth;
}
EDIT 2020: added font name+size caching at Igor Okorokov's suggestion.
First zip or gzip the folders:
Use the following command:
zip -r NameYouWantForZipFile.zip foldertozip/
or
tar -pvczf BackUpDirectory.tar.gz /path/to/directory
for gzip compression use SCP:
scp [email protected]:~/serverpath/public_html ~/Desktop
First you may check query
when the target column is type bool
(PS: about how to use it please check link )
df.query('BoolCol')
Out[123]:
BoolCol
10 True
40 True
50 True
After we filter the original df by the Boolean column we can pick the index .
df=df.query('BoolCol')
df.index
Out[125]: Int64Index([10, 40, 50], dtype='int64')
Also pandas have nonzero
, we just select the position of True
row and using it slice the DataFrame
or index
df.index[df.BoolCol.nonzero()[0]]
Out[128]: Int64Index([10, 40, 50], dtype='int64')
Include the following into build.gradle:
android.libraryVariants.all { variant ->
task("generate${variant.name}Javadoc", type: Javadoc) {
description "Generates Javadoc for $variant.name."
source = variant.javaCompile.source
ext.androidJar = "${android.plugin.sdkDirectory}/platforms/${android.compileSdkVersion}/android.jar"
classpath = files(variant.javaCompile.classpath.files) + files(ext.androidJar)
}
task("javadoc${variant.name}", type: Jar) {
classifier = "javadoc"
description "Bundles Javadoc into a JAR file for $variant.name."
from tasks["generate${variant.name}Javadoc"]
}
task("jar${variant.name}", type: Jar) {
description "Bundles compiled .class files into a JAR file for $variant.name."
dependsOn variant.javaCompile
from variant.javaCompile.destinationDir
exclude '**/R.class', '**/R$*.class', '**/R.html', '**/R.*.html'
}
}
You can then execute gradle with: ./gradlew clean javadocRelease jarRelease
which will build you your Jar and also a javadoc jar into the build/libs/
folder.
EDIT: With android gradle tools 1.10.+ getting the android SDK dir is different than before. You have to change the following (thanks Vishal!):
android.sdkDirectory
instead of
android.plugin.sdkDirectory
I figured out the problem. It ended up being a path to my config file was wrong. The errors for WCF are so helpful sometimes.
OK I have answered my own question (but is it the best way?)
This is how to run a method when you click or tap on some text in a TextView:
package com.textviewy;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class TextyView extends Activity implements OnClickListener {
TextView t ;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t = (TextView)findViewById(R.id.TextView01);
t.setOnClickListener(this);
}
public void onClick(View arg0) {
t.setText("My text on click");
}
}
and my main.xml is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<LinearLayout android:id="@+id/LinearLayout01" android:layout_width="wrap_content" android:layout_height="wrap_content"></LinearLayout>
<ListView android:id="@+id/ListView01" android:layout_width="wrap_content" android:layout_height="wrap_content"></ListView>
<LinearLayout android:id="@+id/LinearLayout02" android:layout_width="wrap_content" android:layout_height="wrap_content"></LinearLayout>
<TextView android:text="This is my first text"
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:textStyle="bold"
android:textSize="28dip"
android:editable = "true"
android:clickable="true"
android:layout_height="wrap_content">
</TextView>
</LinearLayout>
TCPDF 5.9.010 (2010-10-27) - Support for CSS properties 'border-spacing' and 'padding' for tables were added.
You can use multiple font faces quite easily. Below is an example of how I used it in the past:
<!--[if (IE)]><!-->
<style type="text/css" media="screen">
@font-face {
font-family: "Century Schoolbook";
src: url(/fonts/century-schoolbook.eot);
}
@font-face {
font-family: "Chalkduster";
src: url(/fonts/chalkduster.eot);
}
</style>
<!--<![endif]-->
<!--[if !(IE)]><!-->
<style type="text/css" media="screen">
@font-face {
font-family: "Century Schoolbook";
src: url(/fonts/century-schoolbook.ttf);
}
@font-face {
font-family: "Chalkduster";
src: url(/fonts/chalkduster.ttf);
}
</style>
<!--<![endif]-->
It is worth noting that fonts can be funny across different Browsers. Font face on earlier browsers works, but you need to use eot files instead of ttf.
That is why I include my fonts in the head of the html file as I can then use conditional IE tags to use eot or ttf files accordingly.
If you need to convert ttf to eot for this purpose there is a brilliant website you can do this for free online, which can be found at http://ttf2eot.sebastiankippe.com/.
Hope that helps.
You don't need to have a reportViewer control anywhere - you can create the LocalReport on the fly:
var lr = new LocalReport
{
ReportPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? @"C:\", "Reports", "PathOfMyReport.rdlc"),
EnableExternalImages = true
};
lr.DataSources.Add(new ReportDataSource("NameOfMyDataSet", model));
string mimeType, encoding, extension;
Warning[] warnings;
string[] streams;
var renderedBytes = lr.Render
(
"PDF",
@"<DeviceInfo><OutputFormat>PDF</OutputFormat><HumanReadablePDF>False</HumanReadablePDF></DeviceInfo>",
out mimeType,
out encoding,
out extension,
out streams,
out warnings
);
var saveAs = string.Format("{0}.pdf", Path.Combine(tempPath, "myfilename"));
var idx = 0;
while (File.Exists(saveAs))
{
idx++;
saveAs = string.Format("{0}.{1}.pdf", Path.Combine(tempPath, "myfilename"), idx);
}
using (var stream = new FileStream(saveAs, FileMode.Create, FileAccess.Write))
{
stream.Write(renderedBytes, 0, renderedBytes.Length);
stream.Close();
}
lr.Dispose();
You can also add parameters: (lr.SetParameter())
, handle subreports: (lr.SubreportProcessing+=YourHandler)
, or pretty much anything you can think of.
Sequelize methods return promises, and there is no delete()
method. Sequelize uses destroy()
instead.
Model.destroy({
where: {
some_field: {
//any selection operation
// for example [Op.lte]:new Date()
}
}
}).then(result => {
//some operation
}).catch(error => {
console.log(error)
})
Documentation for more details: https://www.codota.com/code/javascript/functions/sequelize/Model/destroy
If you move your for loop, you won't have to make multiple connections. Just a quick edit to your code block (by no means completely correct):
string StrQuery;
try
{
using (SqlConnection conn = new SqlConnection(ConnString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
conn.Open();
for(int i=0; i< dataGridView1.Rows.Count;i++)
{
StrQuery= @"INSERT INTO tableName VALUES ("
+ dataGridView1.Rows[i].Cells["ColumnName"].Text+", "
+ dataGridView1.Rows[i].Cells["ColumnName"].Text+");";
comm.CommandText = StrQuery;
comm.ExecuteNonQuery();
}
}
}
}
As to executing multiple SQL commands at once, please look at this link: Multiple statements in single SqlCommand
If you haven't restarted your SQL database Server after you make login changes, then make sure you do that. Start
->Programs
->Microsoft SQL Server
-> Configuration tools
-> SQL Server configuration manager
-> Restart Server
.
It looks like you only added the user to the server. You need to add them to the database too. Either open the database/Security/User/Add New User or open the server/Security/Logins/Properties/User Mapping.
Based on this article, you should:
create new branch which is based upon new version of master
git branch -b newmaster
merge your old feature branch into new one
git checkout newmaster
resolve conflict on new feature branch
The first two commands can be combined to git checkout -b newmaster
.
This way your history stays clear because you don't need back merges. And you don't need to be so super cautious since you don't need to do a Git rebase.
The solution I prefer is to mix arrays and ostream like this:
std::ostream& operator<<(std::ostream& lhs, WeekEnum e) {
static const std::array<std::string, 7> WEEK_STRINGS = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };
return os << WEEK_STRINGS[statuc_cast<WeekEnum>(e)]
}
cout << "Today is " << WeekEnum::Monday;
I also suggest to use enum class instead of Enum
If you want to know if it's an empty string use === instead of ==.
if(variable === "") {
}
This is because === will only return true if the values on both sides are of the same type, in this case a string.
for example: (false == "") will return true, and (false === "") will return false.
PGPORT=5432
PGHOST="my.database.domain.com"
PGUSER="postgres"
PGDB="mydb"
createdb -h $PGHOST -p $PGPORT -U $PGUSER $PGDB
Assuming you've fixed the syntax errors (you've closed the select box before the name attribute), you're using the same name for the select box as the submit button. Give the select box a different name.
The simplest way is to use the JsonPrimitive
class, which derives from JsonElement
, as shown below:
JsonElement element = new JsonPrimitive(yourString);
JsonObject result = element.getAsJsonObject();
1-check your security groups
2-check internet gateway
3-check route tables
this.<your_form>.form.markAsPristine();
this.<your_form>.form.markAsUntouched();
this.<your_form>.form.updateValueAndValidity();
can also help
Python dictionaries are mutable, so they don't seem like a good way to declare constants:
>>> constants = {"foo":1, "bar":2}
>>> print constants
{'foo': 1, 'bar': 2}
>>> constants["bar"] = 3
>>> print constants
{'foo': 1, 'bar': 3}
Working with just one class:
select {
width: 268px;
padding: 5px;
font-size: 16px;
line-height: 1;
border: 0;
border-radius: 5px;
height: 34px;
background: url(http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png) no-repeat right #ddd;
-webkit-appearance: none;
background-position-x: 244px;
}
Based on your question, I think that you may be a bit confused about the difference between a User and a Login. A Login is an account on the SQL Server as a whole - someone who is able to log in to the server and who has a password. A User is a Login with access to a specific database.
Creating a Login is easy and must (obviously) be done before creating a User account for the login in a specific database:
CREATE LOGIN NewAdminName WITH PASSWORD = 'ABCD'
GO
Here is how you create a User with db_owner privileges using the Login you just declared:
Use YourDatabase;
GO
IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'NewAdminName')
BEGIN
CREATE USER [NewAdminName] FOR LOGIN [NewAdminName]
EXEC sp_addrolemember N'db_owner', N'NewAdminName'
END;
GO
Now, Logins are a bit more fluid than I make it seem above. For example, a Login account is automatically created (in most SQL Server installations) for the Windows Administrator account when the database is installed. In most situations, I just use that when I am administering a database (it has all privileges).
However, if you are going to be accessing the SQL Server from an application, then you will want to set the server up for "Mixed Mode" (both Windows and SQL logins) and create a Login as shown above. You'll then "GRANT" priviliges to that SQL Login based on what is needed for your app. See here for more information.
UPDATE: Aaron points out the use of the sp_addsrvrolemember to assign a prepared role to your login account. This is a good idea - faster and easier than manually granting privileges. If you google it you'll see plenty of links. However, you must still understand the distinction between a login and a user.
It is because of the period in the file name. It is stupid, but anytime there is a period in the js file name you will get this error, and I have come across situations where it will actually prevent the js file from loading.
v
has 10
element, the index starts from 0
to 9
.
for(int j=10;j>0;--j)
{
cout<<v[j]; // v[10] out of range
}
you should update for
loop to
for(int j=9; j>=0; --j)
// ^^^^^^^^^^
{
cout<<v[j]; // out of range
}
Or use reverse iterator to print element in reverse order
for (auto ri = v.rbegin(); ri != v.rend(); ++ri)
{
std::cout << *ri << std::endl;
}
In code, you need to explicitly create a Brush
instance:
Fill = new SolidColorBrush(Color.FromArgb(0xff, 0xff, 0x90))
As a matter of fact, HTML character entites also work : http://www.w3.org/TR/html4/sgml/entities.html.
It lets you insert special characters like bullets '•' (•), '™' (™), ... the HTML way.
Note that you can also (and probably should) type special characters directly in the form fields if you can enter international characters.
=> one consideration here is whether or not you care about third-party sites that collect data on your app from Google Play : some might simply take it as HTML content, others might insert it in a native application that just understand plain Unicode...
GRANT SELECT ON *.* TO 'user'@'localhost' IDENTIFIED BY 'password';
This will create a user with SELECT
privilege for all database including Views.
Warning: Only one null row can be in the column you've set to be unique.
You can do this with a filtered index in SQL 2008:
CREATE UNIQUE NONCLUSTERED INDEX idx_col1
ON dbo.MyTable(col1)
WHERE col1 IS NOT NULL;
See Field value must be unique unless it is NULL for a range of answers.
If you are using it within rails - activerecord validation you can set
allow_blank: true
As:
validates :email, allow_blank: true, format: { with: EMAIL_REGEX }
That is correct. When you do that you are casting it it into an employee
object, so that means you cannot access anything manager specific.
Downcasting is where you take a base class and then try and turn it into a more specific class. This can be accomplished with using is and an explicit cast like this:
if (employee is Manager)
{
Manager m = (Manager)employee;
//do something with it
}
or with the as
operator like this:
Manager m = (employee as Manager);
if (m != null)
{
//do something with it
}
If anything is unclear I'll be happy to correct it!
Here is my function changing the selected option. It works for jQuery 1.3.2
function selectOption(select_id, option_val) {
$('#'+select_id+' option:selected').removeAttr('selected');
$('#'+select_id+' option[value='+option_val+']').attr('selected','selected');
}
I had this issue with javascript calls. I fixed that with just requiring jquery_ujs into application.js file.
I believe you are looking for:
Just pass it the localhost IP.
There is also a gethostbyname function, that is also usefull.
By using typed arrays, you can store arrays of these types:
For example:
?var array = new Uint8Array(100);
array[42] = 10;
alert(array[42]);?
See it in action here.
You just need to initialize your NSMutableArray
NSMutableArray *myArray = [[NSMutableArray alloc] init];
If you've opened a table and you want to clear an existing value to NULL, click on the value, and press Ctrl
+0
.
If X
and beta
do not have the same shape as the second term in the rhs of your last line (i.e. nsample
), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.
I would recommend looking at the numpy broadcasting rules.
Here is a very simple and easy to follow example.
private int CalculateAge()
{
//get birthdate
DateTime dtBirth = Convert.ToDateTime(BirthDatePicker.Value);
int byear = dtBirth.Year;
int bmonth = dtBirth.Month;
int bday = dtBirth.Day;
DateTime dtToday = DateTime.Now;
int tYear = dtToday.Year;
int tmonth = dtToday.Month;
int tday = dtToday.Day;
int age = tYear - byear;
if (bmonth < tmonth)
age--;
else if (bmonth == tmonth && bday>tday)
{
age--;
}
return age;
}
With 'Enter' is better use ReadLine() or Read(2), because key 'Enter' generate 2 symbols. If user enter any text next Pause() also wil be skipped even with Read(2). So ReadLine() is better:
Sub Pause()
WScript.Echo ("Press Enter to continue")
z = WScript.StdIn.ReadLine()
End Sub
More examples look in http://technet.microsoft.com/en-us/library/ee156589.aspx
hi i got the same problem.. add 0.71 to excel cell width value and give that value to the
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(10);
eg: A Column width = 3.71 (excel value)
give column width = 4.42
will give the output file with same cell width.
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(4.42);
hope this help
inside the Form, You can use this code. Replace your variable name (i use $variable)
<input type="text" value="<?php echo (isset($variable))?$variable:'';?>">
If the browser that you are planning to use is Mozilla (Addon development) (not sure of chrome) you can use the following method in Javascript
function DOM( string )
{
var {Cc, Ci} = require("chrome");
var parser = Cc["@mozilla.org/xmlextras/domparser;1"].createInstance(Ci.nsIDOMParser);
console.log("PARSING OF DOM COMPLETED ...");
return (parser.parseFromString(string, "text/html"));
};
Hope this helps
You can give the surrounding div
a
text-align: right
this will leave white space to the left of the image. (= the image will occupy the whole line).
If you want content to be shown to the left hand side of the image, use
float: right
on the image. However, the surrounding div
will then need overflow: auto
to stretch to the needed height.
Issue resolved.!!! Below are the solutions.
For Java 6: Add below jars into {JAVA_HOME}/jre/lib/ext. 1. bcprov-ext-jdk15on-154.jar 2. bcprov-jdk15on-154.jar
Add property into {JAVA_HOME}/jre/lib/security/java.security security.provider.1=org.bouncycastle.jce.provider.BouncyCastleProvider
Java 7:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html
Java 8:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html
Issue is that it is failed to decrypt 256 bits of encryption.
There is no Javascript API to send ping frames or receive pong frames. This is either supported by your browser, or not. There is also no API to enable, configure or detect whether the browser supports and is using ping/pong frames. There was discussion about creating a Javascript ping/pong API for this. There is a possibility that pings may be configurable/detectable in the future, but it is unlikely that Javascript will be able to directly send and receive ping/pong frames.
However, if you control both the client and server code, then you can easily add ping/pong support at a higher level. You will need some sort of message type header/metadata in your message if you don't have that already, but that's pretty simple. Unless you are planning on sending pings hundreds of times per second or have thousands of simultaneous clients, the overhead is going to be pretty minimal to do it yourself.
setattr(x, attr, 'magic')
For help on it:
>>> help(setattr)
Help on built-in function setattr in module __builtin__:
setattr(...)
setattr(object, name, value)
Set a named attribute on an object; setattr(x, 'y', v) is equivalent to
``x.y = v''.
Edit: However, you should note (as pointed out in a comment) that you can't do that to a "pure" instance of object
. But it is likely you have a simple subclass of object where it will work fine. I would strongly urge the O.P. to never make instances of object like that.
sed is line based, so I'm not sure why you want to do this with sed. The paradigm is more processing one line at a time( you could also programatically find the # of fields in the CSV and generate your header line with awk) Why not just
echo "c1, c2, ... " >> file
cat testfile.csv >> file
?
Installation:
for 10.10:
sudo add-apt-repository "deb http://archive.canonical.com/ maverick partner"
for 11.04
sudo add-apt-repository "deb http://archive.canonical.com/ natty partner"
Continue with:
sudo apt-get update
sudo apt-get install sun-java6-jre sun-java6-plugin
Use as default:
sudo update-alternatives --config java
Installing JDK:
sudo apt-get install sun-java6-jdk
Source code (to be used in development):
sudo apt-get install sun-java6-source
Source of these instructions: https://help.ubuntu.com/community/Java
Here is the codepen demo showing the solution:
Important highlights:
html
, body
, ... .container
, should have the height set to 100%flex
to ANY of the flex items will trigger calculation of the items sizes based on flex distribution:
flex
, for example: flex: 1
then this flex item will occupy the remaining of the spaceflex
property, the calculation will be more complicated. For example, if the item 1 is set to flex: 1
and the item 2 is se to flex: 2
then the item 2 will take twice more of the remaining space
flex-direction
propertyflex
property: https://www.w3.org/TR/css-flexbox-1/#propdef-flex
min-*
and max-*
will be respecteddo you have sklearn? if not, do the following:
sudo pip install sklearn
After installing sklearn
from sklearn.model_selection import train_test_split
works fine
**Replacing href attribut value to other**
<div class="cpt">
<a href="/ref/ref/testone.html">testoneLink</a>
</div>
<div class="test" >
<a href="/ref/ref/testtwo.html">testtwoLInk</a>
</div>
<!--Remove first default Link from href attribut -->
<script>
Remove first default Link from href attribut
$(".cpt a").removeAttr("href");
Add Link to same href attribut
var testurl= $(".test").find("a").attr("href");
$(".test a").attr('href', testurl);
</script>
In general, to make a raw string out of a string variable, I use this:
string = "C:\\Windows\Users\alexb"
raw_string = r"{}".format(string)
output:
'C:\\\\Windows\\Users\\alexb'
Here is the sample program.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ReadFromConsole {
public static void main(String[] args) {
System.out.println("Enter here : ");
try{
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
String value = bufferRead.readLine();
System.out.println(value);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
You can get it easily when you search in Internet. StackExchange recommends to do some research and put some effort before reaching it.
I just used the @misir-jafarov and is working now with :
here is my code :
if (document.documentMode || /Edge/.test(navigator.userAgent)) {
jQuery('.art-img img').each(function(){
var t = jQuery(this),
s = 'url(' + t.attr('src') + ')',
p = t.parent(),
d = jQuery('<div></div>');
p.append(d);
d.css({
'height' : t.parent().css('height'),
'background-size' : 'cover',
'background-repeat' : 'no-repeat',
'background-position' : '50% 20%',
'background-image' : s
});
t.hide();
});
}
Hope it helps.
declare @TempTable table([Date] datetime)
insert into @TempTable([Date])
values('2008-01-02'),('2007-08-21')
select datepart(year, [Date]) as [year]
,convert(varchar(10),datepart(year, [Date])) + '-Q' + convert(varchar(3),datename(quarter, [Date])) as quarter_with_year
,datefromparts(datepart(year, [Date]),(convert(varchar(3),datename(quarter, [Date])) * 3)-2,1) as quarter_startdate
,eomonth(datefromparts(datepart(year, [Date]),convert(varchar(3),datename(quarter, [Date])) * 3,1)) as quarter_enddate
FROM @TempTable
This returns the year,quarter, and start end date of quarter.
$("**:**input[type=text], :input[type='textarea']").css({width: '90%'});
I ran into this issue in a web api project.
Api project was using a nuget package of a library with version 3. And one of the referenced assemblies say X was using older version of the same nuget package with version 2.
Whenever referenced assembly is built or any other project referencing X is rebuilt, api project's assemblies gets updated with lower version. And got this assembly reference error.
Rebuild works but in my case I wanted a long term solution.
I made the assemblies reference same version of nuget package.
I improved the cychan's solution, to be like that:
<html>
<head>
<style>
.wrapper{
display: inline;
float: left;
width: 180px;
overflow: hidden;
}
.selectArrow{
display: inline;
float: left;
width: 17px;
height: 20px;
border:1px solid #7f9db9;
border-left: none;
background: url('selectArrow.png') no-repeat 1px 1px;
}
.selectArrow-mousedown{background: url('selectArrow-mousedown.png') no-repeat 1px 1px;}
.selectArrow-mouseover{background: url('selectArrow-mouseover.png') no-repeat 1px 1px;}
</style>
<script language="javascript" src="jquery-1.3.2.min.js"></script>
<script language="javascript">
$(document).ready(function(){
$('#w1').wrap("<div class='wrapper'></div>");
$('.wrapper').after("<div class='selectArrow'/>");
$('.wrapper').find('select').mousedown(function(){
$(this).parent().next().addClass('selectArrow-mousedown').removeClass('selectArrow-mouseover');
}).
mouseup(function(){
$(this).parent().next().removeClass('selectArrow-mousedown').addClass('selectArrow-mouseover');
}).
hover(function(){
$(this).parent().next().addClass('selectArrow-mouseover');
}, function(){
$(this).parent().next().removeClass('selectArrow-mouseover');
});
$('.selectArrow').click(function(){
$(this).prev().find('select').focus();
});
$('.selectArrow').mousedown(function(){
$(this).addClass('selectArrow-mousedown').removeClass('selectArrow-mouseover');
}).
mouseup(function(){
$(this).removeClass('selectArrow-mousedown').addClass('selectArrow-mouseover');
}).
hover(function(){
$(this).addClass('selectArrow-mouseover');
}, function(){
$(this).removeClass('selectArrow-mouseover');
});
});
</script>
</head>
<body>
<select id="w1">
<option value="0">AnyAnyAnyAnyAnyAnyAny</option>
<option value="1">AnyAnyAnyAnyAnyAnyAnyAnyAnyAnyAnyAnyAnyAny</option>
</select>
</body>
</html>
The PNGs used in css classes are uploaded here...
And you still need JQuery.....
Public Shared SaveCommand_AltS As New RoutedCommand
SaveCommand_AltS.InputGestures.Add(New KeyGesture(Key.S, ModifierKeys.Control))
Me.CommandBindings.Add(New CommandBinding(SaveCommand_AltS, AddressOf Me.save))
No XAML is needed.
As an add-on to others' excellent posts, here's an article summarizing these techniques:
I know this is a bit late but what I did to our application is this. Hope this will help someone tho. But it works for me:
SELECT * FROM `landmarks` WHERE `landmark_name` OR `landmark_description` OR `landmark_address` LIKE '%keyword'
OR `landmark_name` OR `landmark_description` OR `landmark_address` LIKE 'keyword%'
OR `landmark_name` OR `landmark_description` OR `landmark_address` LIKE '%keyword%'
Modern C++ makes this super simple.
C++20 introduces std::format
, which allows you to do exactly that. It uses replacement fields similar to those in python:
#include <iostream>
#include <format>
int main() {
std::cout << std::format("Hello {}!\n", "world");
}
Code from cppreference.com, CC BY-SA and GFDL
Check out the compiler support page to see if it's available in your standard library implementation. As of 2020-11-06, it's not supported by any, so you'll have to resort to the C++11 solution below.
With C++11s std::snprintf
, this already became a pretty easy and safe task.
#include <memory>
#include <string>
#include <stdexcept>
template<typename ... Args>
std::string string_format( const std::string& format, Args ... args )
{
int size = snprintf( nullptr, 0, format.c_str(), args ... ) + 1; // Extra space for '\0'
if( size <= 0 ){ throw std::runtime_error( "Error during formatting." ); }
std::unique_ptr<char[]> buf( new char[ size ] );
snprintf( buf.get(), size, format.c_str(), args ... );
return std::string( buf.get(), buf.get() + size - 1 ); // We don't want the '\0' inside
}
The code snippet above is licensed under CC0 1.0.
Aim: Write to a char*
by using std::snprintf
and then convert that to a std::string
.
First, we determine the desired length of the char array using a special condition in snprintf
. From cppreference.com:
Return value
[...] If the resulting string gets truncated due to buf_size limit, function returns the total number of characters (not including the terminating null-byte) which would have been written, if the limit was not imposed.
This means that the desired size is the number of characters plus one, so that the null-terminator will sit after all other characters and that it can be cut off by the string constructor again. This issue was explained by @alexk7 in the comments.
int size = snprintf( nullptr, 0, format.c_str(), args ... ) + 1;
snprintf
will return a negative number if an error occurred, so we then check whether the formatting worked as desired. Not doing this could lead to silent errors or the allocation of a huge buffer, as pointed out by @ead in the comments.
if( size <= 0 ){ throw std::runtime_error( "Error during formatting." ); }
Next, we allocate a new character array and assign it to a std::unique_ptr
. This is generally advised, as you won't have to manually delete
it again.
Note that this is not a safe way to allocate a unique_ptr
with user-defined types as you can not deallocate the memory if the constructor throws an exception!
std::unique_ptr<char[]> buf( new char[ size ] );
After that, we can of course just use snprintf
for its intended use and write the formatted string to the char[]
.
snprintf( buf.get(), size, format.c_str(), args ... );
Finally, we create and return a new std::string
from that, making sure to omit the null-terminator at the end.
return std::string( buf.get(), buf.get() + size - 1 );
You can see an example in action here.
If you also want to use std::string
in the argument list, take a look at this gist.
Additional information for Visual Studio users:
As explained in this answer, Microsoft renamed std::snprintf
to _snprintf
(yes, without std::
). MS further set it as deprecated and advises to use _snprintf_s
instead, however _snprintf_s
won't accept the buffer to be zero or smaller than the formatted output and will not calculate the outputs length if that occurs.
So in order to get rid of the deprecation warnings during compilation, you can insert the following line at the top of the file which contains the use of _snprintf
:
#pragma warning(disable : 4996)
A lot of answers to this question were written before the time of C++11 and use fixed buffer lengths or vargs. Unless you're stuck with old versions of C++, I wouldn't recommend using those solutions. Ideally, go the C++20 way.
Because the C++11 solution in this answer uses templates, it can generate quite a bit of code if it is used a lot. However, unless you're developing for an environment with very limited space for binaries, this won't be a problem and is still a vast improvement over the other solutions in both clarity and security.
If space efficiency is super important, these two solution with vargs and vsnprintf can be useful. DO NOT USE any solutions with fixed buffer lengths, that is just asking for trouble.
UPDATE: As Brad Parks wrote in his comment there is a much better and easier solution with only one line of JS code:
run
setTimeout(function(){debugger;},5000);
, then go show your element and wait until it breaks into the Debugger
Original answer:
I just had the same problem, and I think I found an "universal" solution. (assuming the site uses jQuery)
Hope it helps someone!
<body>
and click "Edit as HTML"<body>
then press Ctrl+Enter: <div id="debugFreeze" data-rand="0"></div>
setTimeout(function(){$("#debugFreeze").attr("data-rand",Math.random())},5000);
Of course you can modify the javascript and the timing, if you get the idea.
Quick and dirty:
head -16428 < file.in | tail -259 > file.out
Probably not the best way to do it but it should work.
BTW: 259 = 16482-16224+1.
In my case Eclipse wasn't properly picking up a Java project that a current project was dependent on.
You can go to Project > BuildPath > Configure BuildPath and then delete and re-add the project.
For me it was the difference between
var response = Request.CreateResponse(HttpStatusCode.OK, new StringContent(log, System.Text.Encoding.UTF8, "application/octet-stream");
and
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(log, System.Text.Encoding.UTF8, "application/octet-stream");
The first one was returning the JSON representation of StringContent: {"Headers":[{"Key":"Content-Type","Value":["application/octet-stream; charset=utf-8"]}]}
While the second one was returning the file proper.
It seems that Request.CreateResponse has an overload that takes a string as the second parameter and this seems to have been what was causing the StringContent object itself to be rendered as a string, instead of the actual content.
Export Particular DataBases
djimi:> mysqldump --user=root --host=localhost --port=3306 --password=test -B CCR KIT >ccr_kit_local.sql
this will export CCR and KIT databases...
Import All Exported DB to Particular Mysql Instance (You have to be where your dump file is)
djimi:> mysql --user=root --host=localhost --port=3306 --password=test < ccr_kit_local.sql
Problem is not in installer
replace nodejs with node or change the path from /usr/bin/nodejs to /usr/bin/node
I know I'm a bit late to the party here but I was having a very similar problem but it included using tkinter as a GUI, and the mainloop made it impossible to use any of the solutions that depend on .join(). Therefore I adapted the solution given in the EDIT of the original question, but made it more general to make it easier to understand for others.
Here is the new thread class in action:
import threading
import traceback
import logging
class ExceptionThread(threading.Thread):
def __init__(self, *args, **kwargs):
threading.Thread.__init__(self, *args, **kwargs)
def run(self):
try:
if self._target:
self._target(*self._args, **self._kwargs)
except Exception:
logging.error(traceback.format_exc())
def test_function_1(input):
raise IndexError(input)
if __name__ == "__main__":
input = 'useful'
t1 = ExceptionThread(target=test_function_1, args=[input])
t1.start()
Of course you can always have it handle the exception some other way from logging, such as printing it out, or having it output to the console.
This allows you to use the ExceptionThread class exactly like you would the Thread class, without any special modifications.
Many Cocoa APIs require NSObject subclasses, which forces you into using class. But other than that, you can use the following cases from Apple’s Swift blog to decide whether to use a struct / enum value type or a class reference type.
I'm going to make a couple of assumptions in my answer. I'm assuming your data starts in A1 and there are no empty cells in the first column of each row that has data.
This code will:
This is not a fast method but will iterate through each one individually as you suggested is your intention.
Sub iterateThroughAll()
ScreenUpdating = False
Dim wks As Worksheet
Set wks = ActiveSheet
Dim rowRange As Range
Dim colRange As Range
Dim LastCol As Long
Dim LastRow As Long
LastRow = wks.Cells(wks.Rows.Count, "A").End(xlUp).Row
Set rowRange = wks.Range("A1:A" & LastRow)
'Loop through each row
For Each rrow In rowRange
'Find Last column in current row
LastCol = wks.Cells(rrow, wks.Columns.Count).End(xlToLeft).Column
Set colRange = wks.Range(wks.Cells(rrow, 1), wks.Cells(rrow, LastCol))
'Loop through all cells in row up to last col
For Each cell In colRange
'Do something to each cell
Debug.Print (cell.Value)
Next cell
Next rrow
ScreenUpdating = True
End Sub
Similar to the Ubuntu answer above, the Windows admin default password is stored in {jenkins install dir}\secrets\initialAdminPassword file (default install location would it in C:\Program Files (x86)\Jenkins\secrets\initialAdminPassword )
With Guava you can write:
ArrayList<String> places = Lists.newArrayList("Buenos Aires", "Córdoba", "La Plata");
In Guava there are also other useful static constructors. You can read about them here.
http://blog.parkji.co.uk/2013/08/11/native-drag-and-drop-in-angularjs.html This is simple method for creating native draggable angularJS elements
You need to use delimiters with regexes in PHP. You can use the often used /
, but PHP lets you use any matching characters, so @
and #
are popular.
If you are interpolating variables inside your regex, be sure to pass the delimiter you chose as the second argument to preg_quote()
.
You have to write you own remove. You can loop over the array, grab the index of the item you want to remove, and use splice
to remove it.
Alternatively, you can create a new array, loop over the current array, and if the current object doesn't match what you want to remove, put it in a new array.
To create a Java project: create a new project directory, jump into it and execute
gradle init --type java-library
Source folders and a Gradle build file (including a wrapper) will be build.
try this
<?php
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
?>
$("input[name='option[colour]'] :checked ")
Even the auto-increment column is not PK ( in this example it is called seq - aka sequence ) you could achieve that with a trigger :
DROP TABLE IF EXISTS devops_guide CASCADE;
SELECT 'create the "devops_guide" table'
;
CREATE TABLE devops_guide (
guid UUID NOT NULL DEFAULT gen_random_uuid()
, level integer NULL
, seq integer NOT NULL DEFAULT 1
, name varchar (200) NOT NULL DEFAULT 'name ...'
, description text NULL
, CONSTRAINT pk_devops_guide_guid PRIMARY KEY (guid)
) WITH (
OIDS=FALSE
);
-- START trg_devops_guide_set_all_seq
CREATE OR REPLACE FUNCTION fnc_devops_guide_set_all_seq()
RETURNS TRIGGER
AS $$
BEGIN
UPDATE devops_guide SET seq=col_serial FROM
(SELECT guid, row_number() OVER ( ORDER BY seq) AS col_serial FROM devops_guide ORDER BY seq) AS tmp_devops_guide
WHERE devops_guide.guid=tmp_devops_guide.guid;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER trg_devops_guide_set_all_seq
AFTER UPDATE OR DELETE ON devops_guide
FOR EACH ROW
WHEN (pg_trigger_depth() < 1)
EXECUTE PROCEDURE fnc_devops_guide_set_all_seq();
import itertools
ab = itertools.chain(['it'], ['was'], ['annoying'])
list(ab)
Just another method....
Seems you are looking for ORDER BY
in DESC
ending order with LIMIT clause:
SELECT
*
FROM
scores
ORDER BY score DESC
LIMIT 10
Of course SELECT *
could seriously affect performance, so use it with caution.
This will work for sure, and I actually tried it out:
lwdba@localhost (DB test) :: DROP TABLE IF EXISTS shirts;
Query OK, 0 rows affected (0.08 sec)
lwdba@localhost (DB test) :: CREATE TABLE shirts
-> (<BR>
-> id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> ticketnumber INT,
-> colors VARCHAR(30)
-> );<BR>
Query OK, 0 rows affected (0.19 sec)
lwdba@localhost (DB test) :: INSERT INTO shirts (ticketnumber,colors) VALUES
-> (32423,'1,2,5,12,15'),
-> (32424,'1,5,12,15,30'),
-> (32425,'2,5,11,15,28'),
-> (32426,'1,2,7,12,15'),
-> (32427,'2,4,8,12,15');
Query OK, 5 rows affected (0.06 sec)
Records: 5 Duplicates: 0 Warnings: 0
lwdba@localhost (DB test) :: SELECT * FROM shirts WHERE LOCATE(CONCAT(',', 1 ,','),CONCAT(',',colors,',')) > 0;
+----+--------------+--------------+
| id | ticketnumber | colors |
+----+--------------+--------------+
| 1 | 32423 | 1,2,5,12,15 |
| 2 | 32424 | 1,5,12,15,30 |
| 4 | 32426 | 1,2,7,12,15 |
+----+--------------+--------------+
3 rows in set (0.00 sec)
Give it a Try !!!
Neither a ":" nor a "." will show up in valid Base64, so I think you can unambiguously throw away the http://www.stackoverflow.com
line. In Perl, say, something like
my $sanitized_str = join q{}, grep {!/[^A-Za-z0-9+\/=]/} split /\n/, $str;
say decode_base64($sanitized_str);
might be what you want. It produces
This is simple ASCII Base64 for StackOverflow exmaple.
@jason-mccreary is totally right. Besides I recommend you this code to get more info in case of malfunction:
$rest = curl_exec($crl);
if ($rest === false)
{
// throw new Exception('Curl error: ' . curl_error($crl));
print_r('Curl error: ' . curl_error($crl));
}
curl_close($crl);
print_r($rest);
EDIT 1
To debug you can set CURLOPT_HEADER
to true to check HTTP response with firebug::net or similar.
curl_setopt($crl, CURLOPT_HEADER, true);
EDIT 2
About Curl error: SSL certificate problem, verify that the CA cert is OK
try adding this headers (just to debug, in a production enviroment you should keep these options in true
):
curl_setopt($crl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($crl, CURLOPT_SSL_VERIFYPEER, false);
First google search yielded me this answer. So I thought of updating this with newer version of attach, detach.
Create database dbname
On
(
Filename= 'path where you copied files',
Filename ='path where you copied log'
)
For attach;
Further,if your database is cleanly shutdown(there are no active transactions while database was shutdown) and you dont have log file,you can use below method,SQL server will create a new transaction log file..
Create database dbname
On
(
Filename= 'path where you copied files'
)
For attach;
if you don't specify transaction log file,SQL will try to look in the default path and will try to use it irrespective of whether database was cleanly shutdown or not..
Here is what MSDN has to say about this..
If a read-write database has a single log file and you do not specify a new location for the log file, the attach operation looks in the old location for the file. If it is found, the old log file is used, regardless of whether the database was shut down cleanly. However, if the old log file is not found and if the database was shut down cleanly and has no active log chain, the attach operation attempts to build a new log file for the database.
There are some restrictions with this approach and some side affects too..
1.attach-and-detach operations both disable cross-database ownership chaining for the database
2.Database trustworthy is set to off
3.Detaching a read-only database loses information about the differential bases of differential backups.
Most importantly..you can't attach a database with recent versions to an earlier version
References:
https://msdn.microsoft.com/en-in/library/ms190794.aspx
To use the hex
encoding in Python 3, use
>>> import codecs
>>> codecs.encode(b"c", "hex")
b'63'
In legacy Python, there are several other ways of doing this:
>>> hex(ord("c"))
'0x63'
>>> format(ord("c"), "x")
'63'
>>> "c".encode("hex")
'63'