Swift 4 updated :
extension UIView {
var screenShot: UIImage? {
if #available(iOS 10, *) {
let renderer = UIGraphicsImageRenderer(bounds: self.bounds)
return renderer.image { (context) in
self.layer.render(in: context.cgContext)
}
} else {
UIGraphicsBeginImageContextWithOptions(bounds.size, false, 5);
if let _ = UIGraphicsGetCurrentContext() {
drawHierarchy(in: bounds, afterScreenUpdates: true)
let screenshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return screenshot
}
return nil
}
}
}
Yes, you can use this query (Instead of 'Specialist'
and 'Developer'
, type any strings you want separated by comma and change employees
table with your table)
SELECT * FROM employees em
WHERE EXISTS (select 1 from table(sys.dbms_debug_vc2coll('Specialist', 'Developer')) mt where em.job like ('%' || mt.column_value || '%'));
Why my query is better than the accepted answer: You don't need a CREATE TABLE
permission to run it. This can be executed with just SELECT
permissions.
I found myself requiring this functionality often enough that I packaged it into a library called std-pour. It should let you execute a command and view the output in real time. To install simply:
npm install std-pour
Then it's simple enough to execute a command and see the output in realtime:
const { pour } = require('std-pour');
pour('ping', ['8.8.8.8', '-c', '4']).then(code => console.log(`Error Code: ${code}`));
It's promised based so you can chain multiple commands. It's even function signature-compatible with child_process.spawn
so it should be a drop in replacement anywhere you're using it.
I have wrote this function to check both methods using old window.performance.navigation
and new performance.getEntriesByType("navigation")
in same time:
function navigationType(){
var result;
var p;
if (window.performance.navigation) {
result=window.performance.navigation;
if (result==255){result=4} // 4 is my invention!
}
if (window.performance.getEntriesByType("navigation")){
p=window.performance.getEntriesByType("navigation")[0].type;
if (p=='navigate'){result=0}
if (p=='reload'){result=1}
if (p=='back_forward'){result=2}
if (p=='prerender'){result=3} //3 is my invention!
}
return result;
}
Result description:
0: clicking a link, Entering the URL in the browser's address bar, form submission, Clicking bookmark, initializing through a script operation.
1: Clicking the Reload button or using Location.reload()
2: Working with browswer history (Bakc and Forward).
3: prerendering activity like <link rel="prerender" href="//example.com/next-page.html">
4: any other method.
Just to be a bit left handed...
x ? y : x = value
will assign value to y if x is not 0 (false).
I ran into the same problem every time it finds a special character marks it as ??. to solve this, I tried using the encoding: ISO-8859-1
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("txtPath"),"ISO-8859-1"));
while ((line = br.readLine()) != null) {
}
I hope this can help anyone who sees this post.
Just to complement the other answers as I don't think anyone mentioned this here: notifyDataSetChanged()
should be executed on the main thread (other notify<Something>
methods of RecyclerView.Adapter
as well, of course)
From what I gather, since you have the parsing procedures and the call to notifyDataSetChanged()
in the same block, either you're calling it from a worker thread, or you're doing JSON parsing on main thread (which is also a no-no as I'm sure you know). So the proper way would be:
protected void parseResponse(JSONArray response, String url) {
// insert dummy data for demo
// <yadda yadda yadda>
mBusinessAdapter = new BusinessAdapter(mBusinesses);
// or just use recyclerView.post() or [Fragment]getView().post()
// instead, but make sure views haven't been destroyed while you were
// parsing
new Handler(Looper.getMainLooper()).post(new Runnable() {
public void run() {
mBusinessAdapter.notifyDataSetChanged();
}
});
}
PS Weird thing is, I don't think you get any indications about the main thread thing from either IDE or run-time logs. This is just from my personal observations: if I do call notifyDataSetChanged()
from a worker thread, I don't get the obligatory Only the original thread that created a view hierarchy can touch its views message or anything like that - it just fails silently (and in my case one off-main-thread call can even prevent succeeding main-thread calls from functioning properly, probably because of some kind of race condition)
Moreover, neither the RecyclerView.Adapter api reference nor the relevant official dev guide explicitly mention the main thread requirement at the moment (the moment is 2017) and none of the Android Studio lint inspection rules seem to concern this issue either.
But, here is an explanation of this by the author himself
If you want to combine this with *args you have to keep *args and **kwargs at the end of the definition.
So:
def method(foo, bar=None, *args, **kwargs):
do_something_with(foo, bar)
some_other_function(*args, **kwargs)
This worked for me like charm. I went through multiple ways but then this helped me. Make sure you follow each step and name the XML files exactly same.
The process is a little tedious but yes it does work.
I think the complication may also occur when trying to nest multiple Divs within the return statement. You may wish to do this to ensure your components render as block elements.
Here's an example of correctly rendering a couple of components, using multiple divs.
return (
<div>
<h1>Data Information</H1>
<div>
<Button type="primary">Create Data</Button>
</div>
</div>
)
This can be done with a single statement and some XML magic:
select table_name,
to_number(extractvalue(xmltype(dbms_xmlgen.getxml('select count(*) c from '||owner||'.'||table_name)),'/ROWSET/ROW/C')) as count
from all_tables
where owner = 'FOOBAR'
Cinn's answer is great, but there's one thing wrong with it.
The PreferredSize
widget will start immediately at the top of the screen, without accounting for the status bar, so some of its height will be shadowed by the status bar's height. This also accounts for the side notches.
The solution: Wrap the preferredSize
's child with a SafeArea
appBar: PreferredSize(
//Here is the preferred height.
preferredSize: Size.fromHeight(50.0),
child: SafeArea(
child: AppBar(
flexibleSpace: ...
),
),
),
If you don't wanna use the flexibleSpace property, then there's no need for all that, because the other properties of the AppBar
will account for the status bar automatically.
I would write it like this
public static String[] names() {
java.util.LinkedList<String> list = new LinkedList<String>();
for (State s : State.values()) {
list.add(s.name());
}
return list.toArray(new String[list.size()]);
}
ApplicationId must be of type UniqueIdentifier
. Your code works fine if you do:
DECLARE @TTEST TABLE
(
TEST UNIQUEIDENTIFIER
)
DECLARE @UNIQUEX UNIQUEIDENTIFIER
SET @UNIQUEX = NEWID();
INSERT INTO @TTEST
(TEST)
VALUES
(@UNIQUEX);
SELECT * FROM @TTEST
Therefore I would say it is safe to assume that ApplicationId
is not the correct data type.
java 1.6.0_21 or later, or so...
$ java -XX:+PrintFlagsFinal -version 2>&1 | grep MaxHeapSize
uintx MaxHeapSize := 12660904960 {product}
It looks like the min(1G) has been removed.
Or on Windows using findstr
C:\>java -XX:+PrintFlagsFinal -version 2>&1 | findstr MaxHeapSize
Here is how you can retrieve only directories with GLOB:
$directories = glob($somePath . '/*' , GLOB_ONLYDIR);
The problem in my case was missing component declaration in the module, but even after adding the declaration the error persisted. I had stop the server and rebuild the entire project in VS Code for the error to go away.
BluetoothAdapter.getDefaultAdapter().isEnabled
->
returns true when bluetooth is open
val audioManager = this.getSystemService(Context.AUDIO_SERVICE) as
AudioManager
audioManager.isBluetoothScoOn
->
returns true when device connected
This is how I would go about it.
$posts = $this->post->orderBy('id', 'DESC')->get();
In my case, I had installed it in the virtualenv but forgot to activate the virtualenv while running the command
python3 manage.py makemigrations
So in my case I had to just activate the environment and then run the command
source [virtualenv folder-name]/bin/activate
python3 manage.py makemigrations
This solved my problem.
another tip...where to add "content-type: application/json"...to the textbox field on the Composer/Parsed tab. There are 3 lines already filled in there, so I added this Content-type as the 4th line. That made the Post work.
Yes, you can modify local variables from inside lambdas (in the way shown by the other answers), but you should not do it. Lambdas have been made for functional style of programming and this means: No side effects. What you want to do is considered bad style. It is also dangerous in case of parallel streams.
You should either find a solution without side effects or use a traditional for loop.
In interface Builder set table view separator "None"
and those separator lines which are shown after the last cell can be remove by following approach. Best approach is to assign Empty View to tableView FooterView in viewDidLoad
self.tableView.tableFooterView = UIView()
To save and load an arraylist of public static ArrayList data = new ArrayList ();
I used (to write)...
static void saveDatabase() {
try {
FileOutputStream fos = new FileOutputStream("mydb.fil");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(data);
oos.close();
databaseIsSaved = true;
}
catch (IOException e) {
e.printStackTrace();
}
} // End of saveDatabase
And used (to read) ...
static void loadDatabase() {
try {
FileInputStream fis = new FileInputStream("mydb.fil");
ObjectInputStream ois = new ObjectInputStream(fis);
data = (ArrayList<User>)ois.readObject();
ois.close();
}
catch (IOException e) {
System.out.println("***catch ERROR***");
e.printStackTrace();
}
catch (ClassNotFoundException e) {
System.out.println("***catch ERROR***");
e.printStackTrace();
}
} // End of loadDatabase
Nuget.exe is placed at .nuget
folder of your project. It can't be executed directly in Package Manager Console, but is executed by Powershell commands because these commands build custom path for themselves.
My steps to solve are:
C:\Program Files\NuGet\Visual Studio 2012
(or your VS version);C:\Program Files\NuGet\Visual Studio 2012
(or your VS version) in PATH environment variable Update
NuGet can be easily installed in your project using the following command:
Install-Package NuGet.CommandLine
Read up on Cancellation (which was introduced in .NET 4.0 and is largely unchanged since then) and the Task-Based Asynchronous Pattern, which provides guidelines on how to use CancellationToken
with async
methods.
To summarize, you pass a CancellationToken
into each method that supports cancellation, and that method must check it periodically.
private async Task TryTask()
{
CancellationTokenSource source = new CancellationTokenSource();
source.CancelAfter(TimeSpan.FromSeconds(1));
Task<int> task = Task.Run(() => slowFunc(1, 2, source.Token), source.Token);
// (A canceled task will raise an exception when awaited).
await task;
}
private int slowFunc(int a, int b, CancellationToken cancellationToken)
{
string someString = string.Empty;
for (int i = 0; i < 200000; i++)
{
someString += "a";
if (i % 1000 == 0)
cancellationToken.ThrowIfCancellationRequested();
}
return a + b;
}
A variable cannot be both null
and undefined
at the same time. However, the direct answer to your question is:
if (variable != null)
One =
, not two.
There are two special clauses in the "abstract equality comparison algorithm" in the JavaScript spec devoted to the case of one operand being null
and the other being undefined
, and the result is true
for ==
and false
for !=
. Thus if the value of the variable is undefined
, it's not != null
, and if it's not null, it's obviously not != null
.
Now, the case of an identifier not being defined at all, either as a var
or let
, as a function parameter, or as a property of the global context is different. A reference to such an identifier is treated as an error at runtime. You could attempt a reference and catch the error:
var isDefined = false;
try {
(variable);
isDefined = true;
}
catch (x) {}
I would personally consider that a questionable practice however. For global symbols that may or may be there based on the presence or absence of some other library, or some similar situation, you can test for a window
property (in browser JavaScript):
var isJqueryAvailable = window.jQuery != null;
or
var isJqueryAvailable = "jQuery" in window;
File->Settings->compiler->check - Compile independent modules in parallel(may require larger heap size)
gradle.properties
org.gradle.jvmargs=-Xmx768m
add this end of the file.
it works for me.
if Not, uncheck - Compile independent modules in parallel, and set org.gradle.jvmargs=Xmx768m like above
We were getting an error related to this after a recent release of code to one of our development environments. We have an application that is a child of another application. This relationship has been working fine for YEARS until yesterday.
The problem:
We were getting a yellow stack trace error due to duplicate keys being entered. This is because both the web.config for the child and parent applications had this key. But this existed for many years like this without change. Why all of sudden its an issue now?
The solution:
The reason this was never a problem is because the keys AND values were always the same. Yesterday we updated our SQL connection strings to include the Application Name in the connection string. This made the string unique and all of sudden started to fail.
Without doing any research on the exact reason for this, I have to assume that when the child application inherits the parents web.config values, it ignores identical key/value pairs.
We were able to solve it by wrapping the connection string like this
<location path="." inheritInChildApplications="false">
<connectionStrings>
<!-- Updated connection strings go here -->
</connectionStrings>
</location>
Edit: I forgot to mention that I added this in the PARENTS web.config. I didn't have to modify the child's web.config.
Thanks for everyones help on this, saved our butts.
Setting a * in the version number in AssemblyInfo or under project properties as described in the other posts does not work with all versions of Visual Studio / .NET.
Afaik it did not work in VS 2005 (but in VS 2003 and VS 2008). For VS 2005 you could use the following: Auto Increment Visual Studio 2005 version build and revision number on compile time.
But be aware that changing the version number automatically is not recommended for strong-named assemblies. The reason is that all references to such an assembly must be updated each time the referenced assembly is rebuilt due to the fact that strong-named assembly references are always a reference to a specific assembly version. Microsoft themselves change the version number of the .NET Framework assemblies only if there are changes in interfaces. (NB: I'm still searching for the link in MSDN where I read that.)
dear friend, Jon Skeet said you can find character Decimal codebut it is not character Hex code as it should mention in unicode, so you should represent character codes via HexCode not in Deciaml.
there is an open source tool at http://unicode.codeplex.com that provides complete information about a characer or a sentece.
so it is better to create a parser that give a char as a parameter and return ahexCode as string
public static String GetHexCode(char character)
{
return String.format("{0:X4}", GetDecimal(character));
}//end
hope it help
The PictureBox.SizeMode options are missing a "fill" or "cover" mode which would be like zoom except with cropping to ensure you're filling the picture box. In CSS it's the "cover" option.
This code should enable that:
static public void fillPictureBox(PictureBox pbox, Bitmap bmp)
{
pbox.SizeMode = PictureBoxSizeMode.Normal;
bool source_is_wider = (float)bmp.Width / bmp.Height > (float)pbox.Width / pbox.Height;
var resized = new Bitmap(pbox.Width, pbox.Height);
var g = Graphics.FromImage(resized);
var dest_rect = new Rectangle(0, 0, pbox.Width, pbox.Height);
Rectangle src_rect;
if (source_is_wider)
{
float size_ratio = (float)pbox.Height / bmp.Height;
int sample_width = (int)(pbox.Width / size_ratio);
src_rect = new Rectangle((bmp.Width - sample_width) / 2, 0, sample_width, bmp.Height);
}
else
{
float size_ratio = (float)pbox.Width / bmp.Width;
int sample_height = (int)(pbox.Height / size_ratio);
src_rect = new Rectangle(0, (bmp.Height - sample_height) / 2, bmp.Width, sample_height);
}
g.DrawImage(bmp, dest_rect, src_rect, GraphicsUnit.Pixel);
g.Dispose();
pbox.Image = resized;
}
If you send a PHP array into a function that expects a string like: echo
or print
, then the PHP interpreter will convert your array to the literal string Array
, throw this Notice and keep going. For example:
php> print(array(1,2,3))
PHP Notice: Array to string conversion in
/usr/local/lib/python2.7/dist-packages/phpsh/phpsh.php(591) :
eval()'d code on line 1
Array
In this case, the function print
dumps the literal string: Array
to stdout and then logs the Notice to stderr and keeps going.
Another example in a PHP script:
<?php
$stuff = array(1,2,3);
print $stuff; //PHP Notice: Array to string conversion in yourfile on line 3
?>
$stuff = array(1,2,3);
foreach ($stuff as $value) {
echo $value, "\n";
}
Prints:
1
2
3
Or along with array keys
$stuff = array('name' => 'Joe', 'email' => '[email protected]');
foreach ($stuff as $key => $value) {
echo "$key: $value\n";
}
Prints:
name: Joe
email: [email protected]
Note that array elements could be arrays as well. In this case either use foreach
again or access this inner array elements using array syntax, e.g. $row['name']
In case it's just a plain 1-demensional array, you can simply join all the cells into a string using a delimiter:
<?php
$stuff = array(1,2,3);
print implode(", ", $stuff); //prints 1, 2, 3
print join(',', $stuff); //prints 1,2,3
In case your array has a complex structure but you need to convert it to a string anyway, then use http://php.net/json_encode
$stuff = array('name' => 'Joe', 'email' => '[email protected]');
print json_encode($stuff);
Prints
{"name":"Joe","email":"[email protected]"}
If you want just to inspect the array contents for the debugging purpose, use one of the following functions. Keep in mind that var_dump is most informative of them and thus usually being preferred for the purpose
examples
$stuff = array(1,2,3);
print_r($stuff);
$stuff = array(3,4,5);
var_dump($stuff);
Prints:
Array
(
[0] => 1
[1] => 2
[2] => 3
)
array(3) {
[0]=>
int(3)
[1]=>
int(4)
[2]=>
int(5)
}
Check your internet settings, firewalls and such may be blocking it, I know when I was working on it in college they were blocking the port number but I've never had any trouble on my home machines
Note, you can use {{.}}
to render the current context item.
{{#avatar}}{{.}}{{/avatar}}
{{^avatar}}missing{{/avatar}}
For building containers you obviously want to use one of the standard containers (such as a std::vector). But this is a perfect example of the things you need to consider when your object contains RAW pointers.
If your object has a RAW pointer then you need to remember the rule of 3 (now the rule of 5 in C++11).
This is because if not defined the compiler will generate its own version of these methods (see below). The compiler generated versions are not always useful when dealing with RAW pointers.
The copy constructor is the hard one to get correct (it's non trivial if you want to provide the strong exception guarantee). The Assignment operator can be defined in terms of the Copy Constructor as you can use the copy and swap idiom internally.
See below for full details on the absolute minimum for a class containing a pointer to an array of integers.
Knowing that it is non trivial to get it correct you should consider using std::vector rather than a pointer to an array of integers. The vector is easy to use (and expand) and covers all the problems associated with exceptions. Compare the following class with the definition of A below.
class A
{
std::vector<int> mArray;
public:
A(){}
A(size_t s) :mArray(s) {}
};
Looking at your problem:
A* arrayOfAs = new A[5];
for (int i = 0; i < 5; ++i)
{
// As you surmised the problem is on this line.
arrayOfAs[i] = A(3);
// What is happening:
// 1) A(3) Build your A object (fine)
// 2) A::operator=(A const&) is called to assign the value
// onto the result of the array access. Because you did
// not define this operator the compiler generated one is
// used.
}
The compiler generated assignment operator is fine for nearly all situations, but when RAW pointers are in play you need to pay attention. In your case it is causing a problem because of the shallow copy problem. You have ended up with two objects that contain pointers to the same piece of memory. When the A(3) goes out of scope at the end of the loop it calls delete [] on its pointer. Thus the other object (in the array) now contains a pointer to memory that has been returned to the system.
The compiler generated copy constructor; copies each member variable by using that members copy constructor. For pointers this just means the pointer value is copied from the source object to the destination object (hence shallow copy).
The compiler generated assignment operator; copies each member variable by using that members assignment operator. For pointers this just means the pointer value is copied from the source object to the destination object (hence shallow copy).
So the minimum for a class that contains a pointer:
class A
{
size_t mSize;
int* mArray;
public:
// Simple constructor/destructor are obvious.
A(size_t s = 0) {mSize=s;mArray = new int[mSize];}
~A() {delete [] mArray;}
// Copy constructor needs more work
A(A const& copy)
{
mSize = copy.mSize;
mArray = new int[copy.mSize];
// Don't need to worry about copying integers.
// But if the object has a copy constructor then
// it would also need to worry about throws from the copy constructor.
std::copy(©.mArray[0],©.mArray[c.mSize],mArray);
}
// Define assignment operator in terms of the copy constructor
// Modified: There is a slight twist to the copy swap idiom, that you can
// Remove the manual copy made by passing the rhs by value thus
// providing an implicit copy generated by the compiler.
A& operator=(A rhs) // Pass by value (thus generating a copy)
{
rhs.swap(*this); // Now swap data with the copy.
// The rhs parameter will delete the array when it
// goes out of scope at the end of the function
return *this;
}
void swap(A& s) noexcept
{
using std::swap;
swap(this.mArray,s.mArray);
swap(this.mSize ,s.mSize);
}
// C++11
A(A&& src) noexcept
: mSize(0)
, mArray(NULL)
{
src.swap(*this);
}
A& operator=(A&& src) noexcept
{
src.swap(*this); // You are moving the state of the src object
// into this one. The state of the src object
// after the move must be valid but indeterminate.
//
// The easiest way to do this is to swap the states
// of the two objects.
//
// Note: Doing any operation on src after a move
// is risky (apart from destroy) until you put it
// into a specific state. Your object should have
// appropriate methods for this.
//
// Example: Assignment (operator = should work).
// std::vector() has clear() which sets
// a specific state without needing to
// know the current state.
return *this;
}
}
You can calculate the checksum of a file by reading the binary data and using hashlib.md5().hexdigest()
. A function to do this would look like the following:
def File_Checksum_Dis(dirname):
if not os.path.exists(dirname):
print(dirname+" directory is not existing");
for fname in os.listdir(dirname):
if not fname.endswith('~'):
fnaav = os.path.join(dirname, fname);
fd = open(fnaav, 'rb');
data = fd.read();
fd.close();
print("-"*70);
print("File Name is: ",fname);
print(hashlib.md5(data).hexdigest())
print("-"*70);
The same way you make anything else negative: put a negative sign in front of it.
var positive = 6;
var negative = -positive;
In order to sort a list of tuples (<word>, <count>)
, for count
in descending order and word
in alphabetical order:
data = [
('betty', 1),
('bought', 1),
('a', 1),
('bit', 1),
('of', 1),
('butter', 2),
('but', 1),
('the', 1),
('was', 1),
('bitter', 1)]
I use this method:
sorted(data, key=lambda tup:(-tup[1], tup[0]))
and it gives me the result:
[('butter', 2),
('a', 1),
('betty', 1),
('bit', 1),
('bitter', 1),
('bought', 1),
('but', 1),
('of', 1),
('the', 1),
('was', 1)]
To enable production mode in angular 6.X.X Just go to environment file
Like this path
Your path: project>\src\environments\environment.ts
Change production: false
from :
export const environment = {
production: false
};
To
export const environment = {
production: true
};
String methodName= "...";
String[] args = {};
Method[] methods = clazz.getMethods();
for (Method m : methods) {
if (methodName.equals(m.getName())) {
// for static methods we can use null as instance of class
m.invoke(null, new Object[] {args});
break;
}
}
it has been solved with me in windows os by setting the JAVA_HOME variable before running as follows:
set JAVA_HOME=C:\Program Files\Java\jdk1.8.0_111
the easiest way to do this is to wrap your sockets in ObjectInput/OutputStreams and send serialized java objects. you can create classes which contain the relevant data, and then you don't need to worry about the nitty gritty details of handling binary protocols. just make sure that you flush your object streams after you write each object "message".
You should use List
or array
instead
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
Or
int[] arr = new int[10];
arr[0]=1;
arr[1]=2;
Or even better
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("n1", 1);
map.put("n2", 2);
//conditionally get
map.get("n1");
The curl installed by default in Debian supports HTTPS since a great while back. (a long time ago there were two separate packages, one with and one without SSL but that's not the case anymore)
You can send an OPTIONS request with curl like this:
curl -i -X OPTIONS http://example.org/path
You may also use -v
instead of -i
to see more output.
To send a plain * (instead of the path, see RFC 7231) with the OPTIONS method, you need curl 7.55.0 or later as then you can run a command line like:
curl -i --request-target "*" -X OPTIONS http://example.org
Press "F4" on windows which will open up "Project Structure" and then click "+" icon or "Alt + Insert" to select a new project to be imported; then click OK button...
For Windows Vista/7/8/10, you can create a symlink instead via mklink
.
Process.Start("cmd.exe", $"/c mklink {linkName} {applicationPath}");
Alternatively, call CreateSymbolicLink
via P/Invoke.
To find the point where to add the -lm in Eclipse-IDE is really horrible, so it took me some time.
If someone else also uses Edlipse, here's the way how to add the command:
Project -> Properties -> C/C++ Build -> Settings -> GCC C Linker -> Miscelleaneous -> Linker flags: in this field add the command -lm
There is this android library called Sherlock. It gives you the full report of crash along with device and application information. Whenever a crash occurs, it displays a notification in the notification bar and on clicking of the notification, it opens the crash details. You can also share crash details with others via email or other sharing options.
Installation
android {
dataBinding {
enabled = true
}
}
compile('com.github.ajitsing:sherlock:1.0.0@aar') {
transitive = true
}
Demo
You can use SHOW
:
SHOW max_connections;
This returns the currently effective setting. Be aware that it can differ from the setting in postgresql.conf
as there are a multiple ways to set run-time parameters in PostgreSQL. To reset the "original" setting from postgresql.conf
in your current session:
RESET max_connections;
However, not applicable to this particular setting. The manual:
This parameter can only be set at server start.
To see all settings:
SHOW ALL;
There is also pg_settings
:
The view
pg_settings
provides access to run-time parameters of the server. It is essentially an alternative interface to theSHOW
andSET
commands. It also provides access to some facts about each parameter that are not directly available fromSHOW
, such as minimum and maximum values.
For your original request:
SELECT *
FROM pg_settings
WHERE name = 'max_connections';
Finally, there is current_setting()
, which can be nested in DML statements:
SELECT current_setting('max_connections');
Related:
Looks to be more efficient to add the recognizer directly to the cell as shown here:
Tap&Hold for TableView Cells, Then and Now
(scroll to the example at the bottom)
This is overly complicated, Jackson handles lists via its writer methods just as well as it handles regular objects. This should work just fine for you, assuming I have not misunderstood your question:
public void writeListToJsonArray() throws IOException {
final List<Event> list = new ArrayList<Event>(2);
list.add(new Event("a1","a2"));
list.add(new Event("b1","b2"));
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(out, list);
final byte[] data = out.toByteArray();
System.out.println(new String(data));
}
namespace TestApplication // Remove .Controller
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
}
Remove the controller word from namepsace
Follow these simple steps :
1: In the Rmarkdown script run Knit(Ctrl+Shift+K) 2: Then after the html markdown is opened click Open in Browser(top left side) and the html is opened in your web browser 3: Then use Ctrl+P and save as PDF .
I recently hit the same issue on Safari. The solution I figured out is based on the Local Storage HTML5 API. Using Local Storage you could emulate cookies.
Here's my blog post with details: http://log.scalemotion.com/2012/10/how-to-trick-safari-and-set-3rd-party.html
That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:
DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=[THE_UNDEFINED_COLUMN_OR_PARAMETER_NAME], DRIVER=4.8.87
Double check your table definition. Maybe you just missed adding something.
I also tried google-ing this problem and saw this:
http://www.coderanch.com/t/515475/JDBC/databases/sql-insert-statement-giving-sqlcode
A refinement of Vadim Zin4uk's answer is just to use the existing GsonHttpMessageConverter class but invoke the setSupportedMediaTypes() setter.
For spring boot apps, this results into adding to following to your configuration classes:
@Bean
public GsonHttpMessageConverter gsonHttpMessageConverter(Gson gson) {
GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
converter.setGson(gson);
List<MediaType> supportedMediaTypes = converter.getSupportedMediaTypes();
if (! supportedMediaTypes.contains(TEXT_PLAIN)) {
supportedMediaTypes = new ArrayList<>(supportedMediaTypes);
supportedMediaTypes.add(TEXT_PLAIN);
converter.setSupportedMediaTypes(supportedMediaTypes);
}
return converter;
}
Here I have a solution that avoid multiple requests, for loops and old document removal.
You can easily create a new idea manually using something like:_id:ObjectId()
But knowing Mongo will automatically assign an _id if missing, you can use aggregate to create a $project
containing all the fields of your document, but omit the field _id. You can then save it with $out
So if your document is:
{
"_id":ObjectId("5b5ed345cfbce6787588e480"),
"title": "foo",
"description": "bar"
}
Then your query will be:
db.getCollection('myCollection').aggregate([
{$match:
{_id: ObjectId("5b5ed345cfbce6787588e480")}
}
{$project:
{
title: '$title',
description: '$description'
}
},
{$out: 'myCollection'}
])
I had more than 100 files like
log-12
log-123
log-34
....
above answers did not work for me
but the following command helped me.
find . -name "log-*" -exec rm -rf {} \;
i gave -type
as .
so it deletes both files and folders which starts with log-
and rm -rf
deletes folders recursively even it has files.
if you want folders alone
find -type d -name "log-*" -exec rm -rf {} \;
files alone
find -type f -name "log-*" -exec rm -rf {} \;
Just enable the "Build Active Architecture Only" option
in PROJECT >> Build Settings >> Build Active Architecture Only >> Yes
remember to check if they are also enabled in each target
A simple forEach
loop solves this quite well:
let text = 'the red apple and the green ball';
const toStrip = ['red', 'green'];
toStrip.forEach(x => {
text = text.replace(x, '');
});
console.log(text);
// logs -> the apple and the ball
As of TypeScript 2.0 you can include typings for native promises by including the following in your tsconfig.json
"compilerOptions": {
"lib": ["es5", "es2015.promise"]
}
This will include the promise declarations that comes with TypeScript without having to set the target to ES6.
"Select your text, right click, then choose
Style Token
and then using 1st style (2nd style, etc …). At the moment is not possible to save the style tokens but there is an idea pending on Idea torrent you may vote for if your are interested in that."
It should be default, but it might be hidden.
"It might be that something happened to your
contextMenu.xml
so that you only get the basic standard. Have a look in NPPs config folder (%appdata%\Notepad++\
) if thecontextMenu.xml
is there. If no: that would be the answer; if yes: it might be defect. Anyway you can grab the original standart contextMenu.xml from here and place it into the config folder (or replace the existing xml). Start NPP and you should have quite a long context menu. Tip: have a look at thecontextmenu.xml
itself - because you're allowed to change it to your own needs."
See this for more information
Simply use the PhoneNumberFormattingTextWatcher, just call:
editText.addTextChangedListener(new PhoneNumberFormattingTextWatcher());
Addition
To be clear, PhoneNumberFormattingTextWatcher's backbone is the PhoneNumberUtils class. The difference is the TextWatcher maintains the EditText while you must call PhoneNumberUtils.formatNumber()
every time you change its contents.
I had the same issue twice, but in the second time I realized it wasn't a problem on Tomcat at all.. Try to delete the cache of your browser, refresh the page and see if the new version of the page on your server is being shown up. It worked with me.
I think this is the most comprehensive answer on the PostgreSQL wiki itself: https://wiki.postgresql.org/wiki/BinaryFilesInDB
Read the part with the title 'What is the best way to store the files in the Database?'
Your code doesn't seem so ugly to me...
however, an alternative (not much better) could be e.g. :
df <- data.frame(table(yn))
colnames(df) <- c('Smoker','Freq')
df$Perc <- df$Freq / sum(df$Freq) * 100
------------------
Smoker Freq Perc
1 No 19 47.5
2 Yes 21 52.5
In DJango 3.0 the default value of a BooleanField in model.py is set like this:
class model_name(models.Model):
example_name = models.BooleanField(default=False)
I'd just like to point out something in these answers. In a date/time format string, '/' will be replaced with whatever the user's date separator is, and ':' will be replaced with whatever the user's time separator is. That is, if I've defined my date separator to be '.' (in the Regional and Language Options control panel applet, "intl.cpl"), and my time separator to be '?' (just pretend I'm crazy like that), then
DateTime.Now.ToString("MM/dd/yyyy h:mm tt")
would return
01.05.2009 6?01 PM
In most cases, this is what you want, because you want to respect the user's settings. If, however, you require the format be something specific (say, if it's going to parsed back out by somebody else down the wire), then you need to escape these special characters:
DateTime.Now.ToString("MM\\/dd\\/yyyy h\\:mm tt")
or
DateTime.Now.ToString(@"MM\/dd\/yyyy h\:mm tt")
which would now return
01/05/2009 6:01 PM
EDIT:
Then again, if you really want to respect the user's settings, you should use one of the standard date/time format strings, so that you respect not only the user's choices of separators, but also the general format of the date and/or time.
DateTime.Now.ToShortDateString()
DateTime.Now.ToString("d")
Both would return "1/5/2009" using standard US options, or "05/01/2009" using standard UK options, for instance.
DateTime.Now.ToLongDateString()
DateTime.Now.ToString("D")
Both would return "Monday, January 05, 2009" in US locale, or "05 January 2009" in UK.
DateTime.Now.ToShortTimeString()
DateTime.Now.ToString("t");
"6:01 PM" in US, "18:01" in UK.
DateTime.Now.ToLongTimeString()
DateTime.Now.ToString("T");
"6:01:04 PM" in US, "18:01:04" in UK.
DateTime.Now.ToString()
DateTime.Now.ToString("G");
"1/5/2009 6:01:04 PM" in US, "05/01/2009 18:01:04" in UK.
Many other options are available. See docs for standard date and time format strings and custom date and time format strings.
the whole if
should be enclosed in brackets and the or
operator is ||
an not !!
, so
if ((Type == 2 && PageCount == 0) || (Type == 2 && PageCount == '')) { ...
First, understand that you have three languages working together:
PHP: It only runs by the server and responds to requests like clicking on a link (GET) or submitting a form (POST).
HTML & JavaScript: It only runs in someone's browser (excluding NodeJS).
I'm assuming your file looks something like:
<!DOCTYPE HTML>
<html>
<?php
function runMyFunction() {
echo 'I just ran a php function';
}
if (isset($_GET['hello'])) {
runMyFunction();
}
?>
Hello there!
<a href='index.php?hello=true'>Run PHP Function</a>
</html>
Because PHP only responds to requests (GET, POST, PUT, PATCH, and DELETE via $_REQUEST), this is how you have to run a PHP function even though they're in the same file. This gives you a level of security, "Should I run this script for this user or not?".
If you don't want to refresh the page, you can make a request to PHP without refreshing via a method called Asynchronous JavaScript and XML (AJAX).
That is something you can look up on YouTube though. Just search "jquery ajax"
I recommend Laravel to anyone new to start off right: http://laravel.com/
What could be easier than something like this:
import tempfile
for i in range(400):
with tempfile.TemporaryFile() as tf:
for j in range(1000):
tf.write('Line {} of file {}'.format(j,i))
That creates 400 temp files and writes 1000 lines to each temp file. It executes in less than 1/2 second on my unremarkable machine. Each temp file of the total is created and deleted as the context manager opens and closes in this case. It is fast, secure, and cross platform.
Using tempfile is a lot better than trying to reinvent it.
So I got indigo, and then : Go to Help->Install New Software Click on Add: Name: "Indigo" Location: "http://download.eclipse.org/releases/indigo" Try to install Android Development Tools (as you will see, only 1 option out of 4 will appear - this is normal for Indigo)
public void ChargingArraySelect()
{
int loop = 0;
int registros = 0;
OdbcConnection conn = WebApiConfig.conn();
OdbcCommand query = conn.CreateCommand();
query.CommandText = "select dataA, DataB, dataC, DataD FROM table where dataA = 'xpto'";
try
{
conn.Open();
OdbcDataReader dr = query.ExecuteReader();
//take the number the registers, to use into next step
registros = dr.RecordsAffected;
//calls an array to be populated
Global.arrayTest = new string[registros, 4];
while (dr.Read())
{
if (loop < registros)
{
Global.arrayTest[i, 0] = Convert.ToString(dr["dataA"]);
Global.arrayTest[i, 1] = Convert.ToString(dr["dataB"]);
Global.arrayTest[i, 2] = Convert.ToString(dr["dataC"]);
Global.arrayTest[i, 3] = Convert.ToString(dr["dataD"]);
}
loop++;
}
}
}
//Declaration the Globais Array in Global Classs
private static string[] uso_internoArray1;
public static string[] arrayTest
{
get { return uso_internoArray1; }
set { uso_internoArray1 = value; }
}
And if you need to calculate the MD5 to see whether it matches the MD5 of an Azure blob, then this SO question and answer might be helpful: MD5 hash of blob uploaded on Azure doesnt match with same file on local machine
So, 10 years later this is still a thing :)
I've tried every answer on this page (ATOW)
and also some ILGenerator powered solutions (FastMember and Fast.Reflection).
But a compiled Lambda Expression seems to be the fastest.
At least for my use cases (on .Net Core 2.2).
This is what I am using for now:
public static class EnumerableExtensions {
internal static Func<TClass, object> CompileGetter<TClass>(string propertyName) {
var param = Expression.Parameter(typeof(TClass));
var body = Expression.Convert(Expression.Property(param, propertyName), typeof(object));
return Expression.Lambda<Func<TClass, object>>(body,param).Compile();
}
public static DataTable ToDataTable<T>(this IEnumerable<T> collection) {
var dataTable = new DataTable();
var properties = typeof(T)
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => p.CanRead)
.ToArray();
if (properties.Length < 1) return null;
var getters = new Func<T, object>[properties.Length];
for (var i = 0; i < properties.Length; i++) {
var columnType = Nullable.GetUnderlyingType(properties[i].PropertyType) ?? properties[i].PropertyType;
dataTable.Columns.Add(properties[i].Name, columnType);
getters[i] = CompileGetter<T>(properties[i].Name);
}
foreach (var row in collection) {
var dtRow = new object[properties.Length];
for (var i = 0; i < properties.Length; i++) {
dtRow[i] = getters[i].Invoke(row) ?? DBNull.Value;
}
dataTable.Rows.Add(dtRow);
}
return dataTable;
}
}
Only works with properties (not fields) but it works on Anonymous Types.
May be below approach will be helpful for someone TS with reactjs
interface Event {
name: string;
dateCreated: string;
type: string;
}
interface UserEvent<T> extends Event<T> {
UserId: string;
}
According to this helpful list of operators [an operator can be thought of as a mathematical expression] found here, you can tell the batch compiler that you are manipulating variables instead of fixed numbers by using the += operator instead of the + operator.
Hope I Helped!
Does this work?
Workbooks.Open Filename:=filepath, ReadOnly:=True
Or, as pointed out in a comment, to keep a reference to the opened workbook:
Dim book As Workbook
Set book = Workbooks.Open(Filename:=filepath, ReadOnly:=True)
VisualVm does not come with Apple JDK. You can use VisualVM Mac Application bundle(dmg) as a separate application, to compensate for that.
this also works:
$url = "http://www.some-url";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$xmlresponse = curl_exec($ch);
$xml=simplexml_load_string($xmlresponse);
then I just run a forloop to grab the stuff from the nodes.
like this:`
for($i = 0; $i < 20; $i++) {
$title = $xml->channel->item[$i]->title;
$link = $xml->channel->item[$i]->link;
$desc = $xml->channel->item[$i]->description;
$html .="<div><h3>$title</h3>$link<br />$desc</div><hr>";
}
echo $html;
***note that your node names will differ, obviously..and your HTML might be structured differently...also your loop might be set to higher or lower amount of results.
I am sure that you have found a solution somewhere over the past 2 years but the following is a solution that works for your requested site
package javasandbox;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
*
* @author Ryan.Oglesby
*/
public class JavaSandbox {
private static String sURL;
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws MalformedURLException, IOException {
sURL = "http://www.cumhuriyet.com.tr/?hn=298710";
System.out.println(sURL);
URL url = new URL(sURL);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
//set http request headers
httpCon.addRequestProperty("Host", "www.cumhuriyet.com.tr");
httpCon.addRequestProperty("Connection", "keep-alive");
httpCon.addRequestProperty("Cache-Control", "max-age=0");
httpCon.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
httpCon.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36");
httpCon.addRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
httpCon.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
//httpCon.addRequestProperty("Cookie", "JSESSIONID=EC0F373FCC023CD3B8B9C1E2E2F7606C; lang=tr; __utma=169322547.1217782332.1386173665.1386173665.1386173665.1; __utmb=169322547.1.10.1386173665; __utmc=169322547; __utmz=169322547.1386173665.1.1.utmcsr=stackoverflow.com|utmccn=(referral)|utmcmd=referral|utmcct=/questions/8616781/how-to-get-a-web-pages-source-code-from-java; __gads=ID=3ab4e50d8713e391:T=1386173664:S=ALNI_Mb8N_wW0xS_wRa68vhR0gTRl8MwFA; scrElm=body");
HttpURLConnection.setFollowRedirects(false);
httpCon.setInstanceFollowRedirects(false);
httpCon.setDoOutput(true);
httpCon.setUseCaches(true);
httpCon.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(httpCon.getInputStream(), "UTF-8"));
String inputLine;
StringBuilder a = new StringBuilder();
while ((inputLine = in.readLine()) != null)
a.append(inputLine);
in.close();
System.out.println(a.toString());
httpCon.disconnect();
}
}
You can do it like this:
$firstday = date_create()->modify('first day January 2010');
Not sure what kind of text box you are refering to. However, I'm not sure if you can do this in a text box on a user form.
A text box on a sheet you can though.
Sheets("Sheet1").Shapes("TextBox 1").TextFrame2.TextRange.Text = "R2=" & variable
Sheets("Sheet1").Shapes("TextBox 1").TextFrame2.TextRange.Characters(2, 1).Font.Superscript = msoTrue
And same thing for an excel cell
Sheets("Sheet1").Range("A1").Characters(2, 1).Font.Superscript = True
If this isn't what you're after you will need to provide more information in your question.
EDIT: posted this after the comment sorry
Creating index.php, index.html, index.htm is not secure. Becuse, anyone can get access on your files within specified directory by guessing files name. E.g.: http://yoursite.com/includes/file.dat So, recommended method is creating a .htaccess file to deny all visitors ;). Have fun !!
You can't send email using javascript or html. You need server side scripts in php or other technologies to send email.
Reinitialise the view controller
YourViewController *vc = [[YourViewController alloc] initWithNibName:@"YourViewControllerIpad" bundle:nil];
[self.navigationController vc animated:NO];
Check this blog by Martin Thoma. I tested the below code on MacOS Mojave and it worked as specified.
> def get_browser():
> """Get the browser (a "driver")."""
> # find the path with 'which chromedriver'
> path_to_chromedriver = ('/home/moose/GitHub/algorithms/scraping/'
> 'venv/bin/chromedriver')
> download_dir = "/home/moose/selenium-download/"
> print("Is directory: {}".format(os.path.isdir(download_dir)))
>
> from selenium.webdriver.chrome.options import Options
> chrome_options = Options()
> chrome_options.add_experimental_option('prefs', {
> "plugins.plugins_list": [{"enabled": False,
> "name": "Chrome PDF Viewer"}],
> "download": {
> "prompt_for_download": False,
> "default_directory": download_dir
> }
> })
>
> browser = webdriver.Chrome(path_to_chromedriver,
> chrome_options=chrome_options)
> return browser
You can switch(this) inside method definitions of enum classes. Made me shout "whut!" loudly when I discovered that this actually works.
You can specify android:screenOrientation="portrait"
for each activity in your manifest.xml file. You cannot specify this option on the application
tag.
Other option is to do it programmatically, for example in an Activity
base class:
@Override
public void onCreate(Bundle savedInstanceState) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
Last option is to do it with activity lifecycle listeners which is only available since Android 4.0 (API 14+). Everything happens in a custom Application
class:
@Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(new ActivityLifecycleAdapter() {
@Override
public void onActivityCreated(Activity a, Bundle savedInstanceState) {
a.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
});
}
ActivityLifecycleAdapter
is just a helper class you'll need to create which will be an empty implementation of ActivityLifecycleCallbacks
(so you don't have to override each and every methods of that interface when you simply need one of them).
Echoing text that contains line breaks is fine, and there's no limit on the amount of text or lines you can echo at once (save for available memory).
The error in your code is caused by the unescaped single quotes which appear in the string.
See this line:
$('input_6').hint('ex: [email protected]');
You'd need to escape those single quotes in a PHP string whether it's a single line or not.
There is another good way to echo large strings, though, and that's to close the PHP block and open it again later:
if (is_single()) {
?>
<link type="text/css" rel="stylesheet" href="http://jotform.com/css/styles/form.css"/><style type="text/css">
.form-label{
width:150px !important;
}
.form-label-left{
width:150px !important;
}
.form-line{
padding:10px;
}
.form-label-right{
width:150px !important;
}
body, html{
margin:0;
padding:0;
background:false;
}
.form-all{
margin:0px auto;
padding-top:20px;
width:650px !important;
color:Black;
font-family:Verdana;
font-size:12px;
}
</style>
<link href="http://jotform.com/css/calendarview.css" rel="stylesheet" type="text/css" />
<script src="http://jotform.com/js/prototype.js" type="text/javascript"></script>
<script src="http://jotform.com/js/protoplus.js" type="text/javascript"></script>
<script src="http://jotform.com/js/protoplus-ui.js" type="text/javascript"></script>
<script src="http://jotform.com/js/jotform.js?v3" type="text/javascript"></script>
<script src="http://jotform.com/js/location.js" type="text/javascript"></script>
<script src="http://jotform.com/js/calendarview.js" type="text/javascript"></script>
<script type="text/javascript">
JotForm.init(function(){
$('input_6').hint('ex: [email protected]');
});
</script>
<?php
}else {
}
Or another alternative, which is probably better for readability, is to put all that static HTML into another page and include() it.
No. When your input type is submit, you should have an onsubmit
event declared in the markup and then do the changes you want. Meaning, have an onsubmit
defined in your form tag.
Otherwise change the input type to a button and then define an onclick
event for that button.
You will find much information about JavaDoc at the Documentation Comment Specification for the Standard Doclet, including the information on the
tag (that you are looking for). The corresponding example from the documentation is as follows
For example, here is a comment that refers to the getComponentAt(int, int) method:
Use the {@link #getComponentAt(int, int) getComponentAt} method.
The package.class
part can be ommited if the referred method is in the current class.
Other useful links about JavaDoc are:
Easiest way is to use +strVal or Number(strVal)
Examples:
let strVal1 = "123.5"
let strVal2 = "One"
let val1a = +strVal1
let val1b = Number(strVal1)
let val1c = parseFloat(strVal1)
let val1d = parseInt(strVal1)
let val1e = +strVal1 - parseInt(strVal1)
let val2a = +strVal2
console.log("val1a->", val1a) // 123.5
console.log("val1b->", val1b) // 123.5
console.log("val1c->", val1c) // 123.5
console.log("val1d->", val1d) // 123
console.log("val1e->", val1e) // 0.5
console.log("val2a->", val2a) // NaN
for some reason my error kept pointing to the "proxy" property in the config file. Which was misleading. During my troubleshooting I was trying different values for the proxy and https-proxy properties, but would only get the error stating to make sure the proxy config was set properly, and pointing to an older value.
Using, NPM CONFIG LS -L command lists all the properties and values in the config file. I was then able to see the value in question was matching the https-proxy, therefore using the https-proxy. So I changed the proxy (my company uses different ones) and then it worked. figured I would add this, as with these subtle confusing errors, every perspective on it helps.
Check this code:
Javascript:
app.config( ["$routeProvider"], function($routeProvider){
$routeProvider.when("/part1", {"templateUrl" : "part1"});
$routeProvider.when("/part2", {"templateUrl" : "part2"});
$routeProvider.otherwise({"redirectTo":"/part1"});
}]
);
function HomeFragmentController($scope) {
$scope.$on("$routeChangeSuccess", function (scope, next, current) {
$scope.transitionState = "active"
});
}
CSS:
.fragmentWrapper {
overflow: hidden;
}
.fragment {
position: relative;
-moz-transition-property: left;
-o-transition-property: left;
-webkit-transition-property: left;
transition-property: left;
-moz-transition-duration: 0.1s;
-o-transition-duration: 0.1s;
-webkit-transition-duration: 0.1s;
transition-duration: 0.1s
}
.fragment:not(.active) {
left: 540px;
}
.fragment.active {
left: 0px;
}
Main page HTML:
<div class="fragmentWrapper" data-ng-view data-ng-controller="HomeFragmentController">
</div>
Partials HTML example:
<div id="part1" class="fragment {{transitionState}}">
</div>
For future reference to anyone here having difficulty, if you are adding the checkboxes dynamically, the correct accepted answer above will not work. You'll need to leverage event delegation which allows a parent node to capture bubbled events from a specific descendant and issue a callback.
// $(<parent>).on('<event>', '<child>', callback);
$(document).on('change', '.checkbox', function() {
if(this.checked) {
// checkbox is checked
}
});
Note that it's almost always unnecessary to use document
for the parent selector. Instead choose a more specific parent node to prevent propagating the event up too many levels.
The example below displays how the events of dynamically added dom nodes do not trigger previously defined listeners.
$postList = $('#post-list');_x000D_
_x000D_
$postList.find('h1').on('click', onH1Clicked);_x000D_
_x000D_
function onH1Clicked() {_x000D_
alert($(this).text());_x000D_
}_x000D_
_x000D_
// simulate added content_x000D_
var title = 2;_x000D_
_x000D_
function generateRandomArticle(title) {_x000D_
$postList.append('<article class="post"><h1>Title ' + title + '</h1></article>');_x000D_
}_x000D_
_x000D_
setTimeout(generateRandomArticle.bind(null, ++title), 1000);_x000D_
setTimeout(generateRandomArticle.bind(null, ++title), 5000);_x000D_
setTimeout(generateRandomArticle.bind(null, ++title), 10000);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<section id="post-list" class="list post-list">_x000D_
<article class="post">_x000D_
<h1>Title 1</h1>_x000D_
</article>_x000D_
<article class="post">_x000D_
<h1>Title 2</h1>_x000D_
</article>_x000D_
</section>
_x000D_
While this example displays the usage of event delegation to capture events for a specific node (h1
in this case), and issue a callback for such events.
$postList = $('#post-list');_x000D_
_x000D_
$postList.on('click', 'h1', onH1Clicked);_x000D_
_x000D_
function onH1Clicked() {_x000D_
alert($(this).text());_x000D_
}_x000D_
_x000D_
// simulate added content_x000D_
var title = 2;_x000D_
_x000D_
function generateRandomArticle(title) {_x000D_
$postList.append('<article class="post"><h1>Title ' + title + '</h1></article>');_x000D_
}_x000D_
_x000D_
setTimeout(generateRandomArticle.bind(null, ++title), 1000); setTimeout(generateRandomArticle.bind(null, ++title), 5000); setTimeout(generateRandomArticle.bind(null, ++title), 10000);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<section id="post-list" class="list post-list">_x000D_
<article class="post">_x000D_
<h1>Title 1</h1>_x000D_
</article>_x000D_
<article class="post">_x000D_
<h1>Title 2</h1>_x000D_
</article>_x000D_
</section>
_x000D_
6 years late to the party but I've been searching for how to extract an html element's tag attribute value, so for:
<span property="addressLocality">Ayr</span>
I want "addressLocality". I kept being directed back here, but the answers didn't really solve my problem.
How I managed to do it eventually:
>>> from bs4 import BeautifulSoup as bs
>>> soup = bs('<span property="addressLocality">Ayr</span>', 'html.parser')
>>> my_attributes = soup.find().attrs
>>> my_attributes
{u'property': u'addressLocality'}
As it's a dict, you can then also use keys
and 'values'
>>> my_attributes.keys()
[u'property']
>>> my_attributes.values()
[u'addressLocality']
Hopefully it helps someone else!
For the legend, you can use this
plt.setp(g._legend.get_title(), fontsize=20)
Where g is your facetgrid object returned after you call the function making it.
jsonweb seems to be the best solution for me. See http://www.jsonweb.info/en/latest/
from jsonweb.encode import to_object, dumper
@to_object()
class DataModel(object):
def __init__(self, id, value):
self.id = id
self.value = value
>>> data = DataModel(5, "foo")
>>> dumper(data)
'{"__type__": "DataModel", "id": 5, "value": "foo"}'
It's unclear how you want to handle fractional years, but perhaps like this:
DateTime now = DateTime.Now;
DateTime origin = new DateTime(2007, 11, 3);
int calendar_years = now.Year - origin.Year;
int whole_years = calendar_years - ((now.AddYears(-calendar_years) >= origin)? 0: 1);
int another_method = calendar_years - ((now.Month - origin.Month) * 32 >= origin.Day - now.Day)? 0: 1);
ASP.NET 2 and SQL Server reporting services 2005 have a limit of 2028. I found this out the hard way, where my dynamic URL generator would not pass over some parameters to a report beyond that point. This was under Internet Explorer 8.
Try this:
function addClass(element, value) {
if(!element.className) {
element.className = value;
} else {
newClassName = element.className;
newClassName+= " ";
newClassName+= value;
element.className = newClassName;
}
}
Similar logic could be used to make a removeClass function.
I realize you mentioned SQL browsing, but everything else in your question makes me want to suggest you also consider DB4O, which is a great, simple object DB.
Here's the LLVM header.
// -*- C++ -*-
//===--------------------------- __nullptr --------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#ifndef _LIBCPP_NULLPTR
#define _LIBCPP_NULLPTR
#include <__config>
#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
#pragma GCC system_header
#endif
#ifdef _LIBCPP_HAS_NO_NULLPTR
_LIBCPP_BEGIN_NAMESPACE_STD
struct _LIBCPP_TEMPLATE_VIS nullptr_t
{
void* __lx;
struct __nat {int __for_bool_;};
_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR nullptr_t() : __lx(0) {}
_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR nullptr_t(int __nat::*) : __lx(0) {}
_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR operator int __nat::*() const {return 0;}
template <class _Tp>
_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
operator _Tp* () const {return 0;}
template <class _Tp, class _Up>
_LIBCPP_INLINE_VISIBILITY
operator _Tp _Up::* () const {return 0;}
friend _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR bool operator==(nullptr_t, nullptr_t) {return true;}
friend _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR bool operator!=(nullptr_t, nullptr_t) {return false;}
};
inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR nullptr_t __get_nullptr_t() {return nullptr_t(0);}
#define nullptr _VSTD::__get_nullptr_t()
_LIBCPP_END_NAMESPACE_STD
#else // _LIBCPP_HAS_NO_NULLPTR
namespace std
{
typedef decltype(nullptr) nullptr_t;
}
#endif // _LIBCPP_HAS_NO_NULLPTR
#endif // _LIBCPP_NULLPTR
(a great deal can be uncovered with a quick grep -r /usr/include/*`
)
One thing that jumps out is the operator *
overload (returning 0 is a lot friendlier than segfaulting...).
Another thing is it doesn't look compatible with storing an address at all. Which, compared to how it goes slinging void*'s and passing NULL results to normal pointers as sentinel values, would obviously reduce the "never forget, it might be a bomb" factor.
Unfortunately, you can't change the font size or styling in a drop-down list that is created using data validation.
You can style the text in a combo box, however. Follow the instructions here: Excel Data Validation Combo Box
@Droidman post is pretty comprehensive. Volley works good with small data of few kbytes. When I tried to use the 'BasicImageDownloader.java' the Android Studio gave me warning that the AsyncTask class should to be static or there could be leaks. I used Volley in another test app and that kept crashing because of leaks so I am worried about using Volley for the image downloader (images can be few 100 kB).
I used Picasso and it worked well, there is small change (probably an update on Picasso) from what is posted above. Below code worked for me:
public static void imageDownload(Context ctx, String url){
Picasso.get().load(yourURL)
.into(getTarget(url));
}
private static Target getTarget(final String url){
Target target2 = new Target() {
@Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
new Thread(new Runnable() {
@Override
public void run() {
File file = new File(localPath + "/"+"YourImageFile.jpg");
try {
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, ostream);
ostream.flush();
ostream.close();
} catch (IOException e) {
Log.e("IOException", e.getLocalizedMessage());
}
}
}).start();
}
@Override
public void onBitmapFailed(Exception e, Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
return target;
}
Deduping is rarely simple. That's because the records to be dedupped often have slightly different values is some of the fields. Therefore choose which record to keep can be problematic. Further, dups are often people records and it is hard to identify if the two John Smith's are two people or one person who is duplicated. So spend a lot (50% or more of the whole project) of your time defining what constitutes a dup and how to handle the differences and child records.
How do you know which is the correct value? Further dedupping requires that you handle all child records not orphaning any. What happens when you find that by changing the id on the child record you are suddenly violating one of the unique indexes or constraints - this will happen eventually and your process needs to handle it. If you have chosen foolishly to apply all your constraints only thorough the application, you may not even know the constraints are violated. When you have 10,000 records to dedup, you aren't going to go through the application to dedup one at a time. If the constraint isn't in the database, lots of luck in maintaining data integrity when you dedup.
A further complication is that dups don't always match exactly on the name or address. For instance a salesrep named Joan Martin may be a dup of a sales rep names Joan Martin-Jones especially if they have the same address and email. OR you could have John or Johnny in the name. Or the same street address except one record abbreveiated ST. and one spelled out Street. In SQL server you can use SSIS and fuzzy grouping to also identify near matches. These are often the most common dups as the fact that weren't exact matches is why they got put in as dups in the first place.
For some types of dedupping, you may need a user interface, so that the person doing the dedupping can choose which of two values to use for a particular field. This is especially true if the person who is being dedupped is in two or more roles. It could be that the data for a particular role is usually better than the data for another role. Or it could be that only the users will know for sure which is the correct value or they may need to contact people to find out if they are genuinely dups or simply two people with the same name.
If you are getting this error, it could be because you don't have a route defined for your get.
For example:
const express = require('express');
const app = express();
app.get('/people', function (req, res) {
res.send('hello');
})
app.listen(3000);
http://http://localhost:3000/people --> this works
http://http://localhost:3000 --> this will output Cannot GET / message.
I don't think that solution would work anyways because you will see some error message in your error log file.
The solution was a lot easier than what I thought.
simply, open the following path to your php5-fpm
sudo nano /etc/php5/fpm/pool.d/www.conf
or if you're the admin 'root'
nano /etc/php5/fpm/pool.d/www.conf
Then find this line and uncomment it:
listen.allowed_clients = 127.0.0.1
This solution will make you be able to use listen = 127.0.0.1:9000 in your vhost blocks
like this: fastcgi_pass 127.0.0.1:9000;
after you make the modifications, all you need is to restart or reload both Nginx and Php5-fpm
Php5-fpm
sudo service php5-fpm restart
or
sudo service php5-fpm reload
Nginx
sudo service nginx restart
or
sudo service nginx reload
From the comments:
Also comment
;listen = /var/run/php5-fpm.sock
and add
listen = 9000
Starting with Android Studio 2.0 you can do it with the new emulator:
Just click 3 "Take Screenshot". Standard location is the desktop.
Or
UPDATE 22/07/2020
If you keep the emulator in Android Studio as possible since Android Studio 4.1 click here to save the screenshot in your standard location:
I know I'm coming to this very late. However, for anyone who's searching, I thought I'd publish what FINALLY worked for me. I'm not claiming it's the best solution - only that it worked.
Our WebApi service uses the config.EnableCors(corsAttribute) method. However, even with that, it would still fail on the pre-flight requests. @Mihai-Andrei Dinculescu's answer provided the clue for me. First of all, I added his Application_BeginRequest() code to flush the options requests. That STILL didn't work for me. The issue is that WebAPI still wasn't adding any of the expected headers to the OPTIONS request. Flushing it alone didn't work - but it gave me an idea. I added the custom headers that would otherwise be added via the web.config to the response for the OPTIONS request. Here's my code:
protected void Application_BeginRequest()
{
if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
{
Response.Headers.Add("Access-Control-Allow-Origin", "https://localhost:44343");
Response.Headers.Add("Access-Control-Allow-Headers",
"Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
Response.Headers.Add("Access-Control-Allow-Credentials", "true");
Response.Flush();
}
}
Obviously, this only applies to the OPTIONS requests. All other verbs are handled by the CORS configuration. If there's a better approach to this, I'm all ears. It feels like a cheat to me and I would prefer if the headers were added automatically, but this is what finally worked and allowed me to move on.
For now no jquery or php needed. Use just "required" HTML5 input attrbute like here
<form>
<p>
<input class="form-control" type="text" name="email" />
<input type="submit" value="ok" class="btn btn-success" name="submit" />
<input type="hidden" name="action" value="0" />
</p>
<p><input type="checkbox" required name="terms">I have read and accept <a href="#">SOMETHING Terms and Conditions</a></p>
</form>
This will validate and prevent any submit before checkbox is opt in. Language independent solution because its generated by users web browser.
A bit involved. Easiest would be to refer to this SQL Fiddle I created for you that produces the exact result. There are ways you can improve it for performance or other considerations, but this should hopefully at least be clearer than some alternatives.
The gist is, you get a canonical ranking of your data first, then use that to segment the data into groups, then find an end date for each group, then eliminate any intermediate rows. ROW_NUMBER() and CROSS APPLY help a lot in doing it readably.
EDIT 2019:
The SQL Fiddle does in fact seem to be broken, for some reason, but it appears to be a problem on the SQL Fiddle site. Here's a complete version, tested just now on SQL Server 2016:
CREATE TABLE Source
(
EmployeeID int,
DateStarted date,
DepartmentID int
)
INSERT INTO Source
VALUES
(10001,'2013-01-01',001),
(10001,'2013-09-09',001),
(10001,'2013-12-01',002),
(10001,'2014-05-01',002),
(10001,'2014-10-01',001),
(10001,'2014-12-01',001)
SELECT *,
ROW_NUMBER() OVER (PARTITION BY EmployeeID ORDER BY DateStarted) AS EntryRank,
newid() as GroupKey,
CAST(NULL AS date) AS EndDate
INTO #RankedData
FROM Source
;
UPDATE #RankedData
SET GroupKey = beginDate.GroupKey
FROM #RankedData sup
CROSS APPLY
(
SELECT TOP 1 GroupKey
FROM #RankedData sub
WHERE sub.EmployeeID = sup.EmployeeID AND
sub.DepartmentID = sup.DepartmentID AND
NOT EXISTS
(
SELECT *
FROM #RankedData bot
WHERE bot.EmployeeID = sup.EmployeeID AND
bot.EntryRank BETWEEN sub.EntryRank AND sup.EntryRank AND
bot.DepartmentID <> sup.DepartmentID
)
ORDER BY DateStarted ASC
) beginDate (GroupKey);
UPDATE #RankedData
SET EndDate = nextGroup.DateStarted
FROM #RankedData sup
CROSS APPLY
(
SELECT TOP 1 DateStarted
FROM #RankedData sub
WHERE sub.EmployeeID = sup.EmployeeID AND
sub.DepartmentID <> sup.DepartmentID AND
sub.EntryRank > sup.EntryRank
ORDER BY EntryRank ASC
) nextGroup (DateStarted);
SELECT * FROM
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY GroupKey ORDER BY EntryRank ASC) AS GroupRank FROM #RankedData
) FinalRanking
WHERE GroupRank = 1
ORDER BY EntryRank;
DROP TABLE #RankedData
DROP TABLE Source
For a class diagram using Oracle database, use the following steps:
File ? Data Modeler ? Import ? Data Dictionary ? select DB connection ? Next ? select database->select tabels -> Finish
The data value may not be changed. Note: The variable value may be changed, but the original immutable data value was discarded and a new data value was created in memory.
You don't want to stretch the span in height?
You have the possiblity to affect one or more flex-items to don't stretch the full height of the container.
To affect all flex-items of the container, choose this:
You have to set align-items: flex-start;
to div
and all flex-items of this container get the height of their content.
div {_x000D_
align-items: flex-start;_x000D_
background: tan;_x000D_
display: flex;_x000D_
height: 200px;_x000D_
}_x000D_
span {_x000D_
background: red;_x000D_
}
_x000D_
<div>_x000D_
<span>This is some text.</span>_x000D_
</div>
_x000D_
To affect only a single flex-item, choose this:
If you want to unstretch a single flex-item on the container, you have to set align-self: flex-start;
to this flex-item. All other flex-items of the container aren't affected.
div {_x000D_
display: flex;_x000D_
height: 200px;_x000D_
background: tan;_x000D_
}_x000D_
span.only {_x000D_
background: red;_x000D_
align-self:flex-start;_x000D_
}_x000D_
span {_x000D_
background:green;_x000D_
}
_x000D_
<div>_x000D_
<span class="only">This is some text.</span>_x000D_
<span>This is more text.</span>_x000D_
</div>
_x000D_
Why is this happening to the span
?
The default value of the property align-items
is stretch
. This is the reason why the span
fill the height of the div
.
Difference between baseline
and flex-start
?
If you have some text on the flex-items, with different font-sizes, you can use the baseline of the first line to place the flex-item vertically. A flex-item with a smaller font-size have some space between the container and itself at top. With flex-start
the flex-item will be set to the top of the container (without space).
div {_x000D_
align-items: baseline;_x000D_
background: tan;_x000D_
display: flex;_x000D_
height: 200px;_x000D_
}_x000D_
span {_x000D_
background: red;_x000D_
}_x000D_
span.fontsize {_x000D_
font-size:2em;_x000D_
}
_x000D_
<div>_x000D_
<span class="fontsize">This is some text.</span>_x000D_
<span>This is more text.</span>_x000D_
</div>
_x000D_
You can find more information about the difference between
baseline
andflex-start
here:
What's the difference between flex-start and baseline?
My opinion is, Instead of storing images directly to the database, It is recommended to store the image location in the database. As we compare both options, Storing images in the database is safe for security purpose. Disadvantage are
If database is corrupted, no way to retrieve.
Retrieving image files from db is slow when compare to other option.
On the other hand, storing image file location in db will have following advantages.
It is easy to retrieve.
If more than one images are stored, we can easily retrieve image information.
To truly force maven to only use your local repo, you can run with mvn <goals> -o
. The -o
tells maven to let you work "offline", and it will stay off the network.
The default limit for the length of the request line is 8192 bytes = 8* 1024. It you want to change the limit, you have to add or update in your tomcat server.xml the attribut maxHttpHeaderSize.
as:
<Connector port="8080" maxHttpHeaderSize="65536" protocol="HTTP/1.1" ... />
In this example I set the limite to 65536 bytes= 64*1024.
Hope this will help.
How about something simple like this?
return ((object[])value).Cast<byte>().ToArray();
.NET 5 will be a unified version of all .NET variants coming in November 2020, so there will be no need to choose between variants anymore.
While the existing answers have given solutions to solve the issue and the second half of the question, they do not provide an answer to the self discovery aspect of the first half of the question that is in bold:
"How can I see which variable causes memory overhead...?"
It may not have been as robust 3 years ago, but the Chrome Developer Tools "Profiles" section is now quite powerful and feature rich. The Chrome team has an insightful article on using it and thus also how garbage collection (GC) works in javascript, which is at the core of this question.
Since delete
is basically the root of the currently accepted answer by Yochai Akoka, it's important to remember what delete does. It's irrelevant if not combined with the concepts of how GC works in the next two answers: if there's an existing reference to an object it's not cleaned up. The answers are more correct, but probably not as appreciated because they require more thought than just writing 'delete'. Yes, one possible solution may be to use delete
, but it won't matter if there's another reference to the memory leak.
Another answer appropriately mentions circular references and the Chrome team documentation can provide much more clarity as well as the tools to verify the cause.
Since delete
was mentioned here, it also may be useful to provide the resource Understanding Delete. Although it does not get into any of the actual solution which is really related to javascript's garbage collector.
one way
awk '/^\*\*/{gsub("*","");printf "\n"$0" ";next}{printf $0" "}' to-plot.xls
Visibility Scopes with Abstract Examples :: Makes easy Understanding
This visibility of a property or method is defined by pre-fixing declaration of one of three keyword (Public, protected and private)
Public : If a property or method is defined as public, it means it can be both access and manipulated by anything that can refer to object.
Protected : when a property or method visibility is set to protected members can only be access within the class itself and by inherited & inheriting classes. (Inherited:- a class can have all the properties and methods of another class).
Private : When a property or method visibility is set to private, only the class that has the private members can access those methods and properties(Internally within the class), despite of whatever class relation there maybe.
Your outer loop is looping over all the words in the list. It's unnecessary and will cause you problems. Remove it and it should work properly.
The second question is easier to answer: you basically can use PyPy as a drop-in replacement if all your code is pure Python. However, many widely used libraries (including some of the standard library) are written in C and compiled as Python extensions. Some of these can be made to work with PyPy, some can't. PyPy provides the same "forward-facing" tool as Python --- that is, it is Python --- but its innards are different, so tools that interface with those innards won't work.
As for the first question, I imagine it is sort of a Catch-22 with the first: PyPy has been evolving rapidly in an effort to improve speed and enhance interoperability with other code. This has made it more experimental than official.
I think it's possible that if PyPy gets into a stable state, it may start getting more widely used. I also think it would be great for Python to move away from its C underpinnings. But it won't happen for a while. PyPy hasn't yet reached the critical mass where it is almost useful enough on its own to do everything you'd want, which would motivate people to fill in the gaps.
Think like this:
class Animal { /* Some virtual members */ };
class Dog: public Animal {};
class Cat: public Animal {};
Dog dog;
Cat cat;
Animal& AnimalRef1 = dog; // Notice no cast required. (Dogs and cats are animals).
Animal& AnimalRef2 = cat;
Animal* AnimalPtr1 = &dog;
Animal* AnimlaPtr2 = &cat;
Cat& catRef1 = dynamic_cast<Cat&>(AnimalRef1); // Throws an exception AnimalRef1 is a dog
Cat* catPtr1 = dynamic_cast<Cat*>(AnimalPtr1); // Returns NULL AnimalPtr1 is a dog
Cat& catRef2 = dynamic_cast<Cat&>(AnimalRef2); // Works
Cat* catPtr2 = dynamic_cast<Cat*>(AnimalPtr2); // Works
// This on the other hand makes no sense
// An animal object is not a cat. Therefore it can not be treated like a Cat.
Animal a;
Cat& catRef1 = dynamic_cast<Cat&>(a); // Throws an exception Its not a CAT
Cat* catPtr1 = dynamic_cast<Cat*>(&a); // Returns NULL Its not a CAT.
Now looking back at your first statement:
Animal animal = cat; // This works. But it slices the cat part out and just
// assigns the animal part of the object.
Cat bigCat = animal; // Makes no sense.
// An animal is not a cat!!!!!
Dog bigDog = bigCat; // A cat is not a dog !!!!
You should very rarely ever need to use dynamic cast.
This is why we have virtual methods:
void makeNoise(Animal& animal)
{
animal.DoNoiseMake();
}
Dog dog;
Cat cat;
Duck duck;
Chicken chicken;
makeNoise(dog);
makeNoise(cat);
makeNoise(duck);
makeNoise(chicken);
The only reason I can think of is if you stored your object in a base class container:
std::vector<Animal*> barnYard;
barnYard.push_back(&dog);
barnYard.push_back(&cat);
barnYard.push_back(&duck);
barnYard.push_back(&chicken);
Dog* dog = dynamic_cast<Dog*>(barnYard[1]); // Note: NULL as this was the cat.
But if you need to cast particular objects back to Dogs then there is a fundamental problem in your design. You should be accessing properties via the virtual methods.
barnYard[1]->DoNoiseMake();
If you need to make single element you can use this construction:
$('<option/>', {
'class': this.dataID,
'text': this.s_dataValue
}).appendTo('.subCategory');
But if you need to print many elements you can use this construction:
function printOptions(arr){
jQuery.each(arr, function(){
$('<option/>', {
'value': this.dataID,
'text': this.s_dataValue
}).appendTo('.subCategory');
});
}
var dictionary = {
"data":[{"id":"0","name":"ABC"}, {"id":"1","name":"DEF"}],
"images": [ {"id":"0","name":"PQR"},"id":"1","name":"xyz"}]
};
for (var key in dictionary) {
var getKey = dictionary[key];
getKey.forEach(function(item) {
console.log(item.name + ' ' + item.id);
});
}
In previous posts I have read that this feature IS available on VS 2015 community if you FIRST install SQL Server express (free) and THEN install VS. I have tried it and it worked. I just had to reinstall Windows and am going thru the same procedure now and it did not work... so will try again :). I know it worked 6 months ago when I tried.
-Ed
According to the git-stash manpage, "A stash is represented as a commit whose tree records the state of the working directory, and its first parent is the commit at HEAD
when the stash was created," and git stash show -p
gives us "the changes recorded in the stash as a diff between the stashed state and its original parent.
To keep your other changes intact, use git stash show -p | patch --reverse
as in the following:
$ git init
Initialized empty Git repository in /tmp/repo/.git/
$ echo Hello, world >messages
$ git add messages
$ git commit -am 'Initial commit'
[master (root-commit)]: created 1ff2478: "Initial commit"
1 files changed, 1 insertions(+), 0 deletions(-)
create mode 100644 messages
$ echo Hello again >>messages
$ git stash
$ git status
# On branch master
nothing to commit (working directory clean)
$ git stash apply
# On branch master
# Changed but not updated:
# (use "git add <file>..." to update what will be committed)
# (use "git checkout -- <file>..." to discard changes in working directory)
#
# modified: messages
#
no changes added to commit (use "git add" and/or "git commit -a")
$ echo Howdy all >>messages
$ git diff
diff --git a/messages b/messages
index a5c1966..eade523 100644
--- a/messages
+++ b/messages
@@ -1 +1,3 @@
Hello, world
+Hello again
+Howdy all
$ git stash show -p | patch --reverse
patching file messages
Hunk #1 succeeded at 1 with fuzz 1.
$ git diff
diff --git a/messages b/messages
index a5c1966..364fc91 100644
--- a/messages
+++ b/messages
@@ -1 +1,2 @@
Hello, world
+Howdy all
Edit:
A light improvement to this is to use git apply
in place of patch:
git stash show -p | git apply --reverse
Alternatively, you can also use git apply -R
as a shorthand to git apply --reverse
.
I've been finding this really handy lately...
Thanks to all for your help - I was off this issue for a couple of days and just came back to it - was able to cobble this together - not the most elegant code, but it works for my purposes - thought I'd share if anyone else encounters this issue:
public class Statistics
{
public Trendline CalculateLinearRegression(int[] values)
{
var yAxisValues = new List<int>();
var xAxisValues = new List<int>();
for (int i = 0; i < values.Length; i++)
{
yAxisValues.Add(values[i]);
xAxisValues.Add(i + 1);
}
return new Trendline(yAxisValues, xAxisValues);
}
}
public class Trendline
{
private readonly IList<int> xAxisValues;
private readonly IList<int> yAxisValues;
private int count;
private int xAxisValuesSum;
private int xxSum;
private int xySum;
private int yAxisValuesSum;
public Trendline(IList<int> yAxisValues, IList<int> xAxisValues)
{
this.yAxisValues = yAxisValues;
this.xAxisValues = xAxisValues;
this.Initialize();
}
public int Slope { get; private set; }
public int Intercept { get; private set; }
public int Start { get; private set; }
public int End { get; private set; }
private void Initialize()
{
this.count = this.yAxisValues.Count;
this.yAxisValuesSum = this.yAxisValues.Sum();
this.xAxisValuesSum = this.xAxisValues.Sum();
this.xxSum = 0;
this.xySum = 0;
for (int i = 0; i < this.count; i++)
{
this.xySum += (this.xAxisValues[i]*this.yAxisValues[i]);
this.xxSum += (this.xAxisValues[i]*this.xAxisValues[i]);
}
this.Slope = this.CalculateSlope();
this.Intercept = this.CalculateIntercept();
this.Start = this.CalculateStart();
this.End = this.CalculateEnd();
}
private int CalculateSlope()
{
try
{
return ((this.count*this.xySum) - (this.xAxisValuesSum*this.yAxisValuesSum))/((this.count*this.xxSum) - (this.xAxisValuesSum*this.xAxisValuesSum));
}
catch (DivideByZeroException)
{
return 0;
}
}
private int CalculateIntercept()
{
return (this.yAxisValuesSum - (this.Slope*this.xAxisValuesSum))/this.count;
}
private int CalculateStart()
{
return (this.Slope*this.xAxisValues.First()) + this.Intercept;
}
private int CalculateEnd()
{
return (this.Slope*this.xAxisValues.Last()) + this.Intercept;
}
}
This is a little C program that illustrates how you could use color codes:
#include <stdio.h>
#define KNRM "\x1B[0m"
#define KRED "\x1B[31m"
#define KGRN "\x1B[32m"
#define KYEL "\x1B[33m"
#define KBLU "\x1B[34m"
#define KMAG "\x1B[35m"
#define KCYN "\x1B[36m"
#define KWHT "\x1B[37m"
int main()
{
printf("%sred\n", KRED);
printf("%sgreen\n", KGRN);
printf("%syellow\n", KYEL);
printf("%sblue\n", KBLU);
printf("%smagenta\n", KMAG);
printf("%scyan\n", KCYN);
printf("%swhite\n", KWHT);
printf("%snormal\n", KNRM);
return 0;
}
Answer by Rick and MadX is the right way to do the steps (Thumbs Up for the answer)
In my case I am using Akcess USB Type C Data Sync Cable For Nexus 5x, 5P - White As Nexus 5x do not supply type C to usb cable I purchased it from some vendor.
Having the same issue. What I am doing stupidly is:- I am connecting the cable in wrong way. After I reconnect it from upside down its working for me.
I might think that some of the Cables do not support debuggable. But its in my case.
This(Image) is my case the Type C should be as USB side symbol. A stupid solution, but work for me
If you're comfortable with numba it allows to create a fast short-circuit (stops as soon as a NaN is found) function:
import numba as nb
import math
@nb.njit
def anynan(array):
array = array.ravel()
for i in range(array.size):
if math.isnan(array[i]):
return True
return False
If there is no NaN
the function might actually be slower than np.min
, I think that's because np.min
uses multiprocessing for large arrays:
import numpy as np
array = np.random.random(2000000)
%timeit anynan(array) # 100 loops, best of 3: 2.21 ms per loop
%timeit np.isnan(array.sum()) # 100 loops, best of 3: 4.45 ms per loop
%timeit np.isnan(array.min()) # 1000 loops, best of 3: 1.64 ms per loop
But in case there is a NaN in the array, especially if it's position is at low indices, then it's much faster:
array = np.random.random(2000000)
array[100] = np.nan
%timeit anynan(array) # 1000000 loops, best of 3: 1.93 µs per loop
%timeit np.isnan(array.sum()) # 100 loops, best of 3: 4.57 ms per loop
%timeit np.isnan(array.min()) # 1000 loops, best of 3: 1.65 ms per loop
Similar results may be achieved with Cython or a C extension, these are a bit more complicated (or easily avaiable as bottleneck.anynan
) but ultimatly do the same as my anynan
function.
you can edit all the columns at once by using this simple code via Foreach loop
foreach (DataGridViewColumn item in datagridview1.Columns)
{
item.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
}
Locate the installation path of GlassFish. Then move to domains/domain-dir/logs/
and you'll find there the log files. If you have created the domain with NetBeans, the domain-dir is most probably called domain1
.
See this link for the official GlassFish documentation about logging.
Here is the answer.
System.exit(0);// normal termination - Successful - zero
System.exit(-1);//Exit with some Error
System.exit(1);//one or any positive integer // exit with some Information message
As of 8.12
, cloning using HTTPS
+ runner token is not supported anymore, as mentioned here:
In 8.12 we improved build permissions. Being able to clone project using runners token it is no supported from now on (it was actually working by coincidence and was never a fully fledged feature, so we changed that in 8.12). You should use build token instead.
This is widely documented here - https://docs.gitlab.com/ce/user/project/new_ci_build_permissions_model.html.
.container{
height:100px;
width:500px;
border:2px dotted #F00;
border-left:none;
border-right:none;
text-align:center;
}
.container div{
display: inline-block;
border-left: 2px dotted #ccc;
vertical-align: middle;
line-height: 100px;
}
.column-left{ float: left; width: 32%; height:100px;}
.column-right{ float: right; width: 32%; height:100px; border-right: 2px dotted #ccc;}
.column-center{ display: inline-block; width: 33%; height:100px;}
<div class="container">
<div class="column-left">Column left</div>
<div class="column-center">Column center</div>
<div class="column-right">Column right</div>
</div>
See this link http://jsfiddle.net/bipin_kumar/XD8RW/2/
You can also join if the number of columns are not same in both tables and can map static value to table column
from t1 in Table1
join t2 in Table2
on new {X = t1.Column1, Y = 0 } on new {X = t2.Column1, Y = t2.Column2 }
select new {t1, t2}
<button type="button" onclick="loadXMLDoc()"> GET CONTENT</button>
<script>
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
var url = "<Enter URL>";``
xmlhttp.onload = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == "200") {
document.getElementById("demo").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
</script>
The negation operator in Python is not
. Therefore just replace your !
with not
.
For your example, do this:
if not os.path.exists("/usr/share/sounds/blues") :
proc = subprocess.Popen(["mkdir", "/usr/share/sounds/blues"])
proc.wait()
For your specific example (as Neil said in the comments), you don't have to use the subprocess
module, you can simply use os.mkdir()
to get the result you need, with added exception handling goodness.
Example:
blues_sounds_path = "/usr/share/sounds/blues"
if not os.path.exists(blues_sounds_path):
try:
os.mkdir(blues_sounds_path)
except OSError:
# Handle the case where the directory could not be created.
import java.util.Date;
...
Date d1 = new Date();
...
...
Date d2 = new Date();
System.out.println(d2.getTime()-d1.getTime()); //gives the time difference in milliseconds.
System.out.println((d2.getTime()-d1.getTime())/1000); //gives the time difference in seconds.
and, to show in a nicer format, you can use:
DecimalFormat myDecimalFormatter = new DecimalFormat("###,###.###");
System.out.println(myDecimalFormatter.format(((double)d2.getTime()-d1.getTime())/1000));
It worked for me.
$f=fopen('php://memory','w');
$header=array("asdf ","asdf","asd","Calasdflee","Start Time","End Time" );
fputcsv($f,$header);
fputcsv($f,$header);
fputcsv($f,$header);
fseek($f,0);
header('content-type:text/csv');
header('Content-Disposition: attachment; filename="' . $filename . '";');
fpassthru($f);```
It turned out that my problem was that I was using a load balancer to handle the SSL, which then sent it over http to the actual server, which then complained.
Description of a fix is here: http://blog.hackedbrain.com/2006/09/26/how-to-ssl-passthrough-with-wcf-or-transportwithmessagecredential-over-plain-http/
Edit: I fixed my problem, which was slightly different, after talking to microsoft support.
My silverlight app had its endpoint address in code going over https to the load balancer. The load balancer then changed the endpoint address to http and to point to the actual server that it was going to. So on each server's web config I added a listenUri for the endpoint that was http instead of https
<endpoint address="" listenUri="http://[LOAD_BALANCER_ADDRESS]" ... />
For only a small amount of objects the update_or_create works well, but if you're doing over a large collection it won't scale well. update_or_create always first runs a SELECT and thereafter an UPDATE.
for the_bar in bars:
updated_rows = SomeModel.objects.filter(bar=the_bar).update(foo=100)
if not updated_rows:
# if not exists, create new
SomeModel.objects.create(bar=the_bar, foo=100)
This will at best only run the first update-query, and only if it matched zero rows run another INSERT-query. Which will greatly increase your performance if you expect most of the rows to actually be existing.
It all comes down to your use case though. If you are expecting mostly inserts then perhaps the bulk_create() command could be an option.
In C++, your source files are usually parsed from top to bottom in a single pass, so any variable or function must be declared before they can be used. There are some exceptions to this, like when defining functions inline in a class definition, but that's not the case for your code.
Either move the definition of integrate
above the one for getSkewNormal
, or add a forward declaration above getSkewNormal
:
double integrate (double start, double stop, int numSteps, Evaluatable evalObj);
The same applies for sum
.
According to the man page of wget, there are a couple of options related to timeouts -- and there is a default read timeout of 900s -- so I say that, yes, it could timeout.
Here are the options in question :
-T seconds
--timeout=seconds
Set the network timeout to seconds seconds. This is equivalent to specifying
--dns-timeout
,--connect-timeout
, and--read-timeout
, all at the same time.
And for those three options :
--dns-timeout=seconds
Set the DNS lookup timeout to seconds seconds.
DNS lookups that don't complete within the specified time will fail.
By default, there is no timeout on DNS lookups, other than that implemented by system libraries.
--connect-timeout=seconds
Set the connect timeout to seconds seconds.
TCP connections that take longer to establish will be aborted.
By default, there is no connect timeout, other than that implemented by system libraries.
--read-timeout=seconds
Set the read (and write) timeout to seconds seconds.
The "time" of this timeout refers to idle time: if, at any point in the download, no data is received for more than the specified number of seconds, reading fails and the download is restarted.
This option does not directly affect the duration of the entire download.
I suppose using something like
wget -O - -q -t 1 --timeout=600 http://www.example.com/cron/run
should make sure there is no timeout before longer than the duration of your script.
(Yeah, that's probably the most brutal solution possible ^^ )
You should not use your domain models
in your views. ViewModels
are the correct way to do it.
You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.
If you never heard of viewmodels, take a look at this.
You could use an asymmetrical border to make curves with CSS.
border-radius: 50%/100px 100px 0 0;
.box {_x000D_
width: 500px; _x000D_
height: 100px; _x000D_
border: solid 5px #000;_x000D_
border-color: #000 transparent transparent transparent;_x000D_
border-radius: 50%/100px 100px 0 0;_x000D_
}
_x000D_
<div class="box"></div>
_x000D_
The jQuery docs for text()
says
Due to variations in the HTML parsers in different browsers, the text returned may vary in newlines and other white space.
I'd use $td.html()
instead.
If your data is already serialized:
a) send a JSON response
public function someAction()
{
$response = new Response();
$response->setContent(file_get_contents('path/to/file'));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
b) send a JSONP response (with callback)
public function someAction()
{
$response = new Response();
$response->setContent('/**/FUNCTION_CALLBACK_NAME(' . file_get_contents('path/to/file') . ');');
$response->headers->set('Content-Type', 'text/javascript');
return $response;
}
If your data needs be serialized:
c) send a JSON response
public function someAction()
{
$response = new JsonResponse();
$response->setData([some array]);
return $response;
}
d) send a JSONP response (with callback)
public function someAction()
{
$response = new JsonResponse();
$response->setData([some array]);
$response->setCallback('FUNCTION_CALLBACK_NAME');
return $response;
}
e) use groups in Symfony 3.x.x
Create groups inside your Entities
<?php
namespace Mindlahus;
use Symfony\Component\Serializer\Annotation\Groups;
/**
* Some Super Class Name
*
* @ORM able("table_name")
* @ORM\Entity(repositoryClass="SomeSuperClassNameRepository")
* @UniqueEntity(
* fields={"foo", "boo"},
* ignoreNull=false
* )
*/
class SomeSuperClassName
{
/**
* @Groups({"group1", "group2"})
*/
public $foo;
/**
* @Groups({"group1"})
*/
public $date;
/**
* @Groups({"group3"})
*/
public function getBar() // is* methods are also supported
{
return $this->bar;
}
// ...
}
Normalize your Doctrine Object inside the logic of your application
<?php
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
// For annotations
use Doctrine\Common\Annotations\AnnotationReader;
use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
...
$repository = $this->getDoctrine()->getRepository('Mindlahus:SomeSuperClassName');
$SomeSuperObject = $repository->findOneById($id);
$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
$encoder = new JsonEncoder();
$normalizer = new ObjectNormalizer($classMetadataFactory);
$callback = function ($dateTime) {
return $dateTime instanceof \DateTime
? $dateTime->format('m-d-Y')
: '';
};
$normalizer->setCallbacks(array('date' => $callback));
$serializer = new Serializer(array($normalizer), array($encoder));
$data = $serializer->normalize($SomeSuperObject, null, array('groups' => array('group1')));
$response = new Response();
$response->setContent($serializer->serialize($data, 'json'));
$response->headers->set('Content-Type', 'application/json');
return $response;
This oughta do it.
DateTimePicker1.Value = DateTime.Now.AddDays(-1).Date;
Simple query to list child's of first recursion:
select @pv:=id as id, name, parent_id
from products
join (select @pv:=19)tmp
where parent_id=@pv
Result:
id name parent_id
20 category2 19
21 category3 20
22 category4 21
26 category24 22
... with left join:
select
@pv:=p1.id as id
, p2.name as parent_name
, p1.name name
, p1.parent_id
from products p1
join (select @pv:=19)tmp
left join products p2 on p2.id=p1.parent_id -- optional join to get parent name
where p1.parent_id=@pv
The solution of @tincot to list all child's:
select id,
name,
parent_id
from (select * from products
order by parent_id, id) products_sorted,
(select @pv := '19') initialisation
where find_in_set(parent_id, @pv) > 0
and @pv := concat(@pv, ',', id)
Test it online with Sql Fiddle and see all results.
This is an old post but...
You can reference the working directory (the folder the .html file is located in) with ./
, and the directory above that with ../
Example directory structure:
/html/public/
- index.html
- script2.js
- js/
- script.js
To load script.js from inside index.html:
<script type="text/javascript" src="./js/script.js">
This goes to the current working directory (location of index.html) and then to the js folder, and then finds the script.
You could also specify ../
to go one directory above the working directory, to load things from there. But that is unusual.
Also you can try:
string.split('foo').join('bar');
It looks like there has been an update to React that doesn't allow you to set the "paths"
in the tsconfig.json
anylonger.
Nicely React just outputs a warning:
The following changes are being made to your tsconfig.json file:
- compilerOptions.paths must not be set (aliased imports are not supported)
then updates your tsconfig.json
and removes the entire "paths"
section for you. There is a way to get around this run
npm run eject
This will eject all of the create-react-scripts
settings by adding config
and scripts
directories and build/config files into your project. This also allows a lot more control over how everything is built, named etc. by updating the {project}/config/*
files.
Then update your tsconfig.json
{
"compilerOptions": {
"baseUrl": "./src",
{…}
"paths": {
"assets/*": [ "assets/*" ],
"styles/*": [ "styles/*" ]
}
},
}
with org.hibernate.hql.internal.ast.QuerySyntaxException: users is not mapped [from users]
, you are trying to select from the users
table. But you are annotating your class with @Table( name = "Users" )
. So either use users
, or Users
.
Drop root privileges after you bind to port 80 (or 443).
This allows port 80/443 to remain protected, while still preventing you from serving requests as root:
function drop_root() {
process.setgid('nobody');
process.setuid('nobody');
}
A full working example using the above function:
var process = require('process');
var http = require('http');
var server = http.createServer(function(req, res) {
res.write("Success!");
res.end();
});
server.listen(80, null, null, function() {
console.log('User ID:',process.getuid()+', Group ID:',process.getgid());
drop_root();
console.log('User ID:',process.getuid()+', Group ID:',process.getgid());
});
See more details at this full reference.
Had same issue when I had to develop a fixed length field format.
Usually we do not use line separator for binary files but For some reason our customer wished to add a line break as separator between records. They set
< record_delimiter value="\n"/ >
but this didn't work as records got two additional characters:
< record1 > \n < record2 > \n.... and so on.
Did following change and it just worked.
< record_delimiter value="\n"/> => < record_delimiter value="
"/ >
After unmarshaling Java interprets as new line character.
:primary_key, :string, :text, :integer, :float, :decimal, :datetime, :timestamp,
:time, :date, :binary, :boolean, :references
See the table definitions section.
input[type="number"]::-webkit-outer-spin-button,
input[type="number"]::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
input[type="number"] {
-moz-appearance: textfield;
}
_x000D_
<input type="number" />
_x000D_
To add to existing answer...
In current versions of Firefox, the (user agent) default value of the -moz-appearance
property on these elements is number-input
. Changing that to the value textfield
effectively removes the spinner.
input[type="number"] {
-moz-appearance: textfield;
}
In some cases, you may want the spinner to be hidden initially, and then appear on hover/focus. (This is currently the default behavior in Chrome). If so, you can use the following:
input[type="number"] {
-moz-appearance: textfield;
}
input[type="number"]:hover,
input[type="number"]:focus {
-moz-appearance: number-input;
}
_x000D_
<input type="number"/>
_x000D_
In current versions of Chrome, the (user agent) default value of the -webkit-appearance
property on these elements is already textfield
. In order to remove the spinner, the -webkit-appearance
property's value needs to be changed to none
on the ::-webkit-outer-spin-button
/::-webkit-inner-spin-button
pseudo classes (it is -webkit-appearance: inner-spin-button
by default).
input[type="number"]::-webkit-outer-spin-button,
input[type="number"]::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
_x000D_
<input type="number" />
_x000D_
It's worth pointing out that margin: 0
is used to remove the margin in older versions of Chrome.
Currently, as of writing this, here is the default user agent styling on the 'inner-spin-button' pseudo class:
input::-webkit-inner-spin-button {
-webkit-appearance: inner-spin-button;
display: inline-block;
cursor: default;
flex: 0 0 auto;
align-self: stretch;
-webkit-user-select: none;
opacity: 0;
pointer-events: none;
-webkit-user-modify: read-only;
}
Simple example using a class :
class test {
public function works($other_parameter, $function_as_parameter)
{
return $function_as_parameter($other_parameter) ;
}
}
$obj = new test() ;
echo $obj->works('working well',function($other_parameter){
return $other_parameter;
});
npm root -g
to check the npm_modules global location
if you give a 2D array to the plot function of matplotlib it will assume the columns to be lines:
If x and/or y is 2-dimensional, then the corresponding columns will be plotted.
In your case your shape is not accepted (100, 1, 1, 8000). As so you can using numpy squeeze to solve the problem quickly:
np.squeez doc: Remove single-dimensional entries from the shape of an array.
import numpy as np
import matplotlib.pyplot as plt
data = np.random.randint(3, 7, (10, 1, 1, 80))
newdata = np.squeeze(data) # Shape is now: (10, 80)
plt.plot(newdata) # plotting by columns
plt.show()
But notice that 100 sets of 80 000 points is a lot of data for matplotlib. I would recommend that you look for an alternative. The result of the code example (run in Jupyter) is:
if (position ==0) {
if (rYes.isChecked()) {
Toast.makeText(SportActivity.this, "yes ur answer is right", Toast.LENGTH_LONG).show();
} else if (rNo.isChecked()) {
Toast.makeText(SportActivity.this, "no.ur answer is wrong", Toast.LENGTH_LONG).show();
}
}
This code is supposed to select both check boxes.
Is there a problem with it?
First I would make sure the email address only shows when you have javascript enabled. This way, there is no plain text that can be read without javascript.
Secondly, A way of implementing a safe feature is by staying away from the <button>
tag. This tag needs a text insert between the tags, which makes it computer-readable. Instead try the <input type="button">
with a javascript handler for an onClick.
Then use all of the techniques mentioned by otherse to implement a safe email notation.
One other option is to have a button with "Click to see emailaddress". Once clicked this changes into a coded email (the characters in HTML codes). On another click this redirects to the 'mailto:email' function
An uncoded version of the last idea, with selectable and non-selectable email addresses:
<html>
<body>
<script type="text/javascript">
e1="@domain";
e2="me";
e3=".extension";
email_link="mailto:"+e2+e1+e3;
</script>
<input type="text" onClick="this.onClick=window.open(email_link);" value="Click for mail"/>
<input type="text" onClick="this.value=email;" value="Click for mail-address"/>
<input type="button" onClick="this.onClick=window.open(email_link);" value="Click for mail"/>
<input type="button" onClick="this.value=email;" value="Click for mail-address"/>
</body></html>
See if this is something you would want and combine it with others' ideas. You can never be too sure.
For some reason, strtotime('next friday')
display the Friday date of the current week. Try this instead:
//Current date 2020-02-03
$fridayNextWeek = date('Y-m-d', strtotime('friday next week'); //Outputs 2020-02-14
$nextFriday = date('Y-m-d', strtotime('next friday'); //Outputs 2020-02-07
In my ROM, it's stored in the "global" database, rather than "secure". So D__'s answer is correct, but the sql line needs to connect to a different database:
sqlite3 /data/data/com.android.providers.settings/databases/settings.db
update global set value=1 where name='wifi_on';
Whenever you want to extend the properties of User.Identity with any additional properties like the question above, add these properties to the ApplicationUser class first like so:
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
// Your Extended Properties
public long? OrganizationId { get; set; }
}
Then what you need is to create an extension method like so (I create mine in an new Extensions folder):
namespace App.Extensions
{
public static class IdentityExtensions
{
public static string GetOrganizationId(this IIdentity identity)
{
var claim = ((ClaimsIdentity)identity).FindFirst("OrganizationId");
// Test for null to avoid issues during local testing
return (claim != null) ? claim.Value : string.Empty;
}
}
}
When you create the Identity in the ApplicationUser class, just add the Claim -> OrganizationId like so:
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here => this.OrganizationId is a value stored in database against the user
userIdentity.AddClaim(new Claim("OrganizationId", this.OrganizationId.ToString()));
return userIdentity;
}
Once you added the claim and have your extension method in place, to make it available as a property on your User.Identity, add a using statement on the page/file you want to access it:
in my case: using App.Extensions;
within a Controller and @using. App.Extensions
withing a .cshtml View file.
EDIT:
What you can also do to avoid adding a using statement in every View is to go to the Views folder, and locate the Web.config file in there.
Now look for the <namespaces>
tag and add your extension namespace there like so:
<add namespace="App.Extensions" />
Save your file and you're done. Now every View will know of your extensions.
You can access the Extension Method:
var orgId = User.Identity.GetOrganizationId();
syntax is:
sheet.addMergedRegion(new CellRangeAddress(start-col,end-col,start-cell,end-cell));
Example:
sheet.addMergedRegion(new CellRangeAddress(4, 4, 0, 5));
Here the cell 0 to cell 5 will be merged of the 4th row.
Because I have to reboot my VM regularly, so somehow this problem happens to me very often. After few times of it, I realized I cannot repeat the process described by @Nathan-Vanhoudnos every time this happens, though it always works. Then I figured out the following faster solution.
Step 1
Move your entire repo to another folder.
mv current_repo temp_repo
Step 2
Clone the repo from origin again.
git clone source_to_current_repo.git
Step 3
Remove Everything under the new repo except the .git folder.
Step 4
Move Everything from the temp_repo to the new repo except the .git folder.
Step 5
Remove the temp_repo, and we are done.
After few times, I'm sure you can do this procedures very quickly.
The precision of float is 7 digits. If you want to keep the whole lot, you need to use the double type that keeps 15-16 digits. Regarding formatting, look at a post about formatting doubles. And you need to worry about decimal separators in C#.
ListView.FocusedItem.Index
or you can use foreach loop like this
int index= -1;
foreach (ListViewItem itm in listView1.SelectedItems)
{
if (itm.Selected)
{
index= itm.Index;
}
}
The important difference between signed and unsigned ints is the interpretation of the last bit. The last bit in signed types represent the sign of the number, meaning: e.g:
0001 is 1 signed and unsigned 1001 is -1 signed and 9 unsigned
(I avoided the whole complement issue for clarity of explanation! This is not exactly how ints are represented in memory!)
You can imagine that it makes a difference to know if you compare with -1 or with +9. In many cases, programmers are just too lazy to declare counting ints as unsigned (bloating the for loop head f.i.) It is usually not an issue because with ints you have to count to 2^31 until your sign bit bites you. That's why it is only a warning. Because we are too lazy to write 'unsigned' instead of 'int'.
$ brew tap caskroom/cask
$ brew install brew-cask
$ brew tap caskroom/versions
$ brew cask install sublime-text
Try this or purpose will solve with lesser no of steps
for (int i = 0; i < a.length; i++)
{
for (int k = i+1; k < a.length; k++)
{
if (a[i] != a[k])
{
System.out.println(a[i]+"not the same with"+a[k]+"\n");
}
}
}
For my case on Ubuntu 14.04 installed with postgres 10.3. I need to follow the following steps
su - postgres
to switch user to postgres
psql
to enter postgres shell\password
then enter your password\q
to quit the shell sessionThen you switch back to root by executing exit
and configure your pg_hba.conf
(mine is at /etc/postgresql/10/main/pg_hba.conf
) by making sure you have the following line
local all postgres md5
service postgresql restart
postgres
user and enter postgres shell again. It will prompt you with password.Just call fig.tight_layout()
as you normally would. (pyplot
is just a convenience wrapper. In most cases, you only use it to quickly generate figure and axes objects and then call their methods directly.)
There shouldn't be a difference between the QtAgg
backend and the default backend (or if there is, it's a bug).
E.g.
import matplotlib.pyplot as plt
#-- In your case, you'd do something more like:
# from matplotlib.figure import Figure
# fig = Figure()
#-- ...but we want to use it interactive for a quick example, so
#-- we'll do it this way
fig, axes = plt.subplots(nrows=4, ncols=4)
for i, ax in enumerate(axes.flat, start=1):
ax.set_title('Test Axes {}'.format(i))
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
plt.show()
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=4, ncols=4)
for i, ax in enumerate(axes.flat, start=1):
ax.set_title('Test Axes {}'.format(i))
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
fig.tight_layout()
plt.show()
Here's my attempt at the most forgiving string to bool conversion that is still useful, basically keying off only the first character.
public static class StringHelpers
{
/// <summary>
/// Convert string to boolean, in a forgiving way.
/// </summary>
/// <param name="stringVal">String that should either be "True", "False", "Yes", "No", "T", "F", "Y", "N", "1", "0"</param>
/// <returns>If the trimmed string is any of the legal values that can be construed as "true", it returns true; False otherwise;</returns>
public static bool ToBoolFuzzy(this string stringVal)
{
string normalizedString = (stringVal?.Trim() ?? "false").ToLowerInvariant();
bool result = (normalizedString.StartsWith("y")
|| normalizedString.StartsWith("t")
|| normalizedString.StartsWith("1"));
return result;
}
}
This code should work for you:
$PHPExcel->getActiveSheet()
->getStyle('A1')
->getFill()
->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
->getStartColor()
->setRGB('FF0000')
But if you bother using this over and over again, I recommend using applyFromArray
.
The bundle id (app ID) has a binding relationship with the apple id (apple id is the Apple development account, which also belongs to a certain development team). When the app is created, the bundle id (app ID) is already associated with you The development team is bound, so your app is being sent to other colleagues, he opens it in Xcode, and connects the real machine with a data cable to debug it will report the error as above;
To Solution
Follow the prompts to change the bundle id
Because some functions, such as third-party login, are bound to the bundle id to apply for the app key, etc., the bundle id cannot be modified. Then please find the apple id account registered by the bundle id before. Here, I will change It’s ok to become the apple id account I registered in the company group
If other colleagues in your group can run this app successfully on a real machine, it means that the "description file" corresponding to the apple id "certificate" used by him is correct.
Using Integer.parseIn(String), you can parse string value into integer. Also you need to catch exception in case if input string is not a proper number.
int x = 0;
try {
x = Integer.parseInt("100"); // Parse string into number
} catch (NumberFormatException e) {
e.printStackTrace();
}
I had same problem with 'parallax' plugin.
I changed jQuery librery version to *jquery-1.6.4*
from *jquery-1.10.2*.
And error cleared.
ForeignKey is represented by django.forms.ModelChoiceField, which is a ChoiceField whose choices are a model QuerySet. See the reference for ModelChoiceField.
So, provide a QuerySet to the field's queryset
attribute. Depends on how your form is built. If you build an explicit form, you'll have fields named directly.
form.rate.queryset = Rate.objects.filter(company_id=the_company.id)
If you take the default ModelForm object, form.fields["rate"].queryset = ...
This is done explicitly in the view. No hacking around.
For those who are using yarn
yarn list webpack
will do the trick
$ yarn list webpack
yarn list v0.27.5
+- [email protected]
Done in 1.24s.
subprocess.Popen does exactly what you want.
from subprocess import Popen
p = Popen(['watch', 'ls']) # something long running
# ... do other stuff while subprocess is running
p.terminate()
(Edit to complete the answer from comments)
The Popen instance can do various other things like you can poll()
it to see if it is still running, and you can communicate()
with it to send it data on stdin, and wait for it to terminate.
The Combinations
package is not part of the standard CRAN set of packages, but is rather part of a different repository, omegahat. To install it you need to use
install.packages("Combinations", repos = "http://www.omegahat.org/R")
See the documentation at http://www.omegahat.org/Combinations/
Do it like this: Remember to close iframe tag.
<iframe src="http://samplepdf.com/sample.pdf" width="800" height="600"></iframe>
You want to use slicing.
for item in listOfStuff[1:3]:
print item
Ahhhh, now it is clear. You seem to have problems binding back the value. Not with displaying it on the view. Indeed, that's the fault of the default model binder. You could write and use a custom one that will take into consideration the [DisplayFormat]
attribute on your model. I have illustrated such a custom model binder here: https://stackoverflow.com/a/7836093/29407
Apparently some problems still persist. Here's my full setup working perfectly fine on both ASP.NET MVC 3 & 4 RC.
Model:
public class MyViewModel
{
[DisplayName("date of birth")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? Birth { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel
{
Birth = DateTime.Now
});
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
View:
@model MyViewModel
@using (Html.BeginForm())
{
@Html.LabelFor(x => x.Birth)
@Html.EditorFor(x => x.Birth)
@Html.ValidationMessageFor(x => x.Birth)
<button type="submit">OK</button>
}
Registration of the custom model binder in Application_Start
:
ModelBinders.Binders.Add(typeof(DateTime?), new MyDateTimeModelBinder());
And the custom model binder itself:
public class MyDateTimeModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (!string.IsNullOrEmpty(displayFormat) && value != null)
{
DateTime date;
displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
// use the format specified in the DisplayFormat attribute to parse the date
if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
return date;
}
else
{
bindingContext.ModelState.AddModelError(
bindingContext.ModelName,
string.Format("{0} is an invalid date format", value.AttemptedValue)
);
}
}
return base.BindModel(controllerContext, bindingContext);
}
}
Now, no matter what culture you have setup in your web.config (<globalization>
element) or the current thread culture, the custom model binder will use the DisplayFormat
attribute's date format when parsing nullable dates.
result_array()
returns Associative Array type data. Returning pure array is slightly faster than returning an array of objects. result()
is recursive in that it returns an std class object where as result_array()
just returns a pure array, so result_array()
would be choice regarding performance.
Andrew White's answer is sufficient to get you moving. Here's a step-by-step for beginners.
A simple get started:
Create test.cpp: (This will be built and run to verify you got things set up right.)
#include <X11/Xlib.h>
#include <unistd.h>
main()
{
// Open a display.
Display *d = XOpenDisplay(0);
if ( d )
{
// Create the window
Window w = XCreateWindow(d, DefaultRootWindow(d), 0, 0, 200,
100, 0, CopyFromParent, CopyFromParent,
CopyFromParent, 0, 0);
// Show the window
XMapWindow(d, w);
XFlush(d);
// Sleep long enough to see the window.
sleep(10);
}
return 0;
}
Try: g++ test.cpp -lX11
If it builds to a.out
, try running it.
If you see a simple window drawn, you have the necessary libraries, and some other root problem is afoot.
If your response is:
test.cpp:1:22: fatal error: X11/Xlib.h: No such file or directory
compilation terminated.
you need to install X11 development libraries.
sudo apt-get install libx11-dev
Retry g++ test.cpp -lX11
If it works, you're golden.
Tested using a fresh install of libX11-dev_2%3a1.5.0-1_i386.deb