The other answers do not seem to touch on a key aspect here, and that is you make no mention of requiring supporting a web browser as a client. Most of the limitations of plain HTTP above are assuming you would be working with browser/ JS implementations.
The HTTP protocol is fully capable of full-duplex communication; it is legal to have a client perform a POST with a chunked encoding transfer, and a server to return a response with a chunked-encoding body. This would remove the header overhead to just at init time.
So if all you're looking for is full-duplex, control both client and server, and are not interested in extra framing/features of WebSockets, then I would argue that HTTP is a simpler approach with lower latency/CPU (although the latency would really only differ in microseconds or less for either).
An alternative using perl would be:
perl -pe 's/(.*) (.*)$/$2/' file
where you may change \t
for whichever the delimiter of file
is
Variable scope in Ruby is controlled by sigils to some degree. Variables starting with $
are global, variables with @
are instance variables, @@
means class variables, and names starting with a capital letter are constants. All other variables are locals. When you open a class or method, that's a new scope, and locals available in the previous scope aren't available.
I generally prefer to avoid creating global variables. There are two techniques that generally achieve the same purpose that I consider cleaner:
Create a constant in a module. So in this case, you would put all the classes that need the offset in the module Foo
and create a constant Offset
, so then all the classes could access Foo::Offset
.
Define a method to access the value. You can define the method globally, but again, I think it's better to encapsulate it in a module or class. This way the data is available where you need it and you can even alter it if you need to, but the structure of your program and the ownership of the data will be clearer. This is more in line with OO design principles.
Actually an enum
's default is the first element in the enum
whose value is 0
.
So for example:
public enum Animals
{
Cat,
Dog,
Pony = 0,
}
//its value will actually be Cat not Pony unless you assign a non zero value to Cat.
Animals animal;
It may just be my opinion, but there's another serious error in your program (setting aside the given 'prime number' question, which has been thoroughly answered).
Like the rest of the responders, I'm assuming this is homework, which indicates you want to become a developer (presumably).
You need to learn to compartmentalize your code. It's not something you'll always need to do in a project, but it's good to know how to do it.
Your method prime_num(long num) could stand a better, more descriptive name. And if it is supposed to find all prime numbers less than a given number, it should return them as a list. This makes it easier to seperate your display and your functionality.
If it simply returned an IList containing prime numbers you could then display them in your main function (perhaps calling another outside function to pretty print them) or use them in further calculations down the line.
So my best recommendation to you is to do something like this:
public void main(string args[])
{
//Get the number you want to use as input
long x = number;//'number' can be hard coded or retrieved from ReadLine() or from the given arguments
IList<long> primes = FindSmallerPrimes(number);
DisplayPrimes(primes);
}
public IList<long> FindSmallerPrimes(long largestNumber)
{
List<long> returnList = new List<long>();
//Find the primes, using a method as described by another answer, add them to returnList
return returnList;
}
public void DisplayPrimes(IList<long> primes)
{
foreach(long l in primes)
{
Console.WriteLine ( "Prime:" + l.ToString() );
}
}
Even if you end up working somewhere where speration like this isn't needed, it's good to know how to do it.
Here's how I got it to work:
copy c:\MinGW\bin\mingw32-make.exe c:\MinGW\bin\make.exe
Then I am able to open a command prompt and type make:
C:\Users\Dell>make
make: *** No targets specified and no makefile found. Stop.
Which means it's working now!
As per the docs:
You can set annotation processor argument (room.schemaLocation) to tell Room to export the schema into a folder. Even though it is not mandatory, it is a good practice to have version history in your codebase and you should commit that file into your version control system (but don't ship it with your app!).
So if you don't need to check the schema and you want to get rid of the warning, just add exportSchema = false
to your RoomDatabase
, as follows.
@Database(entities = { YourEntity.class }, version = 1, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
//...
}
If you follow @mikejonesguy answer below, you will follow the good practice mentioned in the docs :).
Basically you will get a .json
file in your ../app/schemas/
folder.
And it looks something like this:
{
"formatVersion": 1,
"database": {
"version": 1,
"identityHash": "53db508c5248423325bd5393a1c88c03",
"entities": [
{
"tableName": "sms_table",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `message` TEXT, `date` INTEGER, `client_id` INTEGER)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER"
},
{
"fieldPath": "message",
"columnName": "message",
"affinity": "TEXT"
},
{
"fieldPath": "date",
"columnName": "date",
"affinity": "INTEGER"
},
{
"fieldPath": "clientId",
"columnName": "client_id",
"affinity": "INTEGER"
}
],
"primaryKey": {
"columnNames": [
"id"
],
"autoGenerate": true
},
"indices": [],
"foreignKeys": []
}
],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"53db508c5248423325bd5393a1c88c03\")"
]
}
}
If my understanding is correct, you will get such a file with every database version update, so that you can easily follow the history of your db.
Sometime even after setting all it may not work. I have tried all the methods like
Nothing worked. Then I did the following which worked instantly.
Goto eclipse Run --> run configurations. Under Android Applications you can see you application. Now, on the right hand side click on the Target tab. Under the 'Additional Emulator Command line options' add the following.
-dns-server <DNS servers from your local machine upto three> -http-proxy http://<your proxy>:<your proxy port>
The catch here is that the DNS Server setting should be from your local system. Goto cmd prompt and run ipconfig to check your DNS servers. Same with the proxy server and port. Whatever works for your browser should be put in here.
Try eUML2. its a single click generator no need to drag n drop.
You have to set you distribution type. In your code, juste add:
self.stack1.distribution = UIStackViewDistributionFillEqually;
Or you can set the distribution directly in your interface builder. For example:
Hope that helps ;) Lapinou.
For me the nicest way of displaying it (the footer) is sticking to the bottom but not covering content all the time:
#my_footer {
position: static
fixed; bottom: 0
}
For me this worked after I downloaded AJAX Unobtrusive library via NuGet :
Search and install via NuGet Packages: Microsoft.jQuery.Unobtrusive.Ajax
Than add in the view the references to jquery and AJAX Unobtrusive:
@Scripts.Render("~/bundles/jquery")
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"> </script>
For others that find themselves here, the css I was looking for was
overflow-wrap: break-word;
Which will only break a word if it needs to (the length of the single word is greater than the width of the p), unlike word-break: break-all
which can break the last word of every line.
Try it:
if (Objects.equals(gender, "Male")) {
salutation ="Mr.";
} else if (Objects.equals(gender, "Female")) {
salutation ="Ms.";
}
for ORA-01031: insufficient privileges. Some of the more common causes are:
UPDATE
to a table, but you only have SELECT
access to the table.CONNECT INTERNAL
.The option(s) to resolve this Oracle error are:
For ORA-00942: table or view does not exist.
You tried to execute a SQL statement that references a table or view that either does not exist, that you do not have access to, or that belongs to another schema and you didn't reference the table by the schema name.
If this error occurred because the table or view does not exist, you will need to create the table or view.
You can check to see if the table exists in Oracle by executing the following SQL statement:
select *
from all_objects
where object_type in ('TABLE','VIEW')
and object_name = 'OBJECT_NAME';
For example, if you are looking for a suppliers table, you would execute:
select *
from all_objects
where object_type in ('TABLE','VIEW')
and object_name = 'SUPPLIERS';
OPTION #2
If this error occurred because you do not have access to the table or view, you will need to have the owner of the table/view, or a DBA grant you the appropriate privileges to this object.
OPTION #3
If this error occurred because the table/view belongs to another schema and you didn't reference the table by the schema name, you will need to rewrite your SQL to include the schema name.
For example, you may have executed the following SQL statement:
select *
from suppliers;
But the suppliers
table is not owned by you, but rather, it is owned by a schema called app, you could fix your SQL as follows:
select *
from app.suppliers;
If you do not know what schema the suppliers table/view belongs to, you can execute the following SQL to find out:
select owner
from all_objects
where object_type in ('TABLE','VIEW')
and object_name = 'SUPPLIERS';
This will return the schema name who owns the suppliers table.
I don't know the reasoning behind this, but I set my parent container to display:flex
and the child containers to display:inline-block
and they stayed inline despite the combined width of the children exceeding the parent.
Didn't need to toy with max-width
, max-height
, white-space
, or anything else.
Hope that helps someone.
If you don't know what backend is , you can read this: https://matplotlib.org/tutorials/introductory/usage.html#backends
Some people use matplotlib interactively from the python shell and have plotting windows pop up when they type commands. Some people run Jupyter notebooks and draw inline plots for quick data analysis. Others embed matplotlib into graphical user interfaces like wxpython or pygtk to build rich applications. Some people use matplotlib in batch scripts to generate postscript images from numerical simulations, and still others run web application servers to dynamically serve up graphs. To support all of these use cases, matplotlib can target different outputs, and each of these capabilities is called a backend; the "frontend" is the user facing code, i.e., the plotting code, whereas the "backend" does all the hard work behind-the-scenes to make the figure.
So when you type %matplotlib inline , it activates the inline backend. As discussed in the previous posts :
With this backend, the output of plotting commands is displayed inline within frontends like the Jupyter notebook, directly below the code cell that produced it. The resulting plots will then also be stored in the notebook document.
#!/usr/bin/python
file=open("D:\\zzzz\\names2.txt","r+")
wordcount={}
for word in file.read().split():
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
for k,v in wordcount.items():
print k, v
To call the camera you can use:
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivity(intent);
The image will be automatically saved in a default directory.
And you need to set the permission for the camera in your AndroidManifest.xml:
<uses-permission android:name="android.permission.CAMERA"> </uses-permission>
There is a problem with all those solutions floating around using multipliers. Both kkyy and Christoph's solutions are wrong unfortunately.
Please test your code for number 551.175 with 2 decimal places - it will round to 551.17 while it should be 551.18 ! But if you test for ex. 451.175 it will be ok - 451.18. So it's difficult to spot this error at a first glance.
The problem is with multiplying: try 551.175 * 100 = 55117.49999999999 (ups!)
So my idea is to treat it with toFixed() before using Math.round();
function roundFix(number, precision)
{
var multi = Math.pow(10, precision);
return Math.round( (number * multi).toFixed(precision + 1) ) / multi;
}
In my case, I had created a new test target and deleted the default swift file so it was left with just the info.plist
. Adding a new file fixed this.
the delete query only allows for modifiers after the DELETE 'command' to tell the database what/how do handle things.
see this page
Express version:
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1"
}
Optional parameter are very much handy, you can declare and use them easily using express:
app.get('/api/v1/tours/:cId/:pId/:batchNo?', (req, res)=>{
console.log("category Id: "+req.params.cId);
console.log("product ID: "+req.params.pId);
if (req.params.batchNo){
console.log("Batch No: "+req.params.batchNo);
}
});
In the above code batchNo is optional. Express will count it optional because after in URL construction, I gave a '?' symbol after batchNo '/:batchNo?'
Now I can call with only categoryId and productId or with all three-parameter.
http://127.0.0.1:3000/api/v1/tours/5/10
//or
http://127.0.0.1:3000/api/v1/tours/5/10/8987
If you are using Java 7+, you may want to use NIO.2, e.g.:
❍ Code:
public static void main(String[] args) throws Exception {
File file = new File("test.csv");
List<String> lines = Files.readAllLines(file.toPath(),
StandardCharsets.UTF_8);
for (String line : lines) {
String[] array = line.split(",", -1);
System.out.println(array[0]);
}
}
❍ Output:
a
1RW
1RW
1RW
1RW
1RW
1RW
1R1W
1R1W
1R1W
Unfortunately, there is no way to do this easily. Every solution has its drawbacks.
Use atof()
or strtof()
directly: this is what most people will tell you to do and it will work most of the time. However, if the program sets a locale or it uses a library that sets the locale (for instance, a graphics library that displays localised menus) and the user has their locale set to a language where the decimal separator is not .
(such as fr_FR
where the separator is ,
) these functions will stop parsing at the .
and you will stil get 4.0
.
Use atof()
or strtof()
but change the locale; it's a matter of calling setlocale(LC_ALL|~LC_NUMERIC, "");
before any call to atof()
or the likes. The problem with setlocale
is that it will be global to the process and you might interfer with the rest of the program. Note that you might query the current locale with setlocale()
and restore it after you're done.
Write your own float parsing routine. This might be quite quick if you do not need advanced features such as exponent parsing or hexadecimal floats.
Also, note that the value 4.08
cannot be represented exactly as a float; the actual value you will get is 4.0799999237060546875
.
@RobSadler:
RE Martin Wickman's CSS only version...
You can get around that problem by putting accordion-caret on the anchor tag and giving it a collapsed class by default. Like so:
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle accordion-caret collapsed" data-toggle="collapse" href="#collapseOne">
<strong>Header</strong>
</a>
</div>
<div id="collapseOne" class="accordion-body collapse in">
<div class="accordion-inner">
Content
</div>
</div>
That worked for me.
myclass.h
#ifndef __MYCLASS_H__
#define __MYCLASS_H__
class MyClass
{
public:
MyClass();
/* use virtual otherwise linker will try to perform static linkage */
virtual void DoSomething();
private:
int x;
};
#endif
myclass.cc
#include "myclass.h"
#include <iostream>
using namespace std;
extern "C" MyClass* create_object()
{
return new MyClass;
}
extern "C" void destroy_object( MyClass* object )
{
delete object;
}
MyClass::MyClass()
{
x = 20;
}
void MyClass::DoSomething()
{
cout<<x<<endl;
}
class_user.cc
#include <dlfcn.h>
#include <iostream>
#include "myclass.h"
using namespace std;
int main(int argc, char **argv)
{
/* on Linux, use "./myclass.so" */
void* handle = dlopen("myclass.so", RTLD_LAZY);
MyClass* (*create)();
void (*destroy)(MyClass*);
create = (MyClass* (*)())dlsym(handle, "create_object");
destroy = (void (*)(MyClass*))dlsym(handle, "destroy_object");
MyClass* myClass = (MyClass*)create();
myClass->DoSomething();
destroy( myClass );
}
On Mac OS X, compile with:
g++ -dynamiclib -flat_namespace myclass.cc -o myclass.so
g++ class_user.cc -o class_user
On Linux, compile with:
g++ -fPIC -shared myclass.cc -o myclass.so
g++ class_user.cc -ldl -o class_user
If this were for a plugin system, you would use MyClass as a base class and define all the required functions virtual. The plugin author would then derive from MyClass, override the virtuals and implement create_object
and destroy_object
. Your main application would not need to be changed in any way.
For windows open git bash and try
NODE_ENV=production node app.js
There are several ways to try to prevent line breaks, and the phrase “a newer construct” might refer to more than one way—that’s actually the most reasonable interpretation. They probably mostly think of the CSS declaration white-space:nowrap
and possibly the no-break space character. The different ways are not equivalent, far from that, both in theory and especially in practice, though in some given case, different ways might produce the same result.
There is probably nothing real to be gained by switching from the HTML attribute to the somewhat clumsier CSS way, and you would surely lose when style sheets are disabled. But even the nowrap
attribute does no work in all situations. In general, what works most widely is the nobr
markup, which has never made its way to any specifications but is alive and kicking: <td><nobr>...</nobr></td>
.
You can simply download the library which you want to include and copy it to libs folder of your project. Then select that file (in my case it was android-support-v4 library) right click on it and select "Add as Library"
to implement this in algorithmic way, by not using any python inbuilt function . This can be implemented as
def find_pos(string,word):
for i in range(len(string) - len(word)+1):
if string[i:i+len(word)] == word:
return i
return 'Not Found'
string = "the dude is a cool dude"
word = 'dude1'
print(find_pos(string,word))
# output 4
You might try changing this line in your persistence.xml from
<property name="hbm2ddl.auto" value="create"/>
to:
<property name="hibernate.hbm2ddl.auto" value="update"/>
This is supposed to maintain the schema to follow any changes you make to the Model each time you run the app.
Got this from JavaRanch
Sure Google has a limit of downloads so that you don't abuse the system. These are the limits if you are using Gmail:
The following limits apply for Google Apps for Business or Education editions. Limits for domains during trial are lower. These limits may change without notice in order to protect Google’s infrastructure.
Bandwidth limits
Limit Per hour Per day
Download via web client 750 MB 1250 MB
Upload via web client 300 MB 500 MB
POP and IMAP bandwidth limits
Limit Per day
Download via IMAP 2500 MB
Download via POP 1250 MB
Upload via IMAP 500 MB
swift 2 version of the @MS AppTech answer
func handlePan(panGest : UIPanGestureRecognizer) {
let velocity : CGPoint = panGest.velocityInView(self.view);
let magnitude : CGFloat = CGFloat(sqrtf((Float(velocity.x) * Float(velocity.x)) + (Float(velocity.y) * Float(velocity.y))));
let slideMult :CGFloat = magnitude / 200;
//NSLog(@"magnitude: %f, slideMult: %f", magnitude, slideMult);
let slideFactor : CGFloat = 0.1 * slideMult; // Increase for more of a slide
var finalPoint : CGPoint = CGPointMake(panGest.view!.center.x + (velocity.x * slideFactor),
panGest.view!.center.y + (velocity.y * slideFactor));
finalPoint.x = min(max(finalPoint.x, 0), self.view.bounds.size.width);
finalPoint.y = min(max(finalPoint.y, 0), self.view.bounds.size.height);
UIView.animateWithDuration(Double(slideFactor*2), delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
panGest.view!.center = finalPoint;
}, completion: nil)
}
It's worth to mention that CLOB / BLOB data types and their sizes are supported by MySQL 5.0+, so you can choose the proper data type for your need.
http://dev.mysql.com/doc/refman/5.7/en/storage-requirements.html
Data Type Date Type Storage Required
(CLOB) (BLOB)
TINYTEXT TINYBLOB L + 1 bytes, where L < 2**8 (255)
TEXT BLOB L + 2 bytes, where L < 2**16 (64 K)
MEDIUMTEXT MEDIUMBLOB L + 3 bytes, where L < 2**24 (16 MB)
LONGTEXT LONGBLOB L + 4 bytes, where L < 2**32 (4 GB)
where L stands for the byte length of a string
Try this one-
<VirtualHost *:80>
ProxyPreserveHost On
ProxyRequests Off
ServerName www.adminbackend.example.com
ServerAlias adminbackend.example.com
ProxyPass / http://localhost:6000/
ProxyPassReverse / http://localhost:6000/
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
You can change the actual width/height attributes like this:
var theImg = document.getElementById('theImgId');
theImg.height = 150;
theImg.width = 150;
For tab separated values the code below can be used
sort -t$'\t' -k2 -n
-r can be used for getting data in descending order.
-n for numerical sort
-k, --key=POS1[,POS2] where k is column in file
For descending order below is the code
sort -t$'\t' -k2 -rn
viewport
meta tag on mobile browser,
The initial-scale property controls the zoom level when the page is first loaded. The maximum-scale, minimum-scale, and user-scalable properties control how users are allowed to zoom the page in or out.
I had the same problem, getting the message "ImportError: No module named numpy".
I'm also using anaconda and found out that I needed to add numpy to the ENV I was using. You can check the packages you have in your environment with the command:
conda list
So, when I used that command, numpy was not displayed. If that is your case, you just have to add it, with the command:
conda install numpy
After I did that, the error with the import numpy
was gone
The widely-used PCRE library can handle such situations (you won't achieve the the same with POSIX-compliant regex engines, though):
(\b\w+\b)\W+\1
Use update instead of stop
http://api.jqueryui.com/sortable/
update( event, ui )
Type: sortupdate
This event is triggered when the user stopped sorting and the DOM position has changed.
.
stop( event, ui )
Type: sortstop
This event is triggered when sorting has stopped. event Type: Event
Piece of code:
<script type="text/javascript">
var sortable = new Object();
sortable.s1 = new Array(1, 2, 3, 4, 5);
sortable.s2 = new Array(1, 2, 3, 4, 5);
sortable.s3 = new Array(1, 2, 3, 4, 5);
sortable.s4 = new Array(1, 2, 3, 4, 5);
sortable.s5 = new Array(1, 2, 3, 4, 5);
sortingExample();
function sortingExample()
{
// Init vars
var tDiv = $('<div></div>');
var tSel = '';
// ul
for (var tName in sortable)
{
// Creating ul list
tDiv.append(createUl(sortable[tName], tName));
// Add selector id
tSel += '#' + tName + ',';
}
$('body').append('<div id="divArrayInfo"></div>');
$('body').append(tDiv);
// ul sortable params
$(tSel).sortable({connectWith:tSel,
start: function(event, ui)
{
ui.item.startPos = ui.item.index();
},
update: function(event, ui)
{
var a = ui.item.startPos;
var b = ui.item.index();
var id = this.id;
// If element moved to another Ul then 'update' will be called twice
// 1st from sender list
// 2nd from receiver list
// Skip call from sender. Just check is element removed or not
if($('#' + id + ' li').length < sortable[id].length)
{
return;
}
if(ui.sender === null)
{
sortArray(a, b, this.id, this.id);
}
else
{
sortArray(a, b, $(ui.sender).attr('id'), this.id);
}
printArrayInfo();
}
}).disableSelection();;
// Add styles
$('<style>')
.attr('type', 'text/css')
.html(' body {background:black; color:white; padding:50px;} .sortableClass { clear:both; display: block; overflow: hidden; list-style-type: none; } .sortableClass li { border: 1px solid grey; float:left; clear:none; padding:20px; }')
.appendTo('head');
printArrayInfo();
}
function printArrayInfo()
{
var tStr = '';
for ( tName in sortable)
{
tStr += tName + ': ';
for(var i=0; i < sortable[tName].length; i++)
{
// console.log(sortable[tName][i]);
tStr += sortable[tName][i] + ', ';
}
tStr += '<br>';
}
$('#divArrayInfo').html(tStr);
}
function createUl(tArray, tId)
{
var tUl = $('<ul>', {id:tId, class:'sortableClass'})
for(var i=0; i < tArray.length; i++)
{
// Create Li element
var tLi = $('<li>' + tArray[i] + '</li>');
tUl.append(tLi);
}
return tUl;
}
function sortArray(a, b, idA, idB)
{
var c;
c = sortable[idA].splice(a, 1);
sortable[idB].splice(b, 0, c);
}
</script>
Here a solution inside an exercise:
function high($sentence)
{
$alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'ñ', 'o', 'p', 'q', 'r', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
$alphabet = array_flip($alphabet);
$words = explode(" ", $sentence);
foreach ($words as $word) {
$letters = str_split($word);
$points = 0;
foreach ($letters as $letter)
$points += $alphabet[$letter];
$score[$word] = $points;
}
$value = max($score);
$key = array_search($value, $score);
return $key;
}
echo high("what time are we climbing up the volcano");
Just add ExecJS and the Ruby Racer in your gem file and run bundle install
after.
gem 'execjs'
gem 'therubyracer'
Everything should be fine after.
File name should match the layout id which in this example is : items_list_item.xml in the layout folder of your application
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<ImageView android:id="@+id/R.id.list_item_image"
android:layout_width="100dip"
android:layout_height="wrap_content" />
</LinearLayout>
To check kafka version :
cd /usr/hdp/current/kafka-broker/libs
ls kafka_*.jar
return
returns a value. It doesn't matter what name you gave to that value. Returning it just "passes it out" so that something else can use it. If you want to use it, you have to grab it from outside:
lst = defineAList()
useTheList(lst)
Returning list
from inside defineAList
doesn't mean "make it so the whole rest of the program can use that variable". It means "pass this variable out and give the rest of the program one chance to grab it and use it". You need to assign that value to something outside the function in order to make use of it. Also, because of this, there is no need to define your list ahead of time with list = []
. Inside defineAList
, you create a new list and return it; this list has no relationship to the one you defined with list = []
at the beginning.
Incidentally, I changed your variable name from list
to lst
. It's not a good idea to use list
as a variable name because that is already the name of a built-in Python type. If you make your own variable called list
, you won't be able to access the builtin one anymore.
Consider using Django's built-in deserializers. Django's docs are well-written and can help you get started. Consider converting your data from csv to XML or JSON and using a deserializer to import the data. If you're doing this from the command line (rather than through a web request), the loaddata
manage.py command will be especially helpful.
Actually, the erase
function works for two profiles:
Removing a single element
iterator erase (iterator position);
Removing a range of elements
iterator erase (iterator first, iterator last);
Since std::vec.begin() marks the start of container and if we want to delete the ith element in our vector, we can use:
vec.erase(vec.begin() + index);
If you look closely, vec.begin() is just a pointer to the starting position of our vector and adding the value of i to it increments the pointer to i position, so instead we can access the pointer to the ith element by:
&vec[i]
So we can write:
vec.erase(&vec[i]); // To delete the ith element
Since Java 13 you have formatted
1 method on String, which was added along with text blocks as a preview feature 2.
You can use it instead of String.format()
Assertions.assertEquals(
"%s %d %.3f".formatted("foo", 123, 7.89),
"foo 123 7.890"
);
Have a look at the ImageView API. There are several setImage*
methods. Which one to use depends on the image you provide. If you have the image as resource (e.g. file res/drawable/my_image.png)
ImageView img = new ImageView(this); // or (ImageView) findViewById(R.id.myImageView);
img.setImageResource(R.drawable.my_image);
In my case the problem occurred due to closing my PC while visual studio were remain open, so in result csproj.user file saved empty. Thankfully i have already backup, so i just copied all xml from csproj.user and paste in my affected project csproj.user file ,so it worked perfectly.
This file just contain building device info and some more.
It is simple: if recv()
returns 0 bytes; you will not receive any more data on this connection. Ever. You still might be able to send.
It means that your non-blocking socket have to raise an exception (it might be system-dependent) if no data is available but the connection is still alive (the other end may send).
You can create a folder with os.makedirs()
and use os.path.exists() to see if it already exists:
newpath = r'C:\Program Files\arbitrary'
if not os.path.exists(newpath):
os.makedirs(newpath)
If you're trying to make an installer: Windows Installer does a lot of work for you.
If you are using Python 3.6+
you can make use of the new so called f-strings
which stands for formatted strings and it can be used by adding the character f
at the beginning of a string to identify this as an f-string.
price = 123
name = "Jerry"
print(f"{name}!!, {price} is much, isn't {price} a lot? {name}!")
>Jerry!!, 123 is much, isn't 123 a lot? Jerry!
The main benefits of using f-strings is that they are more readable, can be faster, and offer better performance:
Source Pandas for Everyone: Python Data Analysis, By Daniel Y. Chen
No doubt that the new f-strings
are more readable, as you don't have to remap the strings, but is it faster though as stated in the aformentioned quote?
price = 123
name = "Jerry"
def new():
x = f"{name}!!, {price} is much, isn't {price} a lot? {name}!"
def old():
x = "{1}!!, {0} is much, isn't {0} a lot? {1}!".format(price, name)
import timeit
print(timeit.timeit('new()', setup='from __main__ import new', number=10**7))
print(timeit.timeit('old()', setup='from __main__ import old', number=10**7))
> 3.8741058271543776 #new
> 5.861819514350163 #old
Running 10 Million test's it seems that the new f-strings
are actually faster in mapping.
The only solution here that worked for me in 5.6.5 was bigstone1998's regex answer. I'd prefer not to use a regex search though for performance reasons. I believe the reason the other solutions don't work is because a standard field will be analyzed and as a result have no empty string token to negate against. The exists query won't help on it's own either since an empty string is considered non-null.
If you can't change the index the regex approach may be your only option, but if you can change the index then adding a keyword subfield will solve the problem.
In the mappings for the index:
"myfield": {
"type": "text",
"fields": {
"keyword": {
"ignore_above": 256,
"type": "keyword"
}
}
}
Then you can simply use the query:
{
"query": {
"bool": {
"must": {
"exists": {
"field": "myfield"
}
},
"must_not": {
"term": {
"myfield.keyword": ""
}
}
}
}
}
Note the .keyword
in the must_not component.
Within your app theme you can set the android:itemBackground property to change the color of the action menu.
For example:
<style name="AppThemeDark" parent="Theme.AppCompat.Light.DarkActionBar">_x000D_
<item name="colorPrimary">@color/drk_colorPrimary</item>_x000D_
<item name="colorPrimaryDark">@color/drk_colorPrimaryDark</item>_x000D_
<item name="colorAccent">@color/drk_colorAccent</item>_x000D_
<item name="actionBarStyle">@style/NoTitle</item>_x000D_
<item name="windowNoTitle">true</item>_x000D_
<item name="android:textColor">@color/white</item>_x000D_
_x000D_
<!-- THIS IS WHERE YOU CHANGE THE COLOR -->_x000D_
<item name="android:itemBackground">@color/drk_colorPrimary</item>_x000D_
</style>
_x000D_
I've found that you can move div elements to the next line simply by setting the property
Display: block;
On each div.
MongoDB gives freedom to be schema-less and this feature can result in pain in the long term if not thought or planned well,
There are 2 options either Embed or Reference. I will not go through definitions as the above answers have well defined them.
When embedding you should answer one question is your embedded document going to grow, if yes then how much (remember there is a limit of 16 MB per document) So if you have something like a comment on a post, what is the limit of comment count, if that post goes viral and people start adding comments. In such cases, reference could be a better option (but even reference can grow and reach 16 MB limit).
So how to balance it, the answer is a combination of different patterns, check these links, and create your own mix and match based on your use case.
https://www.mongodb.com/blog/post/building-with-patterns-a-summary
https://www.mongodb.com/blog/post/6-rules-of-thumb-for-mongodb-schema-design-part-1
You can do this way :
TimeSpan duration = new TimeSpan(tickCount)
double minutes = duration.TotalMinutes;
jqxhr is a json object:
complete returns:
The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror").
see: jQuery ajax
so you would do:
jqxhr.status
to get the status
Keep it simple! Original Google maps variable, none of the extra stuff.
var mapOptions = {
zoom: 16,
center: myLatlng,
scrollwheel: false
}
I faced the same issue when,
I had created new angular project using old angular-cli version (1.4.7) I then updated angular-cli using below commands (DO NOT DO THE BELOW TO UPDATE CLI)
npm uninstall -g @angular/cli
npm cache clean --force
npm install -g @angular/cli@latest
Now when I tried ng serve
, i was getting same error like you
Angular Cli Error: The serve command requires to be run in an Angular project, but a project definition could not be found
DO BELOW TO UPDATE CLI
ng update @angular/cli --migrate-only --from=1.4.7
I got solution after working whole day on it. It is little hacky solution Added span inside td tag
<td><span><%= item.StartICDate %></span></td>.
Date format which Im using is dd/MM/YYYY. Tested in Datatables1.9.0
If you have phpmyadmin configuration storage setup, the settings will be pulled out of your phpmyadmin.pma__userconfig table, and will override anything you have in config.inc.php. In this table, each MYSQL user can be assigned a different set of phpmyadmin settings.
Arrays.sort(yourarray, new Comparator() {
public int compare(Object o1, Object o2) {
String[] elt1 = (String[])o1;
String[] elt2 = (String[])o2;
return elt1[0].compareTo(elt2[0]);
}
});
It's easier with the enumitem package:
\documentclass{article}
\usepackage{enumitem}
\begin{document}
Less space:
\begin{itemize}[noitemsep]
\item foo
\item bar
\item baz
\end{itemize}
Even more compact:
\begin{itemize}[noitemsep,nolistsep]
\item foo
\item bar
\item baz
\end{itemize}
\end{document}
The enumitem package provides a lot of features to customize bullets, numbering and lengths.
The paralist package provides very compact lists: compactitem, compactenum and even lists within paragraphs like inparaenum and inparaitem.
For generate unique id's:
const uid = () =>
String(
Date.now().toString(32) +
Math.random().toString(32) +
Math.random().toString(32)
).replace(/\./g, '')
For check that is works:
var size = 500000
var arr = new Array(size)
.fill(0)
.map(() => uid())
var b = new Set(arr)
console.log(
size === b.size ? 'all ids are unique' : `not unique records ${size - b.size}`
)
Just a heads up... with Python 2.7, and I believe ever since super()
was introduced in version 2.2, you can only call super()
if one of the parents inherit from a class that eventually inherits object
(new-style classes).
Personally, as for python 2.7 code, I'm going to continue using BaseClassName.__init__(self, args)
until I actually get the advantage of using super()
.
Code c#
using System.Diagnostics;
using System.Management;
public void KillProcessAndChildren(string p_name)
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher
("Select * From Win32_Process Where Name = '"+ p_name +"'");
ManagementObjectCollection moc = searcher.Get();
foreach (ManagementObject mo in moc)
{
try
{
KillProcessAndChildren(Convert.ToInt32(mo["ProcessID"]));
}
catch (ArgumentException)
{
break;
}
}
}
and this function
public void KillProcessAndChildren(int pid)
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher
("Select * From Win32_Process Where ParentProcessID=" + pid);
ManagementObjectCollection moc = searcher.Get();
foreach (ManagementObject mo in moc)
{
try
{
KillProcessAndChildren(Convert.ToInt32(mo["ProcessID"]));
}
catch
{
break;
}
}
try
{
Process proc = Process.GetProcessById(pid);
proc.Kill();
}
catch (ArgumentException)
{
// Process already exited.
}
}
Calling
try
{
KillProcessAndChildren("chromedriver.exe");
}
catch
{
}
You could do it with JavaScript with something like this:
<input onblur="checkLength(this)" id="groupidtext" type="text" style="width: 100px;" maxlength="6" />
<!-- Or use event onkeyup instead if you want to check every character strike -->
function checkLength(el) {
if (el.value.length != 6) {
alert("length must be exactly 6 characters")
}
}
Note this would work in older browsers which don't support HTML 5, but it relies on the user having JavaScript switched on.
remove the http
or https
from wget https:github.com/facebook/facebook-php-sdk/archive/master.zip
. this worked fine for me.
Use the following setting and you will be all set. Go to Window --> Preference --> General --> Network Connection --> select Direct from drop down
In Angular Http 7, the DELETE method accepts as a second parameter options
object in which you provide the request parameters as params
object along with the headers
object. This is different than Angular6.
See example:
this.httpClient.delete('https://api-url', {
headers: {},
params: {
'param1': paramValue1,
'param2': paramValue2
}
});
Form data (for GET or POST) is usually encoded as application/x-www-form-urlencoded
: this specifies +
for spaces.
URLs are encoded as RFC 1738 which specifies %20
.
In theory I think you should have %20 before the ?
and + after:
example.com/foo%20bar?foo+bar
Go to SQL command line:- type:
sql>connect / as sysdba;
then type:
sql>desc dba_users;
then type:
sql>select username,password from dba_users;
If sysdba
doesn't work then try connecting with username:scott and password: Tiger
You will be able to see all users with passwords. Probably you might find your's. Hope this helps
We will look at how the contents of this array are constructed and can be manipulated to affect where the Perl interpreter will find the module files.
Default @INC
Perl interpreter is compiled with a specific @INC
default value. To find out this value, run env -i perl -V
command (env -i
ignores the PERL5LIB
environmental variable - see #2) and in the output you will see something like this:
$ env -i perl -V ... @INC: /usr/lib/perl5/site_perl/5.18.0/x86_64-linux-thread-multi-ld /usr/lib/perl5/site_perl/5.18.0 /usr/lib/perl5/5.18.0/x86_64-linux-thread-multi-ld /usr/lib/perl5/5.18.0 .
Note .
at the end; this is the current directory (which is not necessarily the same as the script's directory). It is missing in Perl 5.26+, and when Perl runs with -T
(taint checks enabled).
To change the default path when configuring Perl binary compilation, set the configuration option otherlibdirs
:
Configure -Dotherlibdirs=/usr/lib/perl5/site_perl/5.16.3
Environmental variable PERL5LIB
(or PERLLIB
)
Perl pre-pends @INC
with a list of directories (colon-separated) contained in PERL5LIB
(if it is not defined, PERLLIB
is used) environment variable of your shell. To see the contents of @INC
after PERL5LIB
and PERLLIB
environment variables have taken effect, run perl -V
.
$ perl -V ... %ENV: PERL5LIB="/home/myuser/test" @INC: /home/myuser/test /usr/lib/perl5/site_perl/5.18.0/x86_64-linux-thread-multi-ld /usr/lib/perl5/site_perl/5.18.0 /usr/lib/perl5/5.18.0/x86_64-linux-thread-multi-ld /usr/lib/perl5/5.18.0 .
-I
command-line option
Perl pre-pends @INC
with a list of directories (colon-separated) passed as value of the -I
command-line option. This can be done in three ways, as usual with Perl options:
Pass it on command line:
perl -I /my/moduledir your_script.pl
Pass it via the first line (shebang) of your Perl script:
#!/usr/local/bin/perl -w -I /my/moduledir
Pass it as part of PERL5OPT
(or PERLOPT
) environment variable (see chapter 19.02 in Programming Perl)
Pass it via the lib
pragma
Perl pre-pends @INC
with a list of directories passed in to it via use lib
.
In a program:
use lib ("/dir1", "/dir2");
On the command line:
perl -Mlib=/dir1,/dir2
You can also remove the directories from @INC
via no lib
.
You can directly manipulate @INC
as a regular Perl array.
Note: Since @INC
is used during the compilation phase, this must be done inside of a BEGIN {}
block, which precedes the use MyModule
statement.
Add directories to the beginning via unshift @INC, $dir
.
Add directories to the end via push @INC, $dir
.
Do anything else you can do with a Perl array.
Note: The directories are unshifted onto @INC
in the order listed in this answer, e.g. default @INC
is last in the list, preceded by PERL5LIB
, preceded by -I
, preceded by use lib
and direct @INC
manipulation, the latter two mixed in whichever order they are in Perl code.
@INC
?There does not seem to be a comprehensive @INC
FAQ-type post on Stack Overflow, so this question is intended as one.
If the modules in a directory need to be used by many/all scripts on your site, especially run by multiple users, that directory should be included in the default @INC
compiled into the Perl binary.
If the modules in the directory will be used exclusively by a specific user for all the scripts that user runs (or if recompiling Perl is not an option to change default @INC
in previous use case), set the users' PERL5LIB
, usually during user login.
Note: Please be aware of the usual Unix environment variable pitfalls - e.g. in certain cases running the scripts as a particular user does not guarantee running them with that user's environment set up, e.g. via su
.
If the modules in the directory need to be used only in specific circumstances (e.g. when the script(s) is executed in development/debug mode, you can either set PERL5LIB
manually, or pass the -I
option to perl.
If the modules need to be used only for specific scripts, by all users using them, use use lib
/no lib
pragmas in the program itself. It also should be used when the directory to be searched needs to be dynamically determined during runtime - e.g. from the script's command line parameters or script's path (see the FindBin module for very nice use case).
If the directories in @INC
need to be manipulated according to some complicated logic, either impossible to too unwieldy to implement by combination of use lib
/no lib
pragmas, then use direct @INC
manipulation inside BEGIN {}
block or inside a special purpose library designated for @INC
manipulation, which must be used by your script(s) before any other modules are used.
An example of this is automatically switching between libraries in prod/uat/dev directories, with waterfall library pickup in prod if it's missing from dev and/or UAT (the last condition makes the standard "use lib + FindBin" solution fairly complicated. A detailed illustration of this scenario is in How do I use beta Perl modules from beta Perl scripts?.
An additional use case for directly manipulating @INC
is to be able to add subroutine references or object references (yes, Virginia, @INC
can contain custom Perl code and not just directory names, as explained in When is a subroutine reference in @INC called?).
As all the above answers have suggested it will throw a NullPointerException.
Please initialise it with some value(s) and then you can use the length property correctly. For example:
String[] str = { "plastic", "paper", "use", "throw" };
System.out.println("Length is:::" + str.length);
The array 'str' is now defined, and so it's length also has a defined value.
As suggested by djjeck
in comment in this answer I missed to put public
modifier for my class.
It should be
public class MyActivity extends AppCompatActivity {
It may help some like me.
List<Integer>[] array;
array = new List<Integer>[10];
this the second case in @TofuBeer's answer is incorrect. because can't create arrays with generics. u can use:
List<List<Integer>> array = new ArrayList<>();
This is what LINQ needs
public static IEnumerable<T> Except<T, TKey>(this IEnumerable<T> items, IEnumerable<T> other, Func<T, TKey> getKey)
{
return from item in items
join otherItem in other on getKey(item)
equals getKey(otherItem) into tempItems
from temp in tempItems.DefaultIfEmpty()
where ReferenceEquals(null, temp) || temp.Equals(default(T))
select item;
}
You can write the accepted answer as a one-liner using date.replace
:
datem = datetime.today().replace(day=1)
Maybe, because you are under IIS,
$_SERVER['PATH_INFO']
is what you want, based on the URLs you used to explain.
For Apache, you'd use $_SERVER['REQUEST_URI']
.
Another way ( longer ) In VB.net [ Say 2300 Start and 0700 Finish next day ]
If tsStart > tsFinish Then
' Take Hours difference and adjust accordingly
tsDifference = New TimeSpan((24 - tsStart.Hours) + tsFinish.Hours, 0, 0)
' Add Minutes to Difference
tsDifference = tsDifference.Add(New TimeSpan(0, Math.Abs(tsStart.Minutes - tsFinish.Minutes), 0))
' Add Seonds to Difference
tsDifference = tsDifference.Add(New TimeSpan(0, 0, Math.Abs(tsStart.Seconds - tsFinish.Seconds)))
this is how I implemented the same in c++.
#include <iostream>
#include <cstring>
using namespace std;
int leng;
char ch;
string str, cpy;
int main() {
cout << "Enter a string: ";
getline(cin, str);
leng = str.length();
cout << endl << "Enter the character to delete: ";
cin >> ch;
for (int i=0; i<leng; i++) {
if (str[i] != ch)
cpy += str[i];
}
cout << endl << "String after removal: " << cpy;
return 0;
}
Alternatively, as long as permissions are not given, the good old <noscript>
tags works. You can cover the page in css and tell them what's wrong, ... without using javascript ofcourse.
You could leverage the html-to-react
npm module.
Note: I'm the author of the module and just published it a few hours ago. Please feel free to report any bugs or usability issues.
In your code add this line
requestWindowFeature(Window.FEATURE_NO_TITLE);
Or in XML use a theme
android:theme="@android:style/Theme.NoTitleBar"
XML would be a better implementation as with the code version the title bar gets created and then removed which is a waste of resource
Ok good try but it is not working. I get: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application if I want to shwo the dialog.
Change the alert dialog type to system dialog ( e.g., TYPE_SYSTEM_OVERLAY ) and see if this resolves your issue
I've tried to support the -ve values for @Ivan Stin excellent 2nd method. (Major credit goes to @Ivan Stin for his method)
public static float round(float value, int scale) {
int pow = 10;
for (int i = 1; i < scale; i++) {
pow *= 10;
}
float tmp = value * pow;
float tmpSub = tmp - (int) tmp;
return ( (float) ( (int) (
value >= 0
? (tmpSub >= 0.5f ? tmp + 1 : tmp)
: (tmpSub >= -0.5f ? tmp : tmp - 1)
) ) ) / pow;
// Below will only handles +ve values
// return ( (float) ( (int) ((tmp - (int) tmp) >= 0.5f ? tmp + 1 : tmp) ) ) / pow;
}
Below are the tests cases I've tried. Please let me know if this is not addressing any other cases.
@Test
public void testFloatRound() {
// +ve values
Assert.assertEquals(0F, NumberUtils.round(0F), 0);
Assert.assertEquals(1F, NumberUtils.round(1F), 0);
Assert.assertEquals(23.46F, NumberUtils.round(23.4567F), 0);
Assert.assertEquals(23.45F, NumberUtils.round(23.4547F), 0D);
Assert.assertEquals(1.00F, NumberUtils.round(0.49999999999999994F + 0.5F), 0);
Assert.assertEquals(123.12F, NumberUtils.round(123.123F), 0);
Assert.assertEquals(0.12F, NumberUtils.round(0.123F), 0);
Assert.assertEquals(0.55F, NumberUtils.round(0.55F), 0);
Assert.assertEquals(0.55F, NumberUtils.round(0.554F), 0);
Assert.assertEquals(0.56F, NumberUtils.round(0.556F), 0);
Assert.assertEquals(123.13F, NumberUtils.round(123.126F), 0);
Assert.assertEquals(123.15F, NumberUtils.round(123.15F), 0);
Assert.assertEquals(123.17F, NumberUtils.round(123.1666F), 0);
Assert.assertEquals(123.46F, NumberUtils.round(123.4567F), 0);
Assert.assertEquals(123.87F, NumberUtils.round(123.8711F), 0);
Assert.assertEquals(123.15F, NumberUtils.round(123.15123F), 0);
Assert.assertEquals(123.89F, NumberUtils.round(123.8909F), 0);
Assert.assertEquals(124.00F, NumberUtils.round(123.9999F), 0);
Assert.assertEquals(123.70F, NumberUtils.round(123.7F), 0);
Assert.assertEquals(123.56F, NumberUtils.round(123.555F), 0);
Assert.assertEquals(123.00F, NumberUtils.round(123.00F), 0);
Assert.assertEquals(123.50F, NumberUtils.round(123.50F), 0);
Assert.assertEquals(123.93F, NumberUtils.round(123.93F), 0);
Assert.assertEquals(123.93F, NumberUtils.round(123.9312F), 0);
Assert.assertEquals(123.94F, NumberUtils.round(123.9351F), 0);
Assert.assertEquals(123.94F, NumberUtils.round(123.9350F), 0);
Assert.assertEquals(123.94F, NumberUtils.round(123.93501F), 0);
Assert.assertEquals(99.99F, NumberUtils.round(99.99F), 0);
Assert.assertEquals(100.00F, NumberUtils.round(99.999F), 0);
Assert.assertEquals(100.00F, NumberUtils.round(99.9999F), 0);
// -ve values
Assert.assertEquals(-123.94F, NumberUtils.round(-123.93501F), 0);
Assert.assertEquals(-123.00F, NumberUtils.round(-123.001F), 0);
Assert.assertEquals(-0.94F, NumberUtils.round(-0.93501F), 0);
Assert.assertEquals(-1F, NumberUtils.round(-1F), 0);
Assert.assertEquals(-0.50F, NumberUtils.round(-0.50F), 0);
Assert.assertEquals(-0.55F, NumberUtils.round(-0.55F), 0);
Assert.assertEquals(-0.55F, NumberUtils.round(-0.554F), 0);
Assert.assertEquals(-0.56F, NumberUtils.round(-0.556F), 0);
Assert.assertEquals(-0.12F, NumberUtils.round(-0.1234F), 0);
Assert.assertEquals(-0.12F, NumberUtils.round(-0.123456789F), 0);
Assert.assertEquals(-0.13F, NumberUtils.round(-0.129F), 0);
Assert.assertEquals(-99.99F, NumberUtils.round(-99.99F), 0);
Assert.assertEquals(-100.00F, NumberUtils.round(-99.999F), 0);
Assert.assertEquals(-100.00F, NumberUtils.round(-99.9999F), 0);
}
The way I typically handle this is with a second piece of software. For Windows I use Notepad++, for OS X I use Sublime Text 2.
You don't need to bother with that. Just write
<input type="text" name="email" placeholder="[email protected]" size="30">
replace the value with placeholder
You could try BeeWare - as described on their website:
Write your apps in Python and release them on iOS, Android, Windows, MacOS, Linux, Web, and tvOS using rich, native user interfaces. One codebase. Multiple apps.
Gives you want you want now to write Android Apps in Python, plus has the advantage that you won't need to learn yet another framework in future if you end up also wanting to do something on one of the other listed platforms.
Here's the Tutorial for Android Apps.
Basically copying and pasting from Bjarne Stroustrup's "The C++ Programming Language 4th Edition":
List initialization does not allow narrowing (§iso.8.5.4). That is:
Example:
void fun(double val, int val2) {
int x2 = val; // if val == 7.9, x2 becomes 7 (bad)
char c2 = val2; // if val2 == 1025, c2 becomes 1 (bad)
int x3 {val}; // error: possible truncation (good)
char c3 {val2}; // error: possible narrowing (good)
char c4 {24}; // OK: 24 can be represented exactly as a char (good)
char c5 {264}; // error (assuming 8-bit chars): 264 cannot be
// represented as a char (good)
int x4 {2.0}; // error: no double to int value conversion (good)
}
The only situation where = is preferred over {} is when using auto
keyword to get the type determined by the initializer.
Example:
auto z1 {99}; // z1 is an int
auto z2 = {99}; // z2 is std::initializer_list<int>
auto z3 = 99; // z3 is an int
Prefer {} initialization over alternatives unless you have a strong reason not to.
I had the same problem. I solved it the following way :
1. Go to Settings->Storage->Click the USB icon at top
2. Make sure that MTP is selected
The problem described here was solved by me quite a long time ago but I don't really remember what was the main reason that uploads weren't working. There were multiple things that needed fixing so the upload could work. I have created checklist that might help others having similar problems and I will edit it to make it as helpful as possible. As I said before on chat, I was working on embedded system, so some points may be skipped on non-embedded systems.
Check upload_tmp_dir
in php.ini. This is directory where PHP stores temporary files while uploading.
Check open_basedir
in php.ini. If defined it limits PHP read/write rights to specified path and its subdirectories. Ensure that upload_tmp_dir
is inside this path.
Check post_max_size
in php.ini. If you want to upload 20 Mbyte files, try something a little bigger, like post_max_size = 21M
. This defines largest size of POST message which you are probably using during upload.
Check upload_max_filesize
in php.ini. This specifies biggest file that can be uploaded.
Check memory_limit
in php.ini. That's the maximum amount of memory a script may consume. It's quite obvious that it can't be lower than upload size (to be honest I'm not quite sure about it-PHP is probably buffering while copying temporary files).
Ensure that you're checking the right php.ini file that is one used by PHP on your webserver. The best solution is to execute script with directive described here http://php.net/manual/en/function.php-ini-loaded-file.php (php_ini_loaded_file
function)
Check what user php runs as (See here how to do it: How to check what user php is running as? ). I have worked on different distros and servers. Sometimes it is apache
, but sometimes it can be root
. Anyway, check that this user has rights for reading and writing in the temporary directory and directory that you're uploading into. Check all directories in the path in case you're uploading into subdirectory (for example /dir1/dir2/
-check both dir1
and dir2
.
On embedded platforms you sometimes need to restrict writing to root filesystem because it is stored on flash card and this helps to extend life of this card. If you are using scripts to enable/disable file writes, ensure that you enable writing before uploading.
I had serious problems with PHP >5.4 upload monitoring based on sessions (as described here http://phpmaster.com/tracking-upload-progress-with-php-and-javascript/ ) on some platforms. Try something simple at first (like here: http://www.dzone.com/snippets/very-simple-php-file-upload ). If it works, you can try more sophisticated mechanisms.
If you make any changes in php.ini remember to restart server so the configuration will be reloaded.
\d tablename
shows the column names for me on version 8.3.8.
"username_idx" UNIQUE, btree (username), tablespace "alldata1"
java.sql.Timestamp
is a subclass of java.util.Date
. So, just upcast it.
Date dtStart = resultSet.getTimestamp("dtStart");
Date dtEnd = resultSet.getTimestamp("dtEnd");
Using SimpleDateFormat
and creating Joda DateTime
should be straightforward from this point on.
@foreach (var m in Model)
{
<img src="~/Images/@m.Url" style="overflow: hidden; position: relative; width:200px; height:200px;" />
}
I find the following tricks give between 2x and 4x speed increase versus the pandas method described above (i.e. pd.DatetimeIndex(dates).year
etc.). The speed of [dt.year for dt in dates.astype(object)]
I find to be similar to the pandas method. Also these tricks can be applied directly to ndarrays of any shape (2D, 3D etc.)
dates = np.arange(np.datetime64('2000-01-01'), np.datetime64('2010-01-01'))
years = dates.astype('datetime64[Y]').astype(int) + 1970
months = dates.astype('datetime64[M]').astype(int) % 12 + 1
days = dates - dates.astype('datetime64[M]') + 1
just in case if you want next day or previous day from today's date
date("Y-m-d", mktime(0, 0, 0, date("m"),date("d")-1,date("Y")));
just change the "-1" to the "+1" regards, Yosafat
sizeof
returns the size of the type of the variable in bytes. So in your case it's returning the size of your char[7]
which is 7 * sizeof(char)
. Since sizeof(char) = 1
, the result is 7.
Expanding this to another example:
int intArr[5];
printf("sizeof(intArr)=%u", sizeof(intArr));
would yield 5 * sizeof(int)
, so you'd get the result "20" (At least on a regular 32bit platform. On others sizeof(int)
might differ)
To return to your problem:
It seems like, that what you want to know is the length of the string which is contained inside your array and not the total array size.
By definition C-Strings have to be terminated with a trailing '\0' (0-Byte). So to get the appropriate length of the string contained within your array, you have to first terminate the string, so that you can tell when it's finished. Otherwise there would be now way to know.
All standard functions build upon this definition, so if you call strlen
to retrieve
the str ing len gth, it will iterate through the given array until it finds the first 0-byte, which in your case would be the very first element.
Another thing you might need to know that only because you don't fill the remaining elements of your char[7]
with a value, they actually do contain random undefined values.
Hope that helped.
If you want to use C++ streams rather than C functions, you can do the following:
int ar[] = { 20, 30, 40, 50, 60, 70, 80, 90 };
const int siz_ar = sizeof(ar) / sizeof(int);
for (int i = 0; i < siz_ar; ++i)
cout << ar[i] << " ";
cout << endl;
for (int i = 0; i < siz_ar; ++i)
cout << hex << setfill('0') << setw(2) << ar[i] << " ";
cout << endl;
Very simple.
Output:
20 30 40 50 60 70 80 90
14 1e 28 32 3c 46 50 5a
I figured it out myself with the help of someone's answer. But he deleted it for some reason.
Here's the solution:
Listen on (window).resize event and ONLY apply inline CSS height IF the viewport is larger than the height of #truecontent, otherwise keep intact
$(function(){
var windowH = $(window).height();
var wrapperH = $('#wrapper').height();
if(windowH > wrapperH) {
$('#wrapper').css({'height':($(window).height())+'px'});
}
$(window).resize(function(){
var windowH = $(window).height();
var wrapperH = $('#wrapper').height();
var differenceH = windowH - wrapperH;
var newH = wrapperH + differenceH;
var truecontentH = $('#truecontent').height();
if(windowH > truecontentH) {
$('#wrapper').css('height', (newH)+'px');
}
})
});
Swift 2.x answer:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
self.getResultSetFromDB(docids)
}
Take a look at jfxmessagebox (http://en.sourceforge.jp/projects/jfxmessagebox/) if you are looking for very simple dialog popups.
Please NOTE that this procedure of adding the reporting services described by @Rich Shealer above will be iterated every time you start a different project. In order to avoid that:
If you may need to set up a different computer (eg, at home without internet), then keep your downloaded installers from the marketplace somewhere safe, ie:
Fetch the following libraries from the packages or bin folder of the application you have created with reporting services in it:
Install the 2 components from 1 above
You are now good to go! ReportViewer icon will be added to your toolbar, and you will also now find Report and ReportWizard templates added to your Common list of templates when you want to add a New Item... (Report) to your project
NB: When set up using Nuget package manager, the Report and ReportWizard templates are grouped under Reporting. Using my method described above however does not add the Reporting grouping in installed templates, but I dont think it is any trouble given that it enables you to quickly integrate rdlc without internet and without downloading what you already have from Nuget every time!
Add a user option in msyql.
GRANT PROXY ON ''@'' TO 'root'@'localhost' WITH GRANT OPTION;
and this link will be useful.
the error for Response.END(); is because you are using a asp update panel or any control that using javascript, try to use control native from asp or html without javascript or scriptmanager or scripting and try again
Assuming there is a column named business:
SELECT Business, COUNT(*) FROM eventsTable GROUP BY Business
I found the OpenSSL answer given above didn't work for me, but the following did, working with a CRT file sourced from windows.
openssl x509 -inform DER -in yourdownloaded.crt -out outcert.pem -text
If you read the comments there's a nice discussion around this particular naming convention.
It seems that since my answer has been posted the naming convention has gotten more formal. People who teach, write books, etc. speak about var
declaration, and function
declaration.
Here is the additional Wikipedia post that supports my point: Declarations and definitions ...and to answer the main question. Declare variable before your function. This will work and it will comply to the good practice of declaring your variables at the top of the scope :)
As mentioned previously, a function needs to be passed to toThrow
as it is the function you're describing in your test: "I expect this function to throw x"
expect(() => parser.parse(raw))
.toThrow(new Error('Parsing is not possible'));
If using Jasmine-Matchers you can also use one of the following when they suit the situation;
// I just want to know that an error was
// thrown and nothing more about it
expect(() => parser.parse(raw))
.toThrowAnyError();
or
// I just want to know that an error of
// a given type was thrown and nothing more
expect(() => parser.parse(raw))
.toThrowErrorOfType(TypeError);
Use This as the solution
This worked for me perfectly..
<div align="center">
<img src="">
</div>
This answer is deprecated, please see @ankitjaininfo's answer below for a more modern solution
Here's how I think you make a POST request with data and a cookie using just the node http library. This example is posting JSON, set your content-type and content-length accordingly if you post different data.
// NB:- node's http client API has changed since this was written
// this code is for 0.4.x
// for 0.6.5+ see http://nodejs.org/docs/v0.6.5/api/http.html#http.request
var http = require('http');
var data = JSON.stringify({ 'important': 'data' });
var cookie = 'something=anything'
var client = http.createClient(80, 'www.example.com');
var headers = {
'Host': 'www.example.com',
'Cookie': cookie,
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(data,'utf8')
};
var request = client.request('POST', '/', headers);
// listening to the response is optional, I suppose
request.on('response', function(response) {
response.on('data', function(chunk) {
// do what you do
});
response.on('end', function() {
// do what you do
});
});
// you'd also want to listen for errors in production
request.write(data);
request.end();
What you send in the Cookie
value should really depend on what you received from the server. Wikipedia's write-up of this stuff is pretty good: http://en.wikipedia.org/wiki/HTTP_cookie#Cookie_attributes
I just give other option for this question - you need to use '.dt' in your code:
import pandas as pd_x000D_
_x000D_
df.index = pd.to_datetime(df.index)_x000D_
_x000D_
#for get year_x000D_
df.index.dt.year_x000D_
_x000D_
#for get month_x000D_
df.index.dt.month_x000D_
_x000D_
#for get day_x000D_
df.index.dt.day_x000D_
_x000D_
#for get hour_x000D_
df.index.dt.hour_x000D_
_x000D_
#for get minute_x000D_
df.index.dt.minute
_x000D_
From: http://java.sun.com/javase/6/docs/technotes/tools/windows/classpath.html
Class path entries can contain the basename wildcard character
*
, which is considered equivalent to specifying a list of all the files in the directory with the extension .jar or .JAR. For example, the class path entryfoo/*
specifies all JAR files in the directory named foo. A classpath entry consisting simply of*
expands to a list of all the jar files in the current directory.
This should work in Java6, not sure about Java5
(If it seems it does not work as expected, try putting quotes. eg: "foo/*"
)
You can convert a tensor in tensorflow
to numpy
array in the following ways.
First:
Use np.array(your_tensor)
Second:
Use your_tensor.numpy
To install an APK on your mobile, you can either:
adb install filename.apk
.
Note, you'll need to enable USB debugging for this to work.Note, that you'll have to enable installing packages from Unknown Sources in your Applications settings.
As for getting USB to work, I suggest consulting the Android StackExchange for advice.
Why would you use reduce()
for this when Python has a perfectly cromulent sum()
function?
print sum(l) / float(len(l))
(The float()
is necessary to force Python to do a floating-point division.)
You may not be able to create a primary key (per say) but if your view is based on a table with a primary key and the key is included in the view, then the primary key will be reflected in the view also. Applications requiring a primary key may accept the view as it is the case with Lightswitch.
Applying the text-align:center
style to an element containing elements will center those elements.
<div id="method-one" style="text-align:center">
CSS `text-align:center`
</div>
Thomas Shields mentions this method
Applying the margin:0 auto
style to a block element will center it within the element it is in.
<div id="method-two" style="background-color:green">
<div style="margin:0 auto;width:50%;background-color:lightblue">
CSS `margin:0 auto` to have left and right margin set to center a block element within another element.
</div>
</div>
user1468562 mentions this method
My original answer was that you can use the <center></center>
tag. To do this, just place the content you want centered between the tags. As of HTML4, this tag has been deprecated, though. <center>
is still technically supported today (9 years later at the time of updating this), but I'd recommend the CSS alternatives I've included above.
<h3>Method 3</h1>
<div id="method-three">
<center>Center tag (not recommended and deprecated in HTML4)</center>
</div>
You can see these three code samples in action in this jsfiddle.
I decided I should revise this answer as the previous one I gave was outdated. It was already deprecated when I suggested it as a solution and that's all the more reason to avoid it now 9 years later.
By using array.map we can reduce the loop, see this on jsfiddle
function Check(){
var arr = Array.prototype.slice.call(arguments);
var result = [];
for(i=0; i< arr.length; i++){
var duplicate = 0;
var val = arr[i];
arr.map(function(x){
if(val === x) duplicate++;
})
result.push(duplicate>= 2);
}
return result;
}
To Test:
var test = new Check(1,2,1,4,1);
console.log(test);
Correction to top query above, to allow to run from any database
SELECT COUNT(COLUMN_NAME) FROM [*database*].INFORMATION_SCHEMA.COLUMNS WHERE
TABLE_CATALOG = 'database' AND TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'table'
I got this error for my Linux Jenkins slave. I fixed it by changing from the node from "Known hosts file Verification Strategy" to "Non verifying Verification Strategy".
In case anyone is looking for recursive.
<?php
echo scanDirectoryImages("images");
/**
* Recursively search through directory for images and display them
*
* @param array $exts
* @param string $directory
* @return string
*/
function scanDirectoryImages($directory, array $exts = array('jpeg', 'jpg', 'gif', 'png'))
{
if (substr($directory, -1) == '/') {
$directory = substr($directory, 0, -1);
}
$html = '';
if (
is_readable($directory)
&& (file_exists($directory) || is_dir($directory))
) {
$directoryList = opendir($directory);
while($file = readdir($directoryList)) {
if ($file != '.' && $file != '..') {
$path = $directory . '/' . $file;
if (is_readable($path)) {
if (is_dir($path)) {
return scanDirectoryImages($path, $exts);
}
if (
is_file($path)
&& in_array(end(explode('.', end(explode('/', $path)))), $exts)
) {
$html .= '<a href="' . $path . '"><img src="' . $path
. '" style="max-height:100px;max-width:100px" /></a>';
}
}
}
}
closedir($directoryList);
}
return $html;
}
You could (but you shouldn't) use reflection for the job:
import java.lang.reflect.Field;
public class Outer {
public class Inner {
}
public static void main(String[] args) throws Exception {
// Create the inner instance
Inner inner = new Outer().new Inner();
// Get the implicit reference from the inner to the outer instance
// ... make it accessible, as it has default visibility
Field field = Inner.class.getDeclaredField("this$0");
field.setAccessible(true);
// Dereference and cast it
Outer outer = (Outer) field.get(inner);
System.out.println(outer);
}
}
Of course, the name of the implicit reference is utterly unreliable, so as I said, you shouldn't :-)
.... but how do we find the equivalent class in the second List to pass to the method below;
This is your actual problem; you must have at least one immutable property, a id or something like that, to identify corresponding objects in both lists. If you do not have such a property you, cannot solve the problem without errors. You can just try to guess corresponding objects by searching for minimal or logical changes.
If you have such an property, the solution becomes really simple.
Enumerable.Join(
listA, listB,
a => a.Id, b => b.Id,
(a, b) => CompareTwoClass_ReturnDifferences(a, b))
thanks to you both danbruc and Noldorin for your feedback. both Lists will be the same length and in the same order. so the method above is close, but can you modify this method to pass the enum.Current to the method i posted above?
Now I am confused ... what is the problem with that? Why not just the following?
for (Int32 i = 0; i < Math.Min(listA.Count, listB.Count); i++)
{
yield return CompareTwoClass_ReturnDifferences(listA[i], listB[i]);
}
The Math.Min() call may even be left out if equal length is guaranted.
Noldorin's implementation is of course smarter because of the delegate and the use of enumerators instead of using ICollection.
This is actually a fairly interesting question. It's not as simple as it looks at first. For reference, I'm going to be basing this off of the latest C11 language grammar defined in N1570
I guess the counter-intuitive part of the question is: if this is correct C:
if (a == 1) {
int b = 10;
}
then why is this not also correct C?
if (a == 1)
int b = 10;
I mean, a one-line conditional if
statement should be fine either with or without braces, right?
The answer lies in the grammar of the if
statement, as defined by the C standard. The relevant parts of the grammar I've quoted below. Succinctly: the int b = 10
line is a declaration, not a statement, and the grammar for the if
statement requires a statement after the conditional that it's testing. But if you enclose the declaration in braces, it becomes a statement and everything's well.
And just for the sake of answering the question completely -- this has nothing to do with scope. The b
variable that exists inside that scope will be inaccessible from outside of it, but the program is still syntactically correct. Strictly speaking, the compiler shouldn't throw an error on it. Of course, you should be building with -Wall -Werror
anyways ;-)
(6.7) declaration: declaration-speci?ers init-declarator-listopt ; static_assert-declaration (6.7) init-declarator-list: init-declarator init-declarator-list , init-declarator (6.7) init-declarator: declarator declarator = initializer (6.8) statement: labeled-statement compound-statement expression-statement selection-statement iteration-statement jump-statement (6.8.2) compound-statement: { block-item-listopt } (6.8.4) selection-statement: if ( expression ) statement if ( expression ) statement else statement switch ( expression ) statement
In IntelliJ, the default maven compiler version is less than version 5, which is not supported, so we have to manually change the version of the maven compiler.
We have two ways to define version.
First way:
<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties>
Second way:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
Thanks Ravi and other users .... Nevertheless I have got the solution
SELECT @phoneNumber=
CASE
WHEN ISNULL(rdg2.nPhoneNumber ,'0') in ('0','-',NULL)
THEN ISNULL(rdg2.nMobileNumber, '0')
WHEN ISNULL(rdg2.nMobileNumber, '0') in ('0','-',NULL)
THEN '0'
ELSE ISNULL(rdg2.nPhoneNumber ,'0')
END
FROM tblReservation_Details_Guest rdg2
WHERE nReservationID=@nReservationID
Just need to put '0' instead of 0
In Swift (I'm using 4.0), you can accomplish this by creating a custom UITableViewCell
class, and overriding
the setSelected
method. Then the separator insets
all to 0. (my main class with the table view has a clear background) color.
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// eliminate extra separators below UITableView
self.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
With POST you can also do multipart mime encoding which means you can attach files as well. Also if you are using post variables across navigation of pages, the user will get a warning asking if they want to resubmit the post parameter. Typically they look the same in an HTTP request, but you should just stick to POST if you need to "POST" something TO a server and "GET" if you need to GET something FROM a server as that's the way they were intended.
Use the GD library or ImageMagick. I googled 'PHP GD merge images' and got several articles on doing this. In the past what I've done is create a large blank image, and then used imagecopymerge() to paste those images into my original blank one. Check out the articles on google you'll find some source code you can start using right away.
The grammar of the language specifies that positional arguments appear before keyword or starred arguments in calls:
argument_list ::= positional_arguments ["," starred_and_keywords]
["," keywords_arguments]
| starred_and_keywords ["," keywords_arguments]
| keywords_arguments
Specifically, a keyword argument looks like this: tag='insider trading!'
while a positional argument looks like this: ..., exchange, ...
. The problem lies in that you appear to have copy/pasted the parameter list, and left some of the default values in place, which makes them look like keyword arguments rather than positional ones. This is fine, except that you then go back to using positional arguments, which is a syntax error.
Also, when an argument has a default value, such as price=None
, that means you don't have to provide it. If you don't provide it, it will use the default value instead.
To resolve this error, convert your later positional arguments into keyword arguments, or, if they have default values and you don't need to use them, simply don't specify them at all:
order_id = kite.order_place(self, exchange, tradingsymbol,
transaction_type, quantity)
# Fully positional:
order_id = kite.order_place(self, exchange, tradingsymbol, transaction_type, quantity, price, product, order_type, validity, disclosed_quantity, trigger_price, squareoff_value, stoploss_value, trailing_stoploss, variety, tag)
# Some positional, some keyword (all keywords at end):
order_id = kite.order_place(self, exchange, tradingsymbol,
transaction_type, quantity, tag='insider trading!')
This exception can raise when you handle Deep linking
or URL for a browser, if there is no default installed. In case of Deep linking there may be no application installed that can process a link in format myapp://mylink
.
You can use the tangerine solution for API up to 29:
private fun openUrl(url: String) {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
val activityInfo = intent.resolveActivityInfo(packageManager, intent.flags)
if (activityInfo?.exported == true) {
startActivity(intent)
} else {
Toast.makeText(
this,
"No application that can handle this link found",
Toast.LENGTH_SHORT
).show()
}
}
For API >= 30 see intent.resolveActivity returns null in API 30.
To get the moving average in pandas we can use cum_sum and then divide by count.
Here is the working example:
import pandas as pd
import numpy as np
df = pd.DataFrame({'id': range(5),
'value': range(100,600,100)})
# some other similar statistics
df['cum_sum'] = df['value'].cumsum()
df['count'] = range(1,len(df['value'])+1)
df['mov_avg'] = df['cum_sum'] / df['count']
# other statistics
df['rolling_mean2'] = df['value'].rolling(window=2).mean()
print(df)
id value cum_sum count mov_avg rolling_mean2
0 0 100 100 1 100.0 NaN
1 1 200 300 2 150.0 150.0
2 2 300 600 3 200.0 250.0
3 3 400 1000 4 250.0 350.0
4 4 500 1500 5 300.0 450.0
I think that equality is something that can be absolutely determined. The trouble with null
is that it's inherently unknown. Null
combined with any other value is null
- unknown. Asking SQL "Is my value equal to null
?" would be unknown every single time, even if the input is null
. I think the implementation of IS NULL
makes it clear.
I was having a similar problem. PHP was working on my sites configured by virtualmin but not for phpmyadmin. PHPMyAdmin would not execute and the file was being downloaded by the browser. Everything I was reading was saying that libapache2-mod-php5 was not installed but I knew it was... so the thing to do was to purge it and reinstall.
sudo apt-get purge libapache2-mod-php5
sudo apt-get install libapache2-mod-php5
sudo apt-get purge phpmyadmin
sudo apt-get install phpmyadmin
sudo /etc/init.d/apache2 restart
If they all have the same extension (for example .jpg), you can use this:
for picture in *.jpg ; do
echo "the next file is $picture"
done
(This solution also works if the filename has spaces)
Either !=
or ne
will work, but you need to get the accessor syntax and nested quotes sorted out.
<c:if test="${content.contentType.name ne 'MCE'}">
<%-- snip --%>
</c:if>
Id : 1) It is used to identify the HTML element through the Document Object Model (via Javascript or styled with CSS). 2) Id is expected to be unique within the page.
Name corresponds to the form element and identifies what is posted back to the server. Example :
<form action="action_page.php" id="Myform">
First name: <input type="text" name="FirstName"><br>
<input type="submit" value="Submit">
</form>
<p>The "Last name" field below is outside the form element, but still part of the form.</p>
Last name: <input type="text" name="LastName" form="Myform">
A more straight forward way is to check for equality
if string1 == string2
puts "match"
else
puts "not match"
end
however, if you really want to stick to regular expression,
string1 =~ /^123456$/
For future references :
we can use isInCollection
to filter ,here is a example :
Note : It will look for exact match
def getSelectedTablesRows(allTablesInfoDF: DataFrame, tableNames: Seq[String]): DataFrame = {
allTablesInfoDF.where(col("table_name").isInCollection(tableNames))
}
My solution:
It worked for me after the second try.
You can use putStringSet
This allow you to save a HashSet in your preferences, just like this:
Save
Set<String> values;
SharedPreferences sharedPref =
mContext.getSharedPreferences(PREF_KEY, Context.MODE_PRIVATE);
Editor editor = sharedPref.edit();
editor.putStringSet("YOUR_KEY", values);
editor.apply();
Retrive
SharedPreferences sharedPref =
mContext.getSharedPreferences(PREF_KEY, Context.MODE_PRIVATE);
Editor editor = sharedPref.edit();
Set<String> newList = editor.getStringSet("YOUR_KEY", null);
The putStringSet allow just a Set and this is an unordered list.
function search($array, $key, $value)
{
$results = array();
if (is_array($array))
{
if (isset($array[$key]) && $array[$key] == $value)
$results[] = $array;
foreach ($array as $subarray)
$results = array_merge($results, search($subarray, $key, $value));
}
return $results;
}
in may case setting SMTPAuth to true fixed it. Of-course you need to set permissions for "Less secure apps" to Enabled.
$mail->SMTPAuth = true;
Sadly, many JSON C++ libraries have APIs that are non trivial to use, while JSON was intended to be easy to use.
So I tried jsoncpp from the gSOAP tools on the JSON doc shown in one of the answers above and this is the code generated with jsoncpp to construct a JSON object in C++ which is then written in JSON format to std::cout:
value x(ctx);
x["appDesc"]["description"] = "SomeDescription";
x["appDesc"]["message"] = "SomeMessage";
x["appName"]["description"] = "Home";
x["appName"]["message"] = "Welcome";
x["appName"]["imp"][0] = "awesome";
x["appName"]["imp"][1] = "best";
x["appName"]["imp"][2] = "good";
std::cout << x << std::endl;
and this is the code generated by jsoncpp to parse JSON from std::cin and extract its values (replace USE_VAL
as needed):
value x(ctx);
std::cin >> x;
if (x.soap->error)
exit(EXIT_FAILURE); // error parsing JSON
#define USE_VAL(path, val) std::cout << path << " = " << val << std::endl
if (x.has("appDesc"))
{
if (x["appDesc"].has("description"))
USE_VAL("$.appDesc.description", x["appDesc"]["description"]);
if (x["appDesc"].has("message"))
USE_VAL("$.appDesc.message", x["appDesc"]["message"]);
}
if (x.has("appName"))
{
if (x["appName"].has("description"))
USE_VAL("$.appName.description", x["appName"]["description"]);
if (x["appName"].has("message"))
USE_VAL("$.appName.message", x["appName"]["message"]);
if (x["appName"].has("imp"))
{
for (int i2 = 0; i2 < x["appName"]["imp"].size(); i2++)
USE_VAL("$.appName.imp[]", x["appName"]["imp"][i2]);
}
}
This code uses the JSON C++ API of gSOAP 2.8.28. I don't expect people to change libraries, but I think this comparison helps to put JSON C++ libraries in perspective.
Well, you can hide it, by removing the entire system menu:
private const int WS_SYSMENU = 0x80000;
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.Style &= ~WS_SYSMENU;
return cp;
}
}
Of course, doing so removes the minimize and maximize buttons.
If you keep the system menu but remove the close item then the close button remains but is disabled.
The final alternative is to paint the non-client area yourself. That's pretty hard to get right.
I would do something like this:
function getCookie(cookie){
return cookie
.trim()
.split(';')
.map(function(line){return line.split(',');})
.reduce(function(props,line) {
var name = line[0].slice(0,line[0].search('='));
var value = line[0].slice(line[0].search('='));
props[name] = value;
return props;
},{})
}
This will return your cookie as an object.
And then you can call it like this:
getCookie(document.cookie)['shares']
I'd like to add that usually you'll want the program to wait only if it's connected to a console. Otherwise (like if it's a part of a pipeline) there is no point printing a message or waiting. For that you could use Java's Console
like this:
import java.io.Console;
// ...
public static void waitForEnter(String message, Object... args) {
Console c = System.console();
if (c != null) {
// printf-like arguments
if (message != null)
c.format(message, args);
c.format("\nPress ENTER to proceed.\n");
c.readLine();
}
}
If the function floatval does not work you can try to make this :
$string = "2968789218";
$float = $string * 1.0;
echo $float;
But for me all the previous answer worked ( try it in http://writecodeonline.com/php/ ) Maybe the problem is on your server ?
Wen-wei Liao's answer is good if you are not trying to export vector graphics or that you have set up your matplotlib backends to ignore colorless axes; otherwise the hidden axes would show up in the exported graphic.
My answer suplabel
here is similar to the fig.suptitle
which uses the fig.text
function. Therefore there is no axes artist being created and made colorless.
However, if you try to call it multiple times you will get text added on top of each other (as fig.suptitle
does too). Wen-wei Liao's answer doesn't, because fig.add_subplot(111)
will return the same Axes object if it is already created.
My function can also be called after the plots have been created.
def suplabel(axis,label,label_prop=None,
labelpad=5,
ha='center',va='center'):
''' Add super ylabel or xlabel to the figure
Similar to matplotlib.suptitle
axis - string: "x" or "y"
label - string
label_prop - keyword dictionary for Text
labelpad - padding from the axis (default: 5)
ha - horizontal alignment (default: "center")
va - vertical alignment (default: "center")
'''
fig = pylab.gcf()
xmin = []
ymin = []
for ax in fig.axes:
xmin.append(ax.get_position().xmin)
ymin.append(ax.get_position().ymin)
xmin,ymin = min(xmin),min(ymin)
dpi = fig.dpi
if axis.lower() == "y":
rotation=90.
x = xmin-float(labelpad)/dpi
y = 0.5
elif axis.lower() == 'x':
rotation = 0.
x = 0.5
y = ymin - float(labelpad)/dpi
else:
raise Exception("Unexpected axis: x or y")
if label_prop is None:
label_prop = dict()
pylab.text(x,y,label,rotation=rotation,
transform=fig.transFigure,
ha=ha,va=va,
**label_prop)
Document.ready
(a jQuery event) will fire when all the elements are in place, and they can be referenced in the JavaScript code, but the content is not necessarily loaded. Document.ready
executes when the HTML document is loaded.
$(document).ready(function() {
// Code to be executed
alert("Document is ready");
});
The window.load
however will wait for the page to be fully loaded. This includes inner frames, images, etc.
$(window).load(function() {
//Fires when the page is loaded completely
alert("window is loaded");
});
jScrollPane is a good solution to cross browser scrollbars and degrades nicely.
I found a workaround that may apply to people trying to do something similar. Instead of disabling the button I put a simple if
statement in the function to check if the checkbox was checked.
If it wasn't, it displayed a simple message saying the box had to be checked before submission.
For example:
$("#confirmation-dialog").dialog({
modal: true,
autoOpen: false,
width: 600,
overlay: {
backgroundColor: '#000',
opacity: 0.5
},
close: function() {
$('input[type="submit"]')
.val('Record Reading')
.attr('disabled', false);
},
buttons: {
'Confirm Reading': function() {
if($('#check-box').attr("checked")){
$(this).dialog('close')
$('form')
.addClass('confirmed')
.submit();
}
else {
$('#please-check').show("slide");
}
}
}
});
Anyway, I hope that helps someone.
Give each xhr request a unique id and store the object reference in an object before sending. Delete the reference after an xhr request completes.
To cancel all request any time:
$.ajaxQ.abortAll();
Returns the unique ids of canceled request. Only for testing purposes.
Working function:
$.ajaxQ = (function(){
var id = 0, Q = {};
$(document).ajaxSend(function(e, jqx){
jqx._id = ++id;
Q[jqx._id] = jqx;
});
$(document).ajaxComplete(function(e, jqx){
delete Q[jqx._id];
});
return {
abortAll: function(){
var r = [];
$.each(Q, function(i, jqx){
r.push(jqx._id);
jqx.abort();
});
return r;
}
};
})();
Returns an object with single function which can be used to add more functionality when required.
filter_by
is used for simple queries on the column names using regular kwargs, like
db.users.filter_by(name='Joe')
The same can be accomplished with filter
, not using kwargs, but instead using the '==' equality operator, which has been overloaded on the db.users.name object:
db.users.filter(db.users.name=='Joe')
You can also write more powerful queries using filter
, such as expressions like:
db.users.filter(or_(db.users.name=='Ryan', db.users.country=='England'))
building on mwigdahls answer. if you also need to do grouping here is how to get it to look like
group, csv
'group1', 'paul, john'
'group2', 'mary'
--drop table #user
create table #user (groupName varchar(25), username varchar(25))
insert into #user (groupname, username) values ('apostles', 'Paul')
insert into #user (groupname, username) values ('apostles', 'John')
insert into #user (groupname, username) values ('family','Mary')
select
g1.groupname
, stuff((
select ', ' + g.username
from #user g
where g.groupName = g1.groupname
order by g.username
for xml path('')
),1,2,'') as name_csv
from #user g1
group by g1.groupname
There are two ways,
android:screenOrientation="portrait"
for each Activity in Manifest Filethis.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
in each java file.Microsoft says the SQL Server 2005 it's not compatible with Windows 8, but I've run it without problems (only using SP3) except the installation.
After you run the install file SQLExpr.exe
look for a hidden folder recently created in the C drive. Copy the contents to another folder and cancel the installer (or use WinRar to open the file and extract the contents to a temp folder)
After that, find the file sqlncli_x64.msi
in the setup folder, and run it.
Now you are ready the run the setup.exe
file and install SQL server 2005 without errors
Assuming this is a personal certificate created by windows on the system you copied your project from, you can use the certificate manager on the system where the project is now and import the certificate. Start the certificate manager (certmgr) and select the personal certificates then right click below the list of existing certificates and select import from the tasks. Use the browse to find the .pfx in the project (the .pfx from the previous system that you copied over with the project). It should be in the sub-directory with the same name as the project directory. I am familiar with C# and VS, so if that is not your environment maybe the .pfx will be elsewhere or maybe this suggestion does not apply. After the import you should get a status message. If you succeeded, the compile certificate error should be gone.
Try using
<table border="1" cellspacing="0" cellpadding="0" class="template-table"
style="table-layout: fixed; width: 100%">
as table style along with
<td style="word-break:break-word">long text</td>
for td it works for normal/real scenario text with words, not for random typed letters without gaps
This is what I expected to see when I came to this question:
#!/usr/bin/env python
import pandas as pd
df = pd.DataFrame([(1, 2, 3, 4),
(5, 6, 7, 8),
(9, 0, 1, 2),
(3, 4, 5, 6)],
columns=list('abcd'),
index=['India', 'France', 'England', 'Germany'])
print(df)
gives
a b c d
India 1 2 3 4
France 5 6 7 8
England 9 0 1 2
Germany 3 4 5 6
I had same problem and I solved using this code
HTML
<span id="current"></span><br>
<input type="number" id="n" value="5" step=".5" />
You can add just 3 first lines the others parts is optional.
$('#n').on('change paste', function () {
$("#current").html($(this).val())
});
// here when click on spinner to change value, call trigger change
$(".input-group-btn-vertical").click(function () {
$("#n").trigger("change");
});
// you can use this to block characters non numeric
$("#n").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 || (e.keyCode === 65 && e.ctrlKey === true) || (e.keyCode >= 35 && e.keyCode <= 40))
return;
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105))
e.preventDefault();
});
Example here : http://jsfiddle.net/XezmB/1303/
Here's two interesting ways:
ubuntu@ubuntu:~$ yes = | head -10 | paste -s -d '' - ========== ubuntu@ubuntu:~$ yes = | head -10 | tr -d "\n" ==========ubuntu@ubuntu:~$
Note these two are subtly different - The paste
method ends in a new line. The tr
method does not.
You could use the String.charAt(int index)
method result as the parameter for String.valueOf(char c).
String.valueOf(myString.charAt(3)) // This will return a string of the character on the 3rd position.
Add a live template called "ser" to the other group, set it to "Applicable in Java: declaration", and untick "Shorten FQ names". Give it a template text of just:
$serial$
Now edit variables and set serial to:
groovyScript("(System.env.JDK_HOME+'/bin/serialver -classpath '+com.intellij.openapi.fileEditor.FileDocumentManager.instance.getFile(_editor.document).path.replaceAll('/java/.*','').replaceAll('/src/','/build/classes/')+' '+_1).execute().text.replaceAll('.*: *','')",qualifiedClassName())
It assumes the standard Gradle project layout. Change /build/ to /target/ for Maven.
This is how you do it column-wise:
[df[col].update((df[col] - df[col].min()) / (df[col].max() - df[col].min())) for col in df.columns]
The solution from the blog Prevent desktop lock or screensaver with PowerShell is working for me. Here is the relevant script, which simply sends a single period to the shell:
param($minutes = 60)
$myshell = New-Object -com "Wscript.Shell"
for ($i = 0; $i -lt $minutes; $i++) {
Start-Sleep -Seconds 60
$myshell.sendkeys(".")
}
and an alternative from the comments, which moves the mouse a single pixel:
$Pos = [System.Windows.Forms.Cursor]::Position
[System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point((($Pos.X) + 1) , $Pos.Y)
$Pos = [System.Windows.Forms.Cursor]::Position
[System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point((($Pos.X) - 1) , $Pos.Y)
if by Blue Border thats on top of the Window Form
you mean titlebar, set Forms ControlBox
property to false
and Text
property to empty string ("").
here's a snippet:
this.ControlBox = false;
this.Text = String.Empty;
Let's face it. PHP is ugly as hell without short tags.
You can enable them in a .htaccess
file if you can't get to the php.ini
:
php_flag short_open_tag on
In bash version 3 you can use the '=~' operator:
if [[ "$date" =~ ^[0-9]{8}$ ]]; then
echo "Valid date"
else
echo "Invalid date"
fi
Reference: http://tldp.org/LDP/abs/html/bashver3.html#REGEXMATCHREF
NOTE: The quoting in the matching operator within the double brackets, [[ ]], is no longer necessary as of Bash version 3.2
Usually, we define classes for this.
class XClass( object ):
def __init__( self ):
self.myAttr= None
x= XClass()
x.myAttr= 'magic'
x.myAttr
However, you can, to an extent, do this with the setattr
and getattr
built-in functions. However, they don't work on instances of object
directly.
>>> a= object()
>>> setattr( a, 'hi', 'mom' )
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'hi'
They do, however, work on all kinds of simple classes.
class YClass( object ):
pass
y= YClass()
setattr( y, 'myAttr', 'magic' )
y.myAttr
quick answer
#include<stdio.h>
#include<time.h>
int main()
{
clock_t t1, t2;
t1 = clock();
int i;
for(i = 0; i < 1000000; i++)
{
int x = 90;
}
t2 = clock();
float diff = ((float)(t2 - t1) / 1000000.0F ) * 1000;
printf("%f",diff);
return 0;
}
Make SymbolIndexer( const SymbolIndexer& )
private. If you're assigning to a reference, you're not copying.
Javac – compiler that converts source code to byte code. JVM- interpreter that converts byte code to machine language code.
As we know java is both compile**r & **interpreter based language. Once the java code also known as source code is compiled, it gets converted to native code known as BYTE CODE which is portable & can be easily executed on all operating systems. Byte code generated is basically represented in hexa decimal format. This format is same on every platform be it Solaris work station or Macintosh, windows or Linux. After compilation, the interpreter reads the generated byte code & translates it according to the host machine. . Byte code is interpreted by Java Virtual Machine which is available with all the operating systems we install. so to port Java programs to a new platform all that is required is to port the interpreter and some of the library routines.
Hope it helps!!!
You can only use await
in an async
method, and Main
cannot be async
.
You'll have to use your own async
-compatible context, call Wait
on the returned Task
in the Main
method, or just ignore the returned Task
and just block on the call to Read
. Note that Wait
will wrap any exceptions in an AggregateException
.
If you want a good intro, see my async
/await
intro post.
This answer is to iterate over selected columns as well as all columns in a DF.
df.columns
gives a list containing all the columns' names in the DF. Now that isn't very helpful if you want to iterate over all the columns. But it comes in handy when you want to iterate over columns of your choosing only.
We can use Python's list slicing easily to slice df.columns according to our needs. For eg, to iterate over all columns but the first one, we can do:
for column in df.columns[1:]:
print(df[column])
Similarly to iterate over all the columns in reversed order, we can do:
for column in df.columns[::-1]:
print(df[column])
We can iterate over all the columns in a lot of cool ways using this technique. Also remember that you can get the indices of all columns easily using:
for ind, column in enumerate(df.columns):
print(ind, column)
document.getElementsByClassName
returns a NodeList
, not a single element, I'd recommend either using jQuery, since you'd only have to use something like $('.new').toggle()
or if you want plain JS try :
function toggle_by_class(cls, on) {
var lst = document.getElementsByClassName(cls);
for(var i = 0; i < lst.length; ++i) {
lst[i].style.display = on ? '' : 'none';
}
}
Extended Chris Pickett's answer because in my case I needed to search deeper than one attribute level:
function findWithAttr(array, attr, value) {
if (attr.indexOf('.') >= 0) {
var split = attr.split('.');
var attr1 = split[0];
var attr2 = split[1];
for(var i = 0; i < array.length; i += 1) {
if(array[i][attr1][attr2] === value) {
return i;
}
}
} else {
for(var i = 0; i < array.length; i += 1) {
if(array[i][attr] === value) {
return i;
}
}
};
};
You can pass 'attr1.attr2' into the function
from official doc version 4
const express = require('express')
const app = express()
app.use(express.json());
app.use(express.urlencoded({ extended: true }))
app.post('/push/send', (request, response) => {
console.log(request.body)
})
If you have a hidden field like this
<asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Eval("VertragNr") %>'/>
Now you can use your value like this
$(this).parent().find('input[type=hidden]').val()
If you're using SSMS (or old school Enterprise Manager) to edit the table directly, press CTRL+0 to add a null.
Avoid public variables, except for classes that are essentially C-style structs. It's just not a good practice to get into.
Once you've defined the class interface, you might never be able to change it (other than adding to it), because people will build on it and rely on it. Making a variable public means that you need to have that variable, and you need to make sure it has what the user needs.
Now, if you use a getter, you're promising to supply some information, which is currently kept in that variable. If the situation changes, and you'd rather not maintain that variable all the time, you can change the access. If the requirements change (and I've seen some pretty odd requirements changes), and you mostly need the name that's in this variable but sometimes the one in that variable, you can just change the getter. If you made the variable public, you'd be stuck with it.
This won't always happen, but I find it a lot easier just to write a quick getter than to analyze the situation to see if I'd regret making the variable public (and risk being wrong later).
Making member variables private is a good habit to get into. Any shop that has code standards is probably going to forbid making the occasional member variable public, and any shop with code reviews is likely to criticize you for it.
Whenever it really doesn't matter for ease of writing, get into the safer habit.
If this is from a SQL Server datebase you could issue this kind of query...
Select Top 1 DepartureTime From TrainSchedule where DepartureTime >
GetUTCDate()
Order By DepartureTime ASC
GetDate()
could also be used, not sure how dates are being stored.
I am not sure how the data is being stored and/or read.
Try this:
from __future__ import with_statement
filename1 = "G:\\test1.TXT"
filename2 = "G:\\test2.TXT"
with open(filename1) as f1:
with open(filename2) as f2:
file1list = f1.read().splitlines()
file2list = f2.read().splitlines()
list1length = len(file1list)
list2length = len(file2list)
if list1length == list2length:
for index in range(len(file1list)):
if file1list[index] == file2list[index]:
print file1list[index] + "==" + file2list[index]
else:
print file1list[index] + "!=" + file2list[index]+" Not-Equel"
else:
print "difference inthe size of the file and number of lines"
My solution is to define a merge function. It's not sophisticated and just cost one line. Here's the code in Python 3.
from functools import reduce
from operator import or_
def merge(*dicts):
return { k: reduce(lambda d, x: x.get(k, d), dicts, None) for k in reduce(or_, map(lambda x: x.keys(), dicts), set()) }
Tests
>>> d = {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
>>> d_letters = {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f', 6: 'g', 7: 'h', 8: 'i', 9: 'j', 10: 'k', 11: 'l', 12: 'm', 13: 'n', 14: 'o', 15: 'p', 16: 'q', 17: 'r', 18: 's', 19: 't', 20: 'u', 21: 'v', 22: 'w', 23: 'x', 24: 'y', 25: 'z', 26: 'A', 27: 'B', 28: 'C', 29: 'D', 30: 'E', 31: 'F', 32: 'G', 33: 'H', 34: 'I', 35: 'J', 36: 'K', 37: 'L', 38: 'M', 39: 'N', 40: 'O', 41: 'P', 42: 'Q', 43: 'R', 44: 'S', 45: 'T', 46: 'U', 47: 'V', 48: 'W', 49: 'X', 50: 'Y', 51: 'Z'}
>>> merge(d, d_letters)
{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f', 6: 'g', 7: 'h', 8: 'i', 9: 'j', 10: 'k', 11: 'l', 12: 'm', 13: 'n', 14: 'o', 15: 'p', 16: 'q', 17: 'r', 18: 's', 19: 't', 20: 'u', 21: 'v', 22: 'w', 23: 'x', 24: 'y', 25: 'z', 26: 'A', 27: 'B', 28: 'C', 29: 'D', 30: 'E', 31: 'F', 32: 'G', 33: 'H', 34: 'I', 35: 'J', 36: 'K', 37: 'L', 38: 'M', 39: 'N', 40: 'O', 41: 'P', 42: 'Q', 43: 'R', 44: 'S', 45: 'T', 46: 'U', 47: 'V', 48: 'W', 49: 'X', 50: 'Y', 51: 'Z'}
>>> merge(d_letters, d)
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 'f', 6: 'g', 7: 'h', 8: 'i', 9: 'j', 10: 'k', 11: 'l', 12: 'm', 13: 'n', 14: 'o', 15: 'p', 16: 'q', 17: 'r', 18: 's', 19: 't', 20: 'u', 21: 'v', 22: 'w', 23: 'x', 24: 'y', 25: 'z', 26: 'A', 27: 'B', 28: 'C', 29: 'D', 30: 'E', 31: 'F', 32: 'G', 33: 'H', 34: 'I', 35: 'J', 36: 'K', 37: 'L', 38: 'M', 39: 'N', 40: 'O', 41: 'P', 42: 'Q', 43: 'R', 44: 'S', 45: 'T', 46: 'U', 47: 'V', 48: 'W', 49: 'X', 50: 'Y', 51: 'Z'}
>>> merge(d)
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
>>> merge(d_letters)
{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f', 6: 'g', 7: 'h', 8: 'i', 9: 'j', 10: 'k', 11: 'l', 12: 'm', 13: 'n', 14: 'o', 15: 'p', 16: 'q', 17: 'r', 18: 's', 19: 't', 20: 'u', 21: 'v', 22: 'w', 23: 'x', 24: 'y', 25: 'z', 26: 'A', 27: 'B', 28: 'C', 29: 'D', 30: 'E', 31: 'F', 32: 'G', 33: 'H', 34: 'I', 35: 'J', 36: 'K', 37: 'L', 38: 'M', 39: 'N', 40: 'O', 41: 'P', 42: 'Q', 43: 'R', 44: 'S', 45: 'T', 46: 'U', 47: 'V', 48: 'W', 49: 'X', 50: 'Y', 51: 'Z'}
>>> merge()
{}
It works for arbitrary number of dictionary arguments. Were there any duplicate keys in those dictionary, the key from the rightmost dictionary in the argument list wins.
If you want to apply clear value to a specific number of fields, then assign id or class to them and apply empty value to them. like this:
$('.all_fields').val('');
where all_fields
is class applied to desired input fields for applying empty values.
It will protect other fields to be empty, that you don't want to change.
Based on Fedor Kazakov and others answers, I created a default config.
styles.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="Widget.Design.TextInputLayout" parent="AppTheme">
<item name="hintTextAppearance">@style/AppTheme.TextFloatLabelAppearance</item>
<item name="errorTextAppearance">@style/AppTheme.TextErrorAppearance</item>
<item name="counterTextAppearance">@style/TextAppearance.Design.Counter</item>
<item name="counterOverflowTextAppearance">@style/TextAppearance.Design.Counter.Overflow</item>
</style>
<style name="AppTheme.TextFloatLabelAppearance" parent="TextAppearance.Design.Hint">
<!-- Floating label appearance here -->
<item name="android:textColor">@color/colorAccent</item>
<item name="android:textSize">20sp</item>
</style>
<style name="AppTheme.TextErrorAppearance" parent="TextAppearance.Design.Error">
<!-- Error message appearance here -->
<item name="android:textColor">#ff0000</item>
<item name="android:textSize">20sp</item>
</style>
</resources>
activity_layout.xml
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.AppCompatEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Text hint here"
android:text="5,2" />
</android.support.design.widget.TextInputLayout>
Focused:
Without focus:
Error message:
It's trying to connect to the computer it's running on on port 5000, but the connection is being refused. Are you sure you have a server running?
If not, you can use netcat
for testing:
nc -l -k -p 5000
Some implementations may require you to omit the -p
flag.
If you want to use Arrays, it's pretty simple.
logs = gson.fromJson(br, JsonLog[].class); // line 6
Provide the JsonLog
as an array JsonLog[].class
In my mind I have to consider that the foo
folder is a stand-alone library. I might want to consider moving it to the Lib\site-packages
folder within a python installation. I might want to consider adding a foo.pth
file there.
I know it's a library since the ./programs/my_python_program.py
contains the following line:
from foo.tasks import my_function
So it doesn't matter that ./programs
is a sibling folder to ./foo
. It's the fact that my_python_program.py
is run as a script like this:
python ./programs/my_python_program.py
Unfortunately what you'd like to do is not possible. GraphQL requires you to be explicit about specifying which fields you would like returned from your query.
The pattern I see on html5-boilerplate is:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script>
It runs smoothly on different schemes like http
, https
, file
.
You can check directly at the CSS grammar.
Basically1, a name must begin with an underscore (_
), a hyphen (-
), or a letter(a
–z
), followed by any number of hyphens, underscores, letters, or numbers. There is a catch: if the first character is a hyphen, the second character must2 be a letter or underscore, and the name must be at least 2 characters long.
-?[_a-zA-Z]+[_a-zA-Z0-9-]*
In short, the previous rule translates to the following, extracted from the W3C spec.:
In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, or a hyphen followed by a digit. Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code (see next item). For instance, the identifier "B&W?" may be written as "B&W?" or "B\26 W\3F".
Identifiers beginning with a hyphen or underscore are typically reserved for browser-specific extensions, as in -moz-opacity
.
1 It's all made a bit more complicated by the inclusion of escaped unicode characters (that no one really uses).
2 Note that, according to the grammar I linked, a rule starting with TWO hyphens, e.g. --indent1
, is invalid. However, I'm pretty sure I've seen this in practice.
Apply a css-reset to reset all the margins and paddings like this
/* http://meyerweb.com/eric/tools/css/reset/
v2.0 | 20110126 License: none (public domain) */
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
You can use various css-resets as you need, normal and use in css
html
{
margin: 0px;
padding: 0px;
}
body
{
margin: 0px;
padding: 0px;
}
I encountered such a situation where code was circumventing STL's api and writing to the array unsafely when someone resizes it. Adding the assert here caught it:
void Logo::add(const QVector3D &v, const QVector3D &n)
{
GLfloat *p = m_data.data() + m_count;
*p++ = v.x();
*p++ = v.y();
*p++ = v.z();
*p++ = n.x();
*p++ = n.y();
*p++ = n.z();
m_count += 6;
Q_ASSERT( m_count <= m_data.size() );
}