For Netbeans 11 users, this works for me:
apply plugin: 'java'
apply plugin: 'application'
// This comes out to package + '.' + mainClassName
mainClassName = 'com.hello.JavaApplication1'
Here generally is my tree:
C:\...\NETBEANSPROJECTS\JAVAAPPLICATION1
¦ build.gradle
+---src
¦ +---main
¦ ¦ +---java
¦ ¦ +---com
¦ ¦ +---hello
¦ ¦ JavaApplication1.java
¦ ¦
¦ +---test
¦ +---java
+---test
table td{
color:#0000ff;
}
<table>
<tbody>
<tr>
<td>
<select name="test">
<option value="Basic">Basic : $30.00 USD - yearly</option>
<option value="Sustaining">Sustaining : $60.00 USD - yearly</option>
<option value="Supporting">Supporting : $120.00 USD - yearly</option>
</select>
</td>
</tr>
</tbody>
</table>
Try either
sudo apt-get install php-zip
orsudo apt-get install php5.6-zip
Then, you might have to restart your web server.
sudo service apache2 restart
orsudo service nginx restart
If you are installing on centos or fedora OS then use yum in place of apt-get. example:-
sudo yum install php-zip
or
sudo yum install php5.6-zip
and
sudo service httpd restart
Using environment variable is sometimes more convenient when you do not control the build scripts / process.
For C includes use C_INCLUDE_PATH
.
For C++ includes use CPLUS_INCLUDE_PATH
.
See this link for other gcc environment variables.
# `pip install` will automatically run `gcc` using parameters
# specified in the `asyncpg` package (that I do not control)
C_INCLUDE_PATH=/home/scott/.pyenv/versions/3.7.9/include/python3.7m pip install asyncpg
set C_INCLUDE_PATH="C:\Users\Scott\.pyenv\versions\3.7.9\include\python3.7m"
pip install asyncpg
# clear the environment variable so it doesn't affect other builds
set C_INCLUDE_PATH=
This looks like a behavior difference in the handling of \s
between grep 2.5 and newer versions (a bug in old grep?). I confirm your result with grep 2.5.4, but all four of your greps do work when using grep 2.6.3 (Ubuntu 10.10).
Note:
GNU grep 2.5.4
echo "foo bar" | grep "\s"
(doesn't match)
whereas
GNU grep 2.6.3
echo "foo bar" | grep "\s"
foo bar
Probably less trouble (as \s
is not documented):
Both GNU greps
echo "foo bar" | grep "[[:space:]]"
foo bar
My advice is to avoid using \s
... use [ \t]*
or [[:space:]]
or something like it instead.
For html generated in JS , do as below (we are using single quote as string wrapper). Each argument has to wrapped in a single quote else all of yours argument will be considered as a single argument like functionName('a,b') , now its a single argument with value a,b.
We have to use string escape character backslash() to close first argument with single quote, give a separator comma in between and then start next argument with a single quote. (This is the magic code to use
'\',\''
)
$('#ValuationAssignedTable').append('<tr> <td><a href=# onclick="return ReAssign(\'' + valuationId +'\',\'' + user + '\')">Re-Assign</a> </td> </tr>');
Assuming that your current primary key constraint is called pk_history, you can replace the following lines:
ALTER TABLE history ADD PRIMARY KEY (id)
ALTER TABLE history
DROP CONSTRAINT userId
DROP CONSTRAINT name
with these:
ALTER TABLE history DROP CONSTRAINT pk_history
ALTER TABLE history ADD CONSTRAINT pk_history PRIMARY KEY (id)
If you don't know what the name of the PK is, you can find it with the following query:
SELECT *
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE TABLE_NAME = 'history'
Yes! You can use the new Visual Studio for Mac, which Microsoft launched in November.
Read about it here: https://msdn.microsoft.com/magazine/mt790182
Download a preview version here: https://www.visualstudio.com/vs/visual-studio-mac/
What is missing in the question and all the answers is that you might need the passphrase to read public data from the PKCS#12 (.pfx) keystore. If you need a passphrase or not depends on how the PKCS#12 file was created. You can check the ASN1 structure of the file (by running it through a ASN1 parser, openssl or certutil can do this too), if the PKCS#7 data (e.g. OID prefix 1.2.840.113549.1.7) is listed as 'encrypted' or with a cipher-spec or if the location of the data in the asn1 tree is below an encrypted node, you won't be able to read it without knowledge of the passphrase. It means your 'openssl pkcs12' command will fail with errors (output depends on the version). For those wondering why you might be interested in the certificate of a PKCS#12 without knowledge of the passphrase. Imagine you have many keystores and many phassphrases and you are really bad at keeping them organized and you don't want to test all combinations, the certificate inside the file could help you find out which password it might be. Or you are developing software to migrate/renew a keystore and you need to decide in advance which procedure to initiate based on the contained certicate without user interaction. So the latter examples work without passphrase depending on the PKCS#12 structure.
Just wanted to add that, because I didn't find an answer myself and spend a lot of time to figure it out.
Showing it graphically.
Centering on parent is done by constraining both sides to the parent. You can the constrain additional objects off of the centered object.
Note. Each arrow represents a "app:layout_constraintXXX_toYYY=" attribute. (6 in the picture)
This site says to try:
import datetime as dt
start="09:35:23"
end="10:23:00"
start_dt = dt.datetime.strptime(start, '%H:%M:%S')
end_dt = dt.datetime.strptime(end, '%H:%M:%S')
diff = (end_dt - start_dt)
diff.seconds/60
This forum uses time.mktime()
If you are running on Vista, you may want to check out the Bitnami Django stack. It is an all-in-one stack of Apache, Python, MySQL, etc. packaged with Bitrock crossplatform installers to make it really easy to get started. It runs on Windows, Mac and Linux. Oh, and is completely free :)
If "partly cherry picking" means "within files, choosing some changes but discarding others", it can be done by bringing in git stash
:
git reset HEAD^
to convert the entire cherry-picked commit into unstaged working changes.git stash save --patch
: interactively select unwanted material to stash.git commit
git stash drop
. Tip: if you give the stash of unwanted changes a name: git stash save --patch junk
then if you forget to do (6) now, later you will recognize the stash for what it is.
You can add an conditional statement. If your array goes beyond index, then break and print the rest of the file.
Method call setSelectedIndex("item_value");
doesn't work because setSelectedIndex
use sequential index.
You have to use NSURLConnectionDelegate
to allow HTTPS connections and there are new callbacks with iOS8.
Deprecated:
connection:canAuthenticateAgainstProtectionSpace:
connection:didCancelAuthenticationChallenge:
connection:didReceiveAuthenticationChallenge:
Instead those, you need to declare:
connectionShouldUseCredentialStorage:
- Sent to determine whether the URL loader should use the credential storage for authenticating the connection.
connection:willSendRequestForAuthenticationChallenge:
- Tells the delegate that the connection will send a request for an authentication challenge.
With willSendRequestForAuthenticationChallenge
you can use challenge
like you did with the deprecated methods, for example:
// Trusting and not trusting connection to host: Self-signed certificate
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
I found this suggestion useful in my case:
def product_params
params.require(:product).permit(:name).tap do |whitelisted|
whitelisted[:data] = params[:product][:data]
end
end
Check this link of Xavier's comment on github.
This approach whitelists the entire params[:measurement][:groundtruth] object.
Using the original questions attributes:
def product_params
params.require(:measurement).permit(:name, :groundtruth).tap do |whitelisted|
whitelisted[:groundtruth] = params[:measurement][:groundtruth]
end
end
In your Dockerfile, run this first:
apt-get update && apt-get install -y gnupg2
You need to explicitly tell the data type or the type can be inferred when you declare anything in Swift.
Swift 3
The sample below declare a dictionary with key as a Int
type and the value as a String
type.
Method 1: Initializer
let dic = Dictionary<Int, String>()
Method 2: Shorthand Syntax
let dic = [Int:String]()
Method 3: Dictionary Literal
var dic = [1: "Sample"]
// dic has NOT to be a constant
dic.removeAll()
Depends what you mean by "table's size". A table doesn't relate to a specific file on the file system. A table will reside on a tablespace (possibly multiple tablespaces if it is partitioned, and possibly multiple tablespaces if you also want to take into account indexes on the table). A tablespace will often have multiple tables in it, and may be spread across multiple files.
If you are estimating how much space you'll need for the table's future growth, then avg_row_len multiplied by the number of rows in the table (or number of rows you expect in the table) will be a good guide. But Oracle will leave some space free on each block, partly to allow for rows to 'grow' if they are updated, partly because it may not be possible to fit another entire row on that block (eg an 8K block would only fit 2 rows of 3K, though that would be an extreme example as 3K is a lot bigger than most row sizes). So BLOCKS (in USER_TABLES) might be a better guide.
But if you had 200,000 rows in a table, deleted half of them, then the table would still 'own' the same number of blocks. It doesn't release them up for other tables to use. Also, blocks are not added to a table individually, but in groups called an 'extent'. So there are generally going to be EMPTY_BLOCKS (also in USER_TABLES) in a table.
Fix memory leaks in your application with help of profile tools like eclipse MAT or VisualVM
With JDK 1.7.x
or later versions, use G1GC
, which spends 10% on garbage collection unlike 2% in other GC algorithms.
Apart from setting heap memory with -Xms1g -Xmx2g
, try `
-XX:+UseG1GC
-XX:G1HeapRegionSize=n,
-XX:MaxGCPauseMillis=m,
-XX:ParallelGCThreads=n,
-XX:ConcGCThreads=n`
Have a look at oracle article for fine-tuning these parameters.
Some question related to G1GC in SE:
Java 7 (JDK 7) garbage collection and documentation on G1
import java.io.*;
public class FileRead {
public static void main(String[] args) throws IOException {
File f=new File("C:\\Documents and Settings\\abc\\Desktop\\abc.pdf");
OutputStream oos = new FileOutputStream("test.pdf");
byte[] buf = new byte[8192];
InputStream is = new FileInputStream(f);
int c = 0;
while ((c = is.read(buf, 0, buf.length)) > 0) {
oos.write(buf, 0, c);
oos.flush();
}
oos.close();
System.out.println("stop");
is.close();
}
}
The easiest way so far. Hope this helps.
A segmentation fault is caused by a request for a page that the process does not have listed in its descriptor table, or an invalid request for a page that it does have listed (e.g. a write request on a read-only page).
A dangling pointer is a pointer that may or may not point to a valid page, but does point to an "unexpected" segment of memory.
The following suggestion let's you test abstract classes without creating a "real" subclass - the Mock is the subclass.
use Mockito.mock(My.class, Mockito.CALLS_REAL_METHODS)
, then mock any abstract methods that are invoked.
Example:
public abstract class My {
public Result methodUnderTest() { ... }
protected abstract void methodIDontCareAbout();
}
public class MyTest {
@Test
public void shouldFailOnNullIdentifiers() {
My my = Mockito.mock(My.class, Mockito.CALLS_REAL_METHODS);
Assert.assertSomething(my.methodUnderTest());
}
}
Note: The beauty of this solution is that you do not have to implement the abstract methods, as long as they are never invoked.
In my honest opinion, this is neater than using a spy, since a spy requires an instance, which means you have to create an instantiatable subclass of your abstract class.
The Web Deployment Agent Service is deployed with WebMatrix and was the cause of my woes. It may also be distributed with other applications installed using Microsoft’s Web Platform Installer.
Uninstall it solved my problems!
string stringtodate = ((DateTime)row.Cells[4].Value).ToString("MM-dd-yyyy");
textBox9.Text = stringtodate;
I believe those who study typography would tell you that 66 characters per a line is supposed to be the most readable width for length. Even so, if you need to debug a machine remotely over an ssh session, most terminals default to 80 characters, 79 just fits, trying to work with anything wider becomes a real pain in such a case. You would also be suprised by the number of developers using vim + screen as a day to day environment.
The only way to get the iOS dictation is to sign up yourself through Nuance: http://dragonmobile.nuancemobiledeveloper.com/ - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.
The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.
As noted in comments above, while still on some UA implementations, readAsBinaryString
method didn't made its way to the specs and should not be used in production.
Instead, use readAsArrayBuffer
and loop through it's buffer
to get back the binary string :
document.querySelector('input').addEventListener('change', function() {_x000D_
_x000D_
var reader = new FileReader();_x000D_
reader.onload = function() {_x000D_
_x000D_
var arrayBuffer = this.result,_x000D_
array = new Uint8Array(arrayBuffer),_x000D_
binaryString = String.fromCharCode.apply(null, array);_x000D_
_x000D_
console.log(binaryString);_x000D_
_x000D_
}_x000D_
reader.readAsArrayBuffer(this.files[0]);_x000D_
_x000D_
}, false);
_x000D_
<input type="file" />_x000D_
<div id="result"></div>
_x000D_
For a more robust way to convert your arrayBuffer in binary string, you can refer to this answer.
Yes, the file API does provide a way to convert your File, in the <input type="file"/>
to a binary string, thanks to the FileReader Object and its method readAsBinaryString
.
[But don't use it in production !]
document.querySelector('input').addEventListener('change', function(){_x000D_
var reader = new FileReader();_x000D_
reader.onload = function(){_x000D_
var binaryString = this.result;_x000D_
document.querySelector('#result').innerHTML = binaryString;_x000D_
}_x000D_
reader.readAsBinaryString(this.files[0]);_x000D_
}, false);
_x000D_
<input type="file"/>_x000D_
<div id="result"></div>
_x000D_
If you want an array buffer, then you can use the readAsArrayBuffer()
method :
document.querySelector('input').addEventListener('change', function(){_x000D_
var reader = new FileReader();_x000D_
reader.onload = function(){_x000D_
var arrayBuffer = this.result;_x000D_
console.log(arrayBuffer);_x000D_
document.querySelector('#result').innerHTML = arrayBuffer + ' '+arrayBuffer.byteLength;_x000D_
}_x000D_
reader.readAsArrayBuffer(this.files[0]);_x000D_
}, false);
_x000D_
<input type="file"/>_x000D_
<div id="result"></div>
_x000D_
Every time a new device is opened par() will reset, so another option is simply do dev.off()
and continue.
Ezward has already provided a good answer, but I noticed that one of the comments asks how it is used. For people like me who stumble across this question, I thought it would be useful to have a link to the official documentation on getters and setters on the Typescript website as that explains it well, will hopefully always stay up-to-date as changes are made, and shows example usage:
http://www.typescriptlang.org/docs/handbook/classes.html
In particular, for those not familiar with it, note that you don't incorporate the word 'get' into a call to a getter (and similarly for setters):
var myBar = myFoo.getBar(); // wrong
var myBar = myFoo.get('bar'); // wrong
You should simply do this:
var myBar = myFoo.bar; // correct (get)
myFoo.bar = true; // correct (set) (false is correct too obviously!)
given a class like:
class foo {
private _bar:boolean = false;
get bar():boolean {
return this._bar;
}
set bar(theBar:boolean) {
this._bar = theBar;
}
}
then the 'bar' getter for the private '_bar' property will be called.
Like Eric, I used homebrew, but I used the default recipe. So:
brew install mercurial
brew install vim
And after restarting the terminal homebrew's vim should be the default. If not, you should update your $PATH
so that /usr/local/bin
is before /usr/bin
. E.g. add the following to your .profile
:
export PATH=/usr/local/bin:$PATH
If the class file you want to look into is open source, you should not decompile it, but instead attach the source files directly into your IDE. that way, you can just view the code of some library class as if it were your own
Just delete packages folder.That helped me
I'm recommended use MySQL Workbench where is import data. Workbench allows the user to create a new table from a file in CSV or JSON format. It handles table schema and data import in just a few clicks through the wizard.
In MySQL Workbench, use the context menu on table list and click Table Data Import Wizard
.
More from the MySQL Workbench 6.5.1 Table Data Export and Import Wizard documentation. Download MySQL Workbench here.
You might also want to look at CanvasJS Chart which is built on top of HTML5 Canvas Element. It renders really fast and can be updated every 50-100 milliseconds without getting into memory issues.
[Full disclosure: I am part of the team]
Why the loop?
You could simply do this:
{% if 'priority' in data %}
<p>Priority: {{ data['priority'] }}</p>
{% endif %}
When you were originally doing your string comparison, you should have used ==
instead.
I could fix it by installing the following directly.
pip install google.cloud.bigquery
pip install google.cloud.storage
See .offset()
here in the jQuery doc. It gives the position relative to the document, not to the parent. You perhaps have .offset()
and .position()
confused. If you want the position in the window instead of the position in the document, you can subtract off the .scrollTop()
and .scrollLeft()
values to account for the scrolled position.
Here's an excerpt from the doc:
The .offset() method allows us to retrieve the current position of an element relative to the document. Contrast this with .position(), which retrieves the current position relative to the offset parent. When positioning a new element on top of an existing one for global manipulation (in particular, for implementing drag-and-drop), .offset() is the more useful.
To combine these:
var offset = $("selector").offset();
var posY = offset.top - $(window).scrollTop();
var posX = offset.left - $(window).scrollLeft();
You can try it here (scroll to see the numbers change): http://jsfiddle.net/jfriend00/hxRPQ/
I strongly suggest you to read this blog post which appeared on HackerNews recently: How HashMap works in Java
In short, the answer is
What will happen if two different HashMap key objects have same hashcode?
They will be stored in same bucket but no next node of linked list. And keys equals () method will be used to identify correct key value pair in HashMap.
The compiler is telling you that there are problems starting at line 122 in the middle of that strange FBI-CIA warning message. That message is not valid C++ code and is NOT commented out so of course it will cause compiler errors. Try removing that entire message.
Also, I agree with In silico: you should always tell us what you tried and exactly what error messages you got.
import java.util.Stack;
public class IterativePostOrderTraversal extends BinaryTree {
public static void iterativePostOrderTraversal(Node root){
Node cur = root;
Node pre = root;
Stack<Node> s = new Stack<Node>();
if(root!=null)
s.push(root);
System.out.println("sysout"+s.isEmpty());
while(!s.isEmpty()){
cur = s.peek();
if(cur==pre||cur==pre.left ||cur==pre.right){// we are traversing down the tree
if(cur.left!=null){
s.push(cur.left);
}
else if(cur.right!=null){
s.push(cur.right);
}
if(cur.left==null && cur.right==null){
System.out.println(s.pop().data);
}
}else if(pre==cur.left){// we are traversing up the tree from the left
if(cur.right!=null){
s.push(cur.right);
}else if(cur.right==null){
System.out.println(s.pop().data);
}
}else if(pre==cur.right){// we are traversing up the tree from the right
System.out.println(s.pop().data);
}
pre=cur;
}
}
public static void main(String args[]){
BinaryTree bt = new BinaryTree();
Node root = bt.generateTree();
iterativePostOrderTraversal(root);
}
}
There is a math function modf()
that will break this up as well.
import math
print("math.modf(3.14159) : ", math.modf(3.14159))
will output a tuple:
math.modf(3.14159) : (0.14159, 3.0)
This is useful if you want to keep both the whole part and decimal for reference like:
decimal, whole = math.modf(3.14159)
You can simply try like this take a string iterate over it using for loop till second last character of string and then simply reverse your loop like following:
public class StringReverse {
public static void main(String ar[]){
System.out.println(reverseMe("iniana"));
}
static String reverseMe(String s){
String reverse = "";
for(int i = s.length()-1; i>=0; i--){
resverse = reverse + s.charAt(i);
}
return reverse;
}
}
It's just an addition, with this you can get the data into CSV format
import sys,os
try:
import pandas as pd
except:
os.system("pip3 install pandas")
root = "/home/kiran/Downloads/MainFolder" # it may have many subfolders and files inside
lst = []
from fnmatch import fnmatch
pattern = "*.csv" #I want to get only csv files
pattern = "*.*" # Note: Use this pattern to get all types of files and folders
for path, subdirs, files in os.walk(root):
for name in files:
if fnmatch(name, pattern):
lst.append((os.path.join(path, name)))
df = pd.DataFrame({"filePaths":lst})
df.to_csv("filepaths.csv")
Right click on the project in solution-explorer and click "clean".
Now run F5
Make sure the code is as below:
Console.WriteLine("TEST");
Console.ReadLine();
I got a solution for downloading from angular 2 without getting corrupt, using spring mvc and angular 2
1st- my return type is :-ResponseEntity from java end. Here I am sending byte[] array has return type from the controller.
2nd- to include the filesaver in your workspace-in the index page as:
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2014-11-29/FileSaver.min.js"></script>
3rd- at component ts write this code:
import {ResponseContentType} from '@angular.core';
let headers = new Headers({ 'Content-Type': 'application/json', 'MyApp-Application' : 'AppName', 'Accept': 'application/pdf' });
let options = new RequestOptions({ headers: headers, responseType: ResponseContentType.Blob });
this.http
.post('/project/test/export',
somevalue,options)
.subscribe(data => {
var mediaType = 'application/vnd.ms-excel';
let blob: Blob = data.blob();
window['saveAs'](blob, 'sample.xls');
});
This will give you xls file format. If you want other formats change the mediatype and file name with right extension.
When Command Extensions are enabled (Windows XP and newer, roughly), you can use the syntax %~nF (where F is the variable and ~n is the request for its name) to only get the filename.
FOR /R C:\Directory %F in (*.*) do echo %~nF
should echo only the filenames.
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Record Inserted Successfully')", true);
You can use this way, but be sure that there is no Page.Redirect()
is used.
If you want to redirect to another page then you can try this:
page.aspx:
<asp:Button AccessKey="S" ID="submitBtn" runat="server" OnClick="Submit" Text="Submit"
Width="90px" ValidationGroup="vg" CausesValidation="true" OnClientClick = "Confirm()" />
JavaScript code:
function Confirm()
{
if (Page_ClientValidate())
{
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Data has been Added. Do you wish to Continue ?"))
{
confirm_value.value = "Yes";
}
else
{
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
}
and this is your code behind snippet :
protected void Submit(object sender, EventArgs e)
{
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
Response.Redirect("~/AddData.aspx");
}
else
{
Response.Redirect("~/ViewData.aspx");
}
}
This will sure work.
For your question as asked
Columns(3).Insert
Range("c1:c4") = Application.Transpose(Array("Loc", "uk", "us", "nj"))
If you had a way of automatically looking up the data (ie matching uk against employer id) then you could do that in VBA
I know that this post is a bit old but incase anyone finds it still relevant you might want to check out the free geocoding services offered by USC College. This does included address validation via ajax and static calls. The only catch is that they request a link back and only offer allotments of 2500 calls. More than fair. https://webgis.usc.edu/Services/AddressValidation/Default.aspx
In an attempt to optimize memory and performance dialogs in Android are asynchronous (they are also managed for this reason). Comming from the Windows world, you are used to modal dialogs. Android dialogs are modal but more like non-modal when it comes to execution. Execution does not stop after displaying a dialog.
The best description of Dialogs in Android I have seen is in "Pro Android" http://www.apress.com/book/view/1430215968
This is not a perfect explanation but it should help you to wrap your brain around the differences between Dialogs in Windows and Android. In Windows you want to do A, ask a question with a dialog, and then do B or C. In android design A with all the code you need for B and C in the onClick() of the OnClickListener(s) for the dialog. Then do A and launch the dialog. You’re done with A! When the user clicks a button B or C will get executed.
Windows
-------
A code
launch dialog
user picks B or C
B or C code
done!
Android
-------
OnClick for B code (does not get executed yet)
OnClick for C code (does not get executed yet)
A code
launch dialog
done!
user picks B or C
{% for i in yourlist %}
{% for k,v in i.items() %}
{# do what you want here #}
{% endfor %}
{% endfor %}
C++ uses structs primarily for 1) backwards compatibility with C and 2) POD types. C structs do not have methods, inheritance or visibility.
For Symfony 2.7 and newer
See this answer here.
1st working option
{{ app.request.scheme ~'://' ~ app.request.httpHost ~ asset('bundles/acmedemo/images/search.png') }}
2nd working option - preferred
Just made a quick test with a clean new Symfony copy. There is also another option which combines scheme and httpHost:
{{ app.request.getSchemeAndHttpHost() ~ asset('bundles/acmedemo/images/search.png') }}
{# outputs #}
{# http://localhost/Symfony/web/bundles/acmedemo/css/demo.css #}
double *ptr = malloc(sizeof(double *) * TIME); /* ... */ for(tcount = 0; tcount <= TIME; tcount++) ^^
<=
to <
or alloc
SIZE + 1
elementsmalloc
is wrong, you'll want sizeof(double)
instead of
sizeof(double *)
ouah
comments, although not directly linked to your corruption problem, you're using *(ptr+tcount)
without initializing itptr[tcount]
instead of *(ptr + tcount)
malloc
+ free
since you already know SIZE
<pre><form name="myform" method="post" enctype="multipart/form-data">
<input type="text" id="name" name="name" />
<input type="submit"/>
</form></pre>
<script language="JavaScript" type="text/javascript">
var frmvalidator = new Validator("myform");
frmvalidator.EnableFocusOnError(false);
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("name","req","Plese Enter Name");
</script>
Note: before using the code above you have to add the gen_validatorv31.js
file.
I just created a simple timer using the MVP pattern (however it may be overkill for that simple project). It has quit, start/pause and a stop button. Time is displayed in HH:MM:SS format. Time counting is implemented using a thread that is running several times a second and the difference between the time the timer has started and the current time.
Use this code to change password to text and vice versa. This code perfectly worked for me. Try this..
EditText paswrd=(EditText)view.findViewById(R.id.paswrd);
CheckBox showpass=(CheckBox)view.findViewById(R.id.showpass);
showpass.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(((CheckBox)v).isChecked()){
paswrd.setInputType(InputType.TYPE_CLASS_TEXT);
}else{
paswrd.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_PASSWORD);
}
}
});
Extending on pkozlowski.opensource's answer and using javascript array's
builtin filter method a prettified solution could be this:
.filter('weDontLike', function(){
return function(items, name){
return items.filter(function(item) {
return item.name != name;
});
};
});
Here's the jsfiddle link.
More on Array filter here.
You have to put all your assets in app/public
folder, and to access them from your views you can use asset()
helper method.
Ex. you can retrieve assets/images/image.png
in your view as following:
<img src="{{asset('assets/images/image.png')}}">
By default, hibernate framework will immediately return id , when you are trying to save the entity using Save(entity)
method. There is no need to do it explicitly.
In case your primary key is int
you can use below code:
int id=(Integer) session.save(entity);
In case of string use below code:
String str=(String)session.save(entity);
Within the range 0 = c < 128, yes the '
is the only difference for CPython 2.6.
>>> set(unichr(c).encode('unicode_escape') for c in range(128)) - set(chr(c).encode('string_escape') for c in range(128))
set(["'"])
Outside of this range the two types are not exchangeable.
>>> '\x80'.encode('string_escape')
'\\x80'
>>> '\x80'.encode('unicode_escape')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can’t decode byte 0x80 in position 0: ordinal not in range(128)
>>> u'1'.encode('unicode_escape')
'1'
>>> u'1'.encode('string_escape')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: escape_encode() argument 1 must be str, not unicode
On Python 3.x, the string_escape
encoding no longer exists, since str
can only store Unicode.
Guess you just missed the find method in the docs:
my_array.find {|e| e.satisfies_condition? }
A slight variation using a dictionary for greater flexibility (e.g. sort, dedup):
import os
from PyPDF2 import PdfFileMerger
# use dict to sort by filepath or filename
file_dict = {}
for subdir, dirs, files in os.walk("<dir>"):
for file in files:
filepath = subdir + os.sep + file
# you can have multiple endswith
if filepath.endswith((".pdf", ".PDF")):
file_dict[file] = filepath
# use strict = False to ignore PdfReadError: Illegal character error
merger = PdfFileMerger(strict=False)
for k, v in file_dict.items():
print(k, v)
merger.append(v)
merger.write("combined_result.pdf")
Moment.js is pretty big library to use for a single use case. I recommend using date-fns
instead. It offers basically the most functionality of Moment.js with a much smaller bundle size and many formatting options
.
import format from 'date-fns/format'
format('2013-03-10T02:00:00Z', 'YYYY-MM-DD'); // 2013-03-10, YYYY-MM-dd for 2.x
One thing to note is that, since it's the ISO 8601 time format, the browser generally converts from UTC time to local timezone. Though this is simple use case where you can probably do '2013-03-10T02:00:00Z'.substring(0, 10);
.
For more complex conversions date-fns
is the way to go.
Run command. You will get installed extentions:
php -r "print_r(get_loaded_extensions());"
Or run this command to get all module install and uninstall with version
dpkg -l | grep php5
I found this answer on another forum, works perfect. No problems with finding 1 if there is also a 10
WHERE tablename REGEXP "(^|,)@search(,|$)"
As of this writing I believe this can be accomplished with the IClaimsTransformation interface in asp.net core 2 and above. I just implemented a proof of concept which is sharable enough to post here.
public class PrivilegesToClaimsTransformer : IClaimsTransformation
{
private readonly IPrivilegeProvider privilegeProvider;
public const string DidItClaim = "http://foo.bar/privileges/resolved";
public PrivilegesToClaimsTransformer(IPrivilegeProvider privilegeProvider)
{
this.privilegeProvider = privilegeProvider;
}
public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
if (principal.Identity is ClaimsIdentity claimer)
{
if (claimer.HasClaim(DidItClaim, bool.TrueString))
{
return principal;
}
var privileges = await this.privilegeProvider.GetPrivileges( ... );
claimer.AddClaim(new Claim(DidItClaim, bool.TrueString));
foreach (var privilegeAsRole in privileges)
{
claimer.AddClaim(new Claim(ClaimTypes.Role /*"http://schemas.microsoft.com/ws/2008/06/identity/claims/role" */, privilegeAsRole));
}
}
return principal;
}
}
To use this in your Controller just add an appropriate [Authorize(Roles="whatever")]
to your methods.
[HttpGet]
[Route("poc")]
[Authorize(Roles = "plugh,blast")]
public JsonResult PocAuthorization()
{
var result = Json(new
{
when = DateTime.UtcNow,
});
result.StatusCode = (int)HttpStatusCode.OK;
return result;
}
In our case every request includes an Authorization header that is a JWT. This is the prototype and I believe we will do something super close to this in our production system next week.
Future voters, consider the date of writing when you vote. As of today, this works on my machine.
™ You will probably want more error handling and logging on your implementation.
A Record lets you create a new type from a Union. The values in the Union are used as attributes of the new type.
For example, say I have a Union like this:
type CatNames = "miffy" | "boris" | "mordred";
Now I want to create an object that contains information about all the cats, I can create a new type using the values in the CatName Union as keys.
type CatList = Record<CatNames, {age: number}>
If I want to satisfy this CatList, I must create an object like this:
const cats:CatList = {
miffy: { age:99 },
boris: { age:16 },
mordred: { age:600 }
}
You get very strong type safety:
I used this recently to create a Status component. The component would receive a status prop, and then render an icon. I've simplified the code quite a lot here for illustrative purposes
I had a union like this:
type Statuses = "failed" | "complete";
I used this to create an object like this:
const icons: Record<
Statuses,
{ iconType: IconTypes; iconColor: IconColors }
> = {
failed: {
iconType: "warning",
iconColor: "red"
},
complete: {
iconType: "check",
iconColor: "green"
};
I could then render by destructuring an element from the object into props, like so:
const Status = ({status}) => <Icon {...icons[status]} />
If the Statuses union is later extended or changed, I know my Status component will fail to compile and I'll get an error that I can fix immediately. This allows me to add additional error states to the app.
Note that the actual app had dozens of error states that were referenced in multiple places, so this type safety was extremely useful.
Just as you would with a CheckBox
RadioButton rb;
rb = (RadioButton) findViewById(R.id.rb);
rb.isChecked();
You could build your form using FormBuilder as it let you more flexible way to configure form.
export class MyComp {
form: ControlGroup;
constructor(@Inject()fb: FormBuilder) {
this.form = fb.group({
foo: ['', MyValidators.regex(/^(?!\s|.*\s$).*$/)]
});
}
Then in your template :
<input type="text" ngControl="foo" />
<div *ngIf="!form.foo.valid">Please correct foo entry !</div>
You can also customize ng-invalid CSS class.
As there is actually no validators for regex, you have to write your own. It is a simple function that takes a control in input, and return null if valid or a StringMap if invalid.
export class MyValidators {
static regex(pattern: string): Function {
return (control: Control): {[key: string]: any} => {
return control.value.match(pattern) ? null : {pattern: true};
};
}
}
Hope that it help you.
The most visible immediate difference in older versions of Java would be the memory allocated to a -client
as opposed to a -server
application. For instance, on my Linux system, I get:
$ java -XX:+PrintFlagsFinal -version 2>&1 | grep -i -E 'heapsize|permsize|version'
uintx AdaptivePermSizeWeight = 20 {product}
uintx ErgoHeapSizeLimit = 0 {product}
uintx InitialHeapSize := 66328448 {product}
uintx LargePageHeapSizeThreshold = 134217728 {product}
uintx MaxHeapSize := 1063256064 {product}
uintx MaxPermSize = 67108864 {pd product}
uintx PermSize = 16777216 {pd product}
java version "1.6.0_24"
as it defaults to -server
, but with the -client
option I get:
$ java -client -XX:+PrintFlagsFinal -version 2>&1 | grep -i -E 'heapsize|permsize|version'
uintx AdaptivePermSizeWeight = 20 {product}
uintx ErgoHeapSizeLimit = 0 {product}
uintx InitialHeapSize := 16777216 {product}
uintx LargePageHeapSizeThreshold = 134217728 {product}
uintx MaxHeapSize := 268435456 {product}
uintx MaxPermSize = 67108864 {pd product}
uintx PermSize = 12582912 {pd product}
java version "1.6.0_24"
so with -server
most of the memory limits and initial allocations are much higher for this java
version.
These values can change for different combinations of architecture, operating system and jvm version however. Recent versions of the jvm have removed flags and re-moved many of the distinctions between server and client.
Remember too that you can see all the details of a running jvm
using jvisualvm
. This is useful if you have users who or modules which set JAVA_OPTS
or use scripts which change command line options. This will also let you monitor, in real time, heap and permgen space usage along with lots of other stats.
check this
<input class="gender" type="radio" name="sex" value="male">Male
<br>
<input class="gender" type="radio" name="sex" value="female">Female
<script type="text/javascript">
$(document).ready(function () {
$(".gender").change(function () {
var val = $('.gender:checked').val();
alert(val);
});
});
</script>
For live video conferencing you can't ignore the need of a streaming server.
Yes, flash will let you display video from a webcam within the local flash control, but that won't let you then send that video over the network - for that you need a streaming server to send it to.
If you're going to build something like this it's prudent to think about how you're going to host the video from a very early stage as it will influence how you build the application. Flash/Flex/Silverlight/Windows Media....etc....
I'm not sure what jQuery api you're looking at, but you should only have to specify id
.
$('#thumb').removeAttr('id');
You can use the get(index) method to access an element from a List.
Sets, by definition, simply contain elements and have no particular order. Therefore, there is no "first" element you can get, but it is possible to iterate through it using iterator (using the for each loop) or convert it to an array using the toArray() method.
Had the same problem, it turned out it was the WindowsFirewall blocking connections. Try to disable WindowsFirewall for a while to see if helps and if it is the problem open ports as needed.
If you have the column it's very easy.
Using the designer, you could set the column as an identity (1,1): right click on the table ? design ? in part left (right click) ? properties ? in identity columns, select #column.
Properties:
Identity column:
Here's a function to upscale or downscale an image by desired width or height while maintaining aspect ratio
# Resizes a image and maintains aspect ratio
def maintain_aspect_ratio_resize(image, width=None, height=None, inter=cv2.INTER_AREA):
# Grab the image size and initialize dimensions
dim = None
(h, w) = image.shape[:2]
# Return original image if no need to resize
if width is None and height is None:
return image
# We are resizing height if width is none
if width is None:
# Calculate the ratio of the height and construct the dimensions
r = height / float(h)
dim = (int(w * r), height)
# We are resizing width if height is none
else:
# Calculate the ratio of the width and construct the dimensions
r = width / float(w)
dim = (width, int(h * r))
# Return the resized image
return cv2.resize(image, dim, interpolation=inter)
Usage
import cv2
image = cv2.imread('1.png')
cv2.imshow('width_100', maintain_aspect_ratio_resize(image, width=100))
cv2.imshow('width_300', maintain_aspect_ratio_resize(image, width=300))
cv2.waitKey()
Using this example image
Simply downscale to width=100
(left) or upscale to width=300
(right)
Seems like the order of the linking flags was not an issue in older versions of gcc. Eg gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-16)
comes with Centos-6.7 happy with linker option before inputfile; but gcc with ubuntu 16.04 gcc (Ubuntu 5.3.1-14ubuntu2.1) 5.3.1 20160413
does not allow.
Its not the gcc version alone, I has got something to with the distros
The problem seems to be a mis-placed )
. In your sample you have the %
outside of the print()
, you should move it inside:
Use this:
print("%s. %s appears %s times." % (str(i), key, str(wordBank[key])))
You can use the SelectedItem
property to get the currently selected object, which you can then cast into the correct type. For instance, if your DataGrid
is bound to a collection of Customer
objects you could do this:
Customer customer = (Customer)myDataGrid.SelectedItem;
Alternatively you can bind SelectedItem
to your source class or ViewModel
.
<Grid DataContext="MyViewModel">
<DataGrid ItemsSource="{Binding Path=Customers}"
SelectedItem="{Binding Path=SelectedCustomer, Mode=TwoWay}"/>
</Grid>
In my case, I want to exclude an existing file. Only modifying .gitignore not work. I followed these steps:
git rm --cached dirToFile/file.php
vim .gitignore
git commit -a
In this way, I cleaned from cache the file that I wanted to exclude and after I added it to .gitignore.
This is the way to dynamically set the value
var jsonVariable = {};
for (var i = 1; i < 3; i++) {
var jsonKey = i + 'name';
jsonVariable[jsonKey] = 'name' + i;
}
Problem seems to be because you're cloning from HTTPS and not SSH. I tried all the other solutions here but was still experiencing problems. This did it for me.
Using the osxkeychain helper
like so:
Find out if you have it installed.
git credential-osxkeychain
If it's not installed, you'll be prompted to download it as part of Xcode Command Line Tools.
If it is installed, tell Git to use osxkeychain helper
using the global credential.helper
config:
git config --global credential.helper osxkeychain
The next time you clone an HTTPS url, you'll be prompted for the username/password, and to grant access to the OSX keychain. After you do this the first time, it should be saved in your keychain and you won't have to type it in again.
This takes the last. Not the maximum though:
In [10]: df.drop_duplicates(subset='A', keep="last")
Out[10]:
A B
1 1 20
3 2 40
4 3 10
You can do also something like:
In [12]: df.groupby('A', group_keys=False).apply(lambda x: x.loc[x.B.idxmax()])
Out[12]:
A B
A
1 1 20
2 2 40
3 3 10
PDB is a debug information file used by Visual Studio. These are system DLLs, which you don't have debug symbols for. Go to Tools->Options->Debugging->Symbols and select checkbox "Microsoft Symbol Servers", Visual Studio will download PDBs automatically. Or you may just ignore these warnings if you don't need to see correct call stack in these modules.
I use <br>
in a CDATA
tag.
As an example, my strings.xml file contains an item like this:
<item><![CDATA[<b>My name is John</b><br>Nice to meet you]]></item>
and prints
My name is John
Nice to meet you
They are the same. But I suggest "while(ture)" which has best representation.
It's indeed almost a duplicate. I guess the regex you're looking for is
(?!foo).*
There are two major purposes of hashing functions:
It's impossible to recommend a hash without knowing what you're using it for.
If you're just making a hash table in a program, then you don't need to worry about how reversible or hackable the algorithm is... SHA-1 or AES is completely unnecessary for this, you'd be better off using a variation of FNV. FNV achieves better dispersion (and thus fewer collisions) than a simple prime mod like you mentioned, and it's more adaptable to varying input sizes.
If you're using the hashes to hide and authenticate public information (such as hashing a password, or a document), then you should use one of the major hashing algorithms vetted by public scrutiny. The Hash Function Lounge is a good place to start.
foreach(range('B','G') as $columnID)
{
$objPHPExcel->getActiveSheet()->getColumnDimension($columnID)->setAutoSize(true);
}
There is no clean way to do this and like @Nick mentioned above it might just be easier to use the old school way of loops as then you can control this. But if you want to stick with what you got there is one way you could handle this. I'm sure I will get some heat for this one. But...
One way you could do what you want without an if statement is to raise an error and wrap your loop with a try/catch block:
try{
$(sentences).each(function() {
var s = this;
alert(s);
$(words).each(function(i) {
if (s.indexOf(this) > -1)
{
alert('found ' + this);
throw "Exit Error";
}
});
});
}
catch (e)
{
alert(e)
}
Ok, let the thrashing begin.
You need to use : "$@"
(WITH the quotes) or "${@}"
(same, but also telling the shell where the variable name starts and ends).
(and do NOT use : $@
, or "$*"
, or $*
).
ex:
#testscript1:
echo "TestScript1 Arguments:"
for an_arg in "$@" ; do
echo "${an_arg}"
done
echo "nb of args: $#"
./testscript2 "$@" #invokes testscript2 with the same arguments we received
I'm not sure I understood your other requirement ( you want to invoke './testscript2' in single quotes?) so here are 2 wild guesses (changing the last line above) :
'./testscript2' "$@" #only makes sense if "/path/to/testscript2" containes spaces?
./testscript2 '"some thing" "another"' "$var" "$var2" #3 args to testscript2
Please give me the exact thing you are trying to do
edit: after his comment saying he attempts tesscript1 "$1" "$2" "$3" "$4" "$5" "$6" to run : salt 'remote host' cmd.run './testscript2 $1 $2 $3 $4 $5 $6'
You have many levels of intermediate: testscript1 on host 1, needs to run "salt", and give it a string launching "testscrit2" with arguments in quotes...
You could maybe "simplify" by having:
#testscript1
#we receive args, we generate a custom script simulating 'testscript2 "$@"'
theargs="'$1'"
shift
for i in "$@" ; do
theargs="${theargs} '$i'"
done
salt 'remote host' cmd.run "./testscript2 ${theargs}"
if THAt doesn't work, then instead of running "testscript2 ${theargs}", replace THE LAST LINE above by
echo "./testscript2 ${theargs}" >/tmp/runtestscript2.$$ #generate custom script locally ($$ is current pid in bash/sh/...)
scp /tmp/runtestscript2.$$ user@remotehost:/tmp/runtestscript2.$$ #copy it to remotehost
salt 'remotehost' cmd.run "./runtestscript2.$$" #the args are inside the custom script!
ssh user@remotehost "rm /tmp/runtestscript2.$$" #delete the remote one
rm /tmp/runtestscript2.$$ #and the local one
You can't implicitly return with an if
, you would need the braces:
let adults = family.filter(person => { if (person.age > 18) return person} );
It can be simplified though:
let adults = family.filter(person => person.age > 18);
The function returns a FileStream
object. So you could use it's return value to open your StreamWriter
or close it using the proper method of the object:
File.Create(myPath).Close();
Got the same error, CHECK THIS : MINOR SILLY MISTAKE
check findviewbyid(R.id.yourID); If you have put the id correct or not.
I believe that is is a move operator. operator=
is the assignment operator, say vector x = vector y
. The clear()
function call sounds like as if it is deleting the contents of the vector to prevent a memory leak. The operator returns a pointer to the new vector.
This way,
std::vector<int> a(100, 10);
std::vector<int> b = a;
for(unsigned int i = 0; i < b.size(); i++)
{
std::cout << b[i] << ' ';
}
Even though we gave vector a values, vector b has the values. It's the magic of the operator=()
!
In Git, to "fast forward" means to update the HEAD
pointer in such a way that its new value is a direct descendant of the prior value. In other words, the prior value is a parent, or grandparent, or grandgrandparent, ...
Fast forwarding is not possible when the new HEAD
is in a diverged state relative to the stream you want to integrate. For instance, you are on master
and have local commits, and git fetch
has brought new upstream commits into origin/master
. The branch now diverges from its upstream and cannot be fast forwarded: your master
HEAD
commit is not an ancestor of origin/master
HEAD
. To simply reset master
to the value of origin/master
would discard your local commits. The situation requires a rebase or merge.
If your local master
has no changes, then it can be fast-forwarded: simply updated to point to the same commit as the latestorigin/master
. Usually, no special steps are needed to do fast-forwarding; it is done by merge
or rebase
in the situation when there are no local commits.
Is it ok to assume that fast-forward means all commits are replayed on the target branch and the HEAD is set to the last commit on that branch?
No, that is called rebasing, of which fast-forwarding is a special case when there are no commits to be replayed (and the target branch has new commits, and the history of the target branch has not been rewritten, so that all the commits on the target branch have the current one as their ancestor.)
All of the full-featured Java IDE's are good and share all of the same concepts and main features. If you can find your way around one you can probably do the same for any other without much trouble.
EDIT: Google gave us a wonderful gift with the new and free AndroidStudio is very good. I highly recommend it over Eclipse.
$.getJSON
is an asynchronous request, meaning the code will continue to run even though the request is not yet done. You should trigger the second request when the first one is done, one of the choices you seen already in ComFreek's answer.
Alternatively you could use jQuery's $.when/.then(), similar to this:
var input = "netuetamundis"; var sID; $(document).ready(function () { $.when($.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/" + input + "?api_key=API_KEY_HERE", function () { obj = name; sID = obj.id; console.log(sID); })).then(function () { $.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.2/stats/by-summoner/" + sID + "/summary?api_key=API_KEY_HERE", function (stats) { console.log(stats); }); }); });
This would be more open for future modification and separates out the responsibility for the first call to know about the second call.
The first call can simply complete and do it's own thing not having to be aware of any other logic you may want to add, leaving the coupling of the logic separated.
I got this message when trying to access values of a null valued object.
sName = myObj.Name;
this will produce error. First you should check if object not null
if(myObj != null)
sName = myObj.Name;
This works.
CommonJS is more than that - it's a project to define a common API and ecosystem for JavaScript. One part of CommonJS is the Module specification. Node.js and RingoJS are server-side JavaScript runtimes, and yes, both of them implement modules based on the CommonJS Module spec.
AMD (Asynchronous Module Definition) is another specification for modules. RequireJS is probably the most popular implementation of AMD. One major difference from CommonJS is that AMD specifies that modules are loaded asynchronously - that means modules are loaded in parallel, as opposed to blocking the execution by waiting for a load to finish.
AMD is generally more used in client-side (in-browser) JavaScript development due to this, and CommonJS Modules are generally used server-side. However, you can use either module spec in either environment - for example, RequireJS offers directions for running in Node.js and browserify is a CommonJS Module implementation that can run in the browser.
To split a string with a delimiter with GNU sed you say:
sed 's/delimiter/\n/g' # GNU sed
For example, to split using :
as a delimiter:
$ sed 's/:/\n/g' <<< "he:llo:you"
he
llo
you
Or with a non-GNU sed:
$ sed $'s/:/\\\n/g' <<< "he:llo:you"
he
llo
you
In this particular case, you missed the g
after the substitution. Hence, it is just done once. See:
$ echo "string1:string2:string3:string4:string5" | sed s/:/\\n/g
string1
string2
string3
string4
string5
g
stands for g
lobal and means that the substitution has to be done globally, that is, for any occurrence. See that the default is 1 and if you put for example 2, it is done 2 times, etc.
All together, in your case you would need to use:
sed 's/:/\\n/g' ~/Desktop/myfile.txt
Note that you can directly use the sed ... file
syntax, instead of unnecessary piping: cat file | sed
.
for entry in "$search_dir"/* "$work_dir"/*
do
if [ -f "$entry" ];then
echo "$entry"
fi
done
runAllManagedModulesForAllRequests=true
is actually a real bad solution. This increased the load time of my application by 200%. The better solution is to manually remove and add the session object and to avoid the run all managed modules attribute all together.
The coordinate system on the screen is left-handed, i.e. the x coordinate increases from left to right and the y coordinate increases from top to bottom. The origin, O(0, 0) is at the upper left corner of the screen.
A clockwise rotation around the origin of a point with coordinates (x, y) is given by the following equations:
where (x', y') are the coordinates of the point after rotation and angle theta, the angle of rotation (needs to be in radians, i.e. multiplied by: PI / 180).
To perform rotation around a point different from the origin O(0,0), let's say point A(a, b) (pivot point). Firstly we translate the point to be rotated, i.e. (x, y) back to the origin, by subtracting the coordinates of the pivot point, (x - a, y - b). Then we perform the rotation and get the new coordinates (x', y') and finally we translate the point back, by adding the coordinates of the pivot point to the new coordinates (x' + a, y' + b).
Following the above description:
Using your function prototype: (x, y) -> (p.x, p.y); (a, b) -> (cx, cy); theta -> angle:
POINT rotate_point(float cx, float cy, float angle, POINT p){
return POINT(cos(angle) * (p.x - cx) - sin(angle) * (p.y - cy) + cx,
sin(angle) * (p.x - cx) + cos(angle) * (p.y - cy) + cy);
}
I tested your answers and only Stefan Reich's one worked for me. Although I couldn't manage to restore the window to its previous state (maximized/normal). I found this mutation better:
view.setState(java.awt.Frame.ICONIFIED);
view.setState(java.awt.Frame.NORMAL);
That is setState
instead of setExtendedState
.
By default hibernate lazily loads the collections (relationships) which means whenver you use the collection
in your code(here comments
field
in Topic
class)
the hibernate gets that from database, now the problem is that you are getting the collection in your controller (where the
JPA session is closed).This is the line of code that causes the exception
(where you are loading the comments
collection):
Collection<Comment> commentList = topicById.getComments();
You are getting "comments" collection (topic.getComments()) in your controller(where JPA session
has ended) and that causes the exception. Also if you had got
the comments
collection in your jsp file like this(instead of getting it in your controller):
<c:forEach items="topic.comments" var="item">
//some code
</c:forEach>
You would still have the same exception for the same reason.
Because you just can have only two collections with the FetchType.Eager
(eagerly fetched collection) in an Entity class and because lazy loading is more
efficient than eagerly loading, I think this way of solving your problem is better than just changing the FetchType
to eager:
If you want to have collection lazy initialized, and also make this work,
it is better to add this snippet of code to your web.xml
:
<filter>
<filter-name>SpringOpenEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SpringOpenEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
What this code does is that it will increase the length of your JPA session
or as the documentation says, it is used "to allow for lazy loading in web views despite the original transactions already being completed."
so
this way the JPA session will be open a bit longer and because of that
you can lazily load collections in your jsp files and controller classes.
Version I am using
Update 5th May 2012
Jeff Smith has blogged showing, what I believe is the superior method to get CSV output from SQL Developer. Jeff's method is shown as Method 1 below:
Method 1
Add the comment /*csv*/
to your SQL query and run the query as a script (using F5 or the 2nd execution button on the worksheet toolbar)
That's it.
Method 2
Run a query
Right click and select unload.
Update. In Sql Developer Version 3.0.04 unload has been changed to export Thanks to Janis Peisenieks for pointing this out
Revised screen shot for SQL Developer Version 3.0.04
From the format drop down select CSV
And follow the rest of the on screen instructions.
In case not solved yet. Your iptables say:
state RELATED,ESTABLISHED
Which means that it lets pass only connections already established... that's established by you, not by remote machines. Then you can see exceptions to this in the next rules:
state NEW tcp dpt:ssh
Which counts only for ssh, so you should add a similar rule/line for http, which you can do like this:
state NEW tcp dpt:80
Which you can do like this:
sudo iptables -I INPUT 4 -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT
(In this case I am choosing to add the new rule in the fourth line)
Remember that after editing the file you should save it like this:
sudo /etc/init.d/iptables save
I had the same issue as above and I am using PostgreSQL 10.5. I tried everything as above but nothing seems to be working.
Then I closed the pgadmin and opened a session for the PSQL terminal. Logged into the PSQL and connected to the database and schema respectively :
\c <DATABASE_NAME>;
set search_path to <SCHEMA_NAME>;
Then, restarted the pgadmin console and then I was able to work without issue in the query-tool of the pagadmin.
You have two ways:
First go to the particular path of Android SDK:
1) Open your command prompt and traverse to the platform-tools directory through it such as
$ cd Frameworks\Android-Sdk\platform-tools
2) Run your adb commands now such as to know that your adb is working properly :
$ adb devices OR adb logcat OR simply adb
Second way is :
1) Right click on your My Computer.
2) Open Environment variables.
3) Add new variable to your System PATH variable(Add if not exist otherwise no need to add new variable if already exist).
4) Add path of platform-tools directory to as value of this variable such as C:\Program Files\android-sdk\platform-tools.
5) Restart your computer once.
6) Now run the above adb commands such adb devices or other adb commands from anywhere in command prompt.
Also on you can fire a command on terminal setx PATH "%PATH%;C:\Program Files\android-sdk\platform-tools"
-z
string is null, that is, has zero length
String='' # Zero-length ("null") string variable.
if [ -z "$String" ]
then
echo "\$String is null."
else
echo "\$String is NOT null."
fi # $String is null.
I modified Zack's answer since I wanted spaces and interpolation but not newlines and used:
%W[
It's a nice day "#{name}"
for a walk!
].join(' ')
where name = 'fred'
this produces It's a nice day "fred" for a walk!
This is a variant of Pedro Lobito answer using How to loop through a directory recursively to delete files with certain extensions teachings:
shopt -s globstar
root_directory="."
for zip_file_name in **/*.{zip,sublime\-package}; do
directory_name=`echo $zip_file_name | sed 's/\.\(zip\|sublime\-package\)$//'`
printf "Unpacking zip file \`$root_directory/$zip_file_name\`...\n"
if [ -f "$root_directory/$zip_file_name" ]; then
mkdir -p "$root_directory/$directory_name"
unzip -o -q "$root_directory/$zip_file_name" -d "$directory_name"
# Some files have the executable flag and were not being deleted because of it.
# chmod -x "$root_directory/$zip_file_name"
# rm -f "$root_directory/$zip_file_name"
fi
done
I started getting weird ConftestImportFailure: ImportError('No module named ...
errors when I had accidentally added __init__.py
file to my src directory (which was not supposed to be a Python package, just a container of all source).
To resolve external dependencies within project. below things are important..
1. The compiler should know that where are header '.h' files located in workspace.
2. The linker able to find all specified all '.lib' files & there names for current project.
So, Developer has to specify external dependencies for Project as below..
1. Select Project in Solution explorer.
2 . Project Properties -> Configuration Properties -> C/C++ -> General
specify all header files in "Additional Include Directories".
3. Project Properties -> Configuration Properties -> Linker -> General
specify relative path for all lib files in "Additional Library Directories".
In python, bool(sequence)
is False
if the sequence is empty. Since strings are sequences, this will work:
cookie = ''
if cookie:
print "Don't see this"
else:
print "You'll see this"
You will need to install a local mailserver in order to do this. If you want to send it to external e-mail addresses, it might end up in unwanted e-mails or it may not arrive at all.
A good mailserver which I use (I use it on Linux, but it's also available for Windows) is Axigen: http://www.axigen.com/mail-server/download/
You might need some experience with mailservers to install it, but once it works, you can do anything you want with it.
I believe enum have a .name() in its API, pretty simple to use like this example:
private int security;
public String security(){ return Security.values()[security].name(); }
public void setSecurity(int security){ this.security = security; }
private enum Security {
low,
high
}
With this you can simply call
yourObject.security()
and it returns high/low as String, in this example
additionally to sangam
code
if (chNode["innerNode"]["innermostNode"]==null)
return true; //node *parentNode*/innerNode/innermostNode exists
Step 1: open your mysql workbench application select table. choose image cell right click select "Open value in Editor"
Step 2: click on the load button and choose image file
Step 3:then click apply button
Step 4: Then apply the query to save the image .Don't forgot image data type is "BLOB". Step 5: You can can check uploaded image
On Fedora you can use
# yum install foo
as long as Fedora has an existing package for the module.
In Python 2 dict.keys() return a list, whereas in Python 3 it returns a generator.
You could only iterate over it's values else you may have to explicitly convert it to a list i.e. pass it to a list function.
I wasn't happy with AppCompat, so I wrote my own CardView and backported ripples. Here it's running on Galaxy S with Gingerbread, so it's definitely possible.
For more details check the source code.
Doesn't allow duplicates in the sense, It allow to add you but it does'nt care about this key already have a value or not. So at present for one key there will be only one value
It silently overrides the value
for null
key. No exception.
When you try to get, the last inserted value with null
will be return.
That is not only with null
and for any key.
Have a quick example
Map m = new HashMap<String, String>();
m.put("1", "a");
m.put("1", "b"); //no exception
System.out.println(m.get("1")); //b
Use the logging built-in library module instead of printing.
You create a Logger
object (say logger
), and then after that, whenever you insert a debug print, you just put:
logger.debug("Some string")
You can use logger.setLevel
at the start of the program to set the output level. If you set it to DEBUG, it will print all the debugs. Set it to INFO or higher and immediately all of the debugs will disappear.
You can also use it to log more serious things, at different levels (INFO, WARNING and ERROR).
If you have more than one column to be converted you can do the following:
df[["col1", "col2", "col3"]] = df[["col1", "col2", "col3"]].apply(pd.to_datetime)
Also, you can use exists
select case when exists (select 1 from table)
then 'contains rows'
else 'doesnt contain rows'
end
or to check if there are child rows for a particular record :
select * from Table t1
where exists(
select 1 from ChildTable t2
where t1.id = t2.parentid)
or in a procedure
if exists(select 1 from table)
begin
-- do stuff
end
document.cookie = "cookie_name=cookie_value; max-age=31536000; path=/";
Will set the value for a year.
To retrieve an item from your config file, use the following function:
$this->config->item('item name');
Where item name is the $config array index you want to retrieve. For example, to fetch your language choice you'll do this:
$lang = $this->config->item('language');
The function returns FALSE (boolean) if the item you are trying to fetch does not exist.
If you are using the second parameter of the $this->config->load function in order to assign your config items to a specific index you can retrieve it by specifying the index name in the second parameter of the $this->config->item() function. Example:
// Loads a config file named blog_settings.php and assigns it to an index named "blog_settings"
$this->config->load('blog_settings', TRUE);
// Retrieve a config item named site_name contained within the blog_settings array
$site_name = $this->config->item('site_name', 'blog_settings');
// An alternate way to specify the same item:
$blog_config = $this->config->item('blog_settings');
$site_name = $blog_config['site_name'];
You're actually supposed to use $("#terms").dialog({ autoOpen: false });
to initialize it.
Then you can use $('#terms').dialog('open');
to open the dialog, and $('#terms').dialog('close');
to close it.
It may be that it's not loading the template you expect. I added a new class that inherited from UpdateView
- I thought it would automatically pick the template from what I named my class, but it actually loaded it based on the model
property on the class, which resulted in another (wrong) template being loaded. Once I explicitly set template_name
for the new class, it worked fine.
Try this:
while True:
# main program
while True:
answer = str(input('Run again? (y/n): '))
if answer in ('y', 'n'):
break
print("invalid input.")
if answer == 'y':
continue
else:
print("Goodbye")
break
The inner while loop loops until the input is either 'y'
or 'n'
. If the input is 'y'
, the while loop starts again (continue
keyword skips the remaining code and goes straight to the next iteration). If the input is 'n'
, the program ends.
The Transact-SQL control-of-flow language keywords are:
BEGIN
...END
BREAK
CONTINUE
GOTO
label
IF
...ELSE
RETURN
THROW
TRY
...CATCH
WAITFOR
WHILE
The file name u used spring-dispatcher-servlet.xml
kindly check in web.xml
servlet name as spring-dispatcher at both tag <servlet> and <servlet-mapping>
in your case it should be
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class></servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>spring-dispatcher</servlet-name>
<url-pattern></url-pattern>
</servlet-mapping>
I found the easiest way to check if installed was to:
cmd
, then OK)powershell
then hit return. You should then get the PowerShell PS
prompt:C:\Users\MyUser>powershell
Windows PowerShell
Copyright (C) 2009 Microsoft Corporation. All rights reserved.
PS C:\Users\MyUser>
You can then check the version from the PowerShell prompt by typing $PSVersionTable.PSVersion
:
PS C:\Users\MyUser> $PSVersionTable.PSVersion
Major Minor Build Revision
----- ----- ----- --------
2 0 -1 -1
PS C:\Users\MyUser>
Type exit
if you want to go back to the command prompt (exit
again if you want to also close the command prompt).
To run scripts, see http://ss64.com/ps/syntax-run.html.
$(this).parent().parent().attr('id');
Is how you would get the id of the parent's parent.
EDIT:
$(this).closest('ul').attr('id');
Is a more foolproof solution for your case.
Mi solution :
pw = "1321";
if (pw.length() < 16){
for(int x = pw.length() ; x < 16 ; x++){
pw += "*";
}
}
The output :
1321************
I have tried several solutions today, the one working best for me is Jo-Geek/jQuery-ResizableColumns. Is is very simple, yet it handles tables placed in flex containers, which many of the other ones fail with.
<table class="resizable">
</table>
$('table.resizable').resizableColumns();
$(function() {_x000D_
$('table.resizable').resizableColumns();_x000D_
})
_x000D_
body {_x000D_
margin: 0px;_x000D_
}_x000D_
_x000D_
table {_x000D_
width: 100%;_x000D_
table-layout: fixed;_x000D_
border-collapse: collapse;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://jo-geek.github.io/jQuery-ResizableColumns/demo/resizableColumns.min.js"></script>_x000D_
<table class="resizable" border="true">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>col 1</th><th>col 2</th><th>col 3</th><th>col 4</th>_x000D_
</tr>_x000D_
</thead>_x000D_
_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>Column 1</td><td>Column 2</td><td>Column 3</td><td>Column 4</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Column 1</td><td>Column 2</td><td>Column 3</td><td>Column 4</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
I'm not 100% sure that I understand your question, so tell me if I'm wrong.
If I got it right, you are reading jbytes that are technically signed chars, but really pixel values ranging from 0 to 255, and you're wondering how you should handle them without corrupting the values in the process.
Then, you should do the following:
convert jbytes to unsigned char before doing anything else, this will definetly restore the pixel values you are trying to manipulate
use a larger signed integer type, such as int while doing intermediate calculations, this to make sure that over- and underflows can be detected and dealt with (in particular, not casting to a signed type could force to compiler to promote every type to an unsigned type in which case you wouldn't be able to detect underflows later on)
when assigning back to a jbyte, you'll want to clamp your value to the 0-255 range, convert to unsigned char and then convert again to signed char: I'm not certain the first conversion is strictly necessary, but you just can't be wrong if you do both
For example:
inline int fromJByte(jbyte pixel) {
// cast to unsigned char re-interprets values as 0-255
// cast to int will make intermediate calculations safer
return static_cast<int>(static_cast<unsigned char>(pixel));
}
inline jbyte fromInt(int pixel) {
if(pixel < 0)
pixel = 0;
if(pixel > 255)
pixel = 255;
return static_cast<jbyte>(static_cast<unsigned char>(pixel));
}
jbyte in = ...
int intermediate = fromJByte(in) + 30;
jbyte out = fromInt(intermediate);
You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.
I used CountIf below, but there is lots of different ways to check existence of a value in a range.
Public Sub test()
Dim rng As Range
Dim aNumber As Long
aNumber = 666
Set rng = Sheet5.Range("B16:B615")
If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then
rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)
Else
MsgBox aNumber & " does not exist in range " & rng.Address
End If
End Sub
ALTERNATIVE WAY
Public Sub test()
Dim rng As Range
Dim aNumber As Variant
Dim rowNum As Long
aNumber = "2gg"
Set rng = Sheet5.Range("B1:B20")
If Not IsError(Application.Match(aNumber, rng, 0)) Then
rowNum = Application.Match(aNumber, rng, 0)
MsgBox rowNum
Else
MsgBox "error"
End If
End Sub
OR
Public Sub test()
Dim rng As Range
Dim aNumber As Variant
Dim rowNum As Variant
aNumber = "2gg"
Set rng = Sheet5.Range("B1:B20")
rowNum = Application.Match(aNumber, rng, 0)
If Not IsError(rowNum) Then
MsgBox rowNum
Else
MsgBox "error"
End If
End Sub
It should be noted that you can call key()
on any array to find the current key its on. As you can guess current()
will return the current value and next()
will move the array's pointer to the next element.
If it is not defined in the web service or application or server (apache or IIS) that is hosting the web service consumable then you could create infinite connections until failure
This was apparently always possible in .net core 1.0 with Microsoft.AspNetCore.Http.Extensions
, which adds extension to HttpRequest
to get full URL; GetEncodedUrl.
e.g. from razor view:
@using Microsoft.AspNetCore.Http.Extensions
...
<a href="@Context.Request.GetEncodedUrl()">Link to myself</a>
Since 2.0, also have relative path and query GetEncodedPathAndQuery.
Yes, as many as you want!
BUT, only one "public" class in every file.
I was receiving the same error message, and my issue was that I was not in the correct directory when running the command make install
. When I changed to the directory that had my makefile it worked.
So possibly you aren't in the right directory.
FYI, they've updated the Google Play developer page again. Now, at the far right, click the vertical ellipsis (like a colon with an extra dot in it). That now has the 'Unpublish App' option.
If you do this a lot, NumPy is the way to go.
If for some reason you can't use NumPy:
>>> map(lambda x:sum(x)/float(len(x)), zip(*a))
[45.0, 10.5]
The database uses the same lock for all #temp tables so if you are using a lot you will get deadlock problems. It is better to use @ table variables for concurrency.
Get the content of the JSON file using file_get_contents()
:
$str = file_get_contents('http://example.com/example.json/');
Now decode the JSON using json_decode()
:
$json = json_decode($str, true); // decode the JSON into an associative array
You have an associative array containing all the information. To figure out how to access the values you need, you can do the following:
echo '<pre>' . print_r($json, true) . '</pre>';
This will print out the contents of the array in a nice readable format. Note that the second parameter is set to true
in order to let print_r()
know that the output should be returned (rather than just printed to screen). Then, you access the elements you want, like so:
$temperatureMin = $json['daily']['data'][0]['temperatureMin'];
$temperatureMax = $json['daily']['data'][0]['temperatureMax'];
Or loop through the array however you wish:
foreach ($json['daily']['data'] as $field => $value) {
// Use $field and $value here
}
The application has to be both compiled and linked with -g
option. I.e. you need to put -g
in both CPPFLAGS
and LDFLAGS
.
Your best bet, starting fresh like you are, is to go grab the enterprise library. They have a configuration tool you can use to wire everything up for you nicely.
They also have a data access application block which is very useful and documentation filled with good samples.
set @latitude=53.754842;
set @longitude=-2.708077;
set @radius=20;
set @lng_min = @longitude - @radius/abs(cos(radians(@latitude))*69);
set @lng_max = @longitude + @radius/abs(cos(radians(@latitude))*69);
set @lat_min = @latitude - (@radius/69);
set @lat_max = @latitude + (@radius/69);
SELECT * FROM postcode
WHERE (longitude BETWEEN @lng_min AND @lng_max)
AND (latitude BETWEEN @lat_min and @lat_max);
If you just want to change file permissions, you want to be careful about using -R
on chmod
since it will change anything, files or folders. If you are doing a relative change (like adding write permission for everyone), you can do this:
sudo chmod -R a+w /var/www
But if you want to use the literal permissions of read/write, you may want to select files versus folders:
sudo find /var/www -type f -exec chmod 666 {} \;
(Which, by the way, for security reasons, I wouldn't recommend either of these.)
Or for folders:
sudo find /var/www -type d -exec chmod 755 {} \;
I know you have already accepted another answer, but I think the broader issue needs to addressed - programming style that is suitable to the current language.
Yes, 'initialization' isn't needed in Python, but what you are doing isn't initialization. It is just an incomplete and erroneous imitation of initialization as practiced in other languages. The important thing about initialization in static typed languages is that you specify the nature of the variables.
In Python, as in other languages, you do need to give variables values before you use them. But giving them values at the start of the function isn't important, and even wrong if the values you give have nothing to do with values they receive later. That isn't 'initialization', it's 'reuse'.
I'll make some notes and corrections to your code:
def main():
# doc to define the function
# proper Python indentation
# document significant variables, especially inputs and outputs
# grade_1, grade_2, grade_3, average - id these
# year - id this
# fName, lName, ID, converted_ID
infile = open("studentinfo.txt", "r")
# you didn't 'intialize' this variable
data = infile.read()
# nor this
fName, lName, ID, year = data.split(",")
# this will produce an error if the file does not have the right number of strings
# 'year' is now a string, even though you 'initialized' it as 0
year = int(year)
# now 'year' is an integer
# a language that requires initialization would have raised an error
# over this switch in type of this variable.
# Prompt the user for three test scores
grades = eval(input("Enter the three test scores separated by a comma: "))
# 'eval' ouch!
# you could have handled the input just like you did the file input.
grade_1, grade_2, grade_3 = grades
# this would work only if the user gave you an 'iterable' with 3 values
# eval() doesn't ensure that it is an iterable
# and it does not ensure that the values are numbers.
# What would happen with this user input: "'one','two','three',4"?
# Create a username
uName = (lName[:4] + fName[:2] + str(year)).lower()
converted_id = ID[:3] + "-" + ID[3:5] + "-" + ID[5:]
# earlier you 'initialized' converted_ID
# initialization in a static typed language would have caught this typo
# pseudo-initialization in Python does not catch typos
....
You can use str.contains
alone with a regex pattern using OR (|)
:
s[s.str.contains('og|at')]
Or you could add the series to a dataframe
then use str.contains
:
df = pd.DataFrame(s)
df[s.str.contains('og|at')]
Output:
0 cat
1 hat
2 dog
3 fog
I always use this way:
$foo = (object)null; //create an empty object
$foo->bar = "12345";
echo $foo->bar; //12345
If you are using python 3.6 and newer then you can use f-strings to do the task like this.
print(f"I have {card.price}")
just include f in front of your string and add the variable inside curly braces { }.
Refer to a blog The new f-strings in Python 3.6: written by Christoph Zwerschke which includes execution times of the various method.
The PHP documentation for time() shows an example of how you can get a date one week out. You can modify this to instead go into a loop that iterates a maximum of 7 times, get the timestamp each time, get the corresponding date, and from that get the day of the week.
Short answer:
StandardOutput=file:/var/log1.log
StandardError=file:/var/log2.log
If you don't want the files to be cleared every time the service is run, use append instead:
StandardOutput=append:/var/log1.log
StandardError=append:/var/log2.log
I worked for the Greater Detroit Society for the Blind for three years running a BBS tailored for blind access and worked with a number of blind users on how to better meet their needs, and with newly blind users to get them acclimated to the available hardware and software offerings that were available at the time. If nothing else, I at least learned to read Braille as a hedge against the case where I ever wound up in the same situation!
The majority of blind computer users and programmers use a screen reader of some sort. Jaws in particular is popular. Fortunately, most major applications these days offer some form of handicapped access. You may have to tune your environment slightly to cut down on the chatter, e.g. consider disabling Intellisense in Visual Studio.
A Braille display is less common and is comparatively much more expensive and can show 40 or 80 columns of text, and can be used when exact positioning/punctuation is important. While a screen reader can be configured to rattle off punctuation, a lot of people find it distracting, and it is easier in many cases to feel your way through it. Jaws can be configured to drive the display, so you're not juggling accessibility applications.
Also, a lot of legally blind users still have some modicum of sight left to them. Using high contrast backgrounds and the magnification functionality can help a lot of these users.
Using ToggleKeys in Windows will let you hear when you accidentally tap one of the modal 'caps lock', 'num lock', 'scroll lock', etc. keys as well.
I know at least one Haskell programmer who uses a screen reader and who explicitly programs without using Haskell's layout rules, and instead opts to use the rather non-idiomatic, but supported {;}
's instead, because it is easier/less distracting for him to get his screen reader to read off punctuation than for him to figure out exact indentation that complies with Haskell's layout rules. On that same note, I've heard some grumbling from a couple of blind programmers about when they have to write Python.
Ultimately, you learn to play on your strengths.
I'm not aware of anything like a single table that lets you compare all of them in at one glance (I'm not sure such a table would even be feasible).
Of course the ISO standard document enumerates the complexity requirements in detail, sometimes in various rather readable tables, other times in less readable bullet points for each specific method.
Also the STL library reference at http://www.cplusplus.com/reference/stl/ provides the complexity requirements where appropriate.
@ symbol is also used to access variables inside a plydata / pandas dataframe query, pandas.DataFrame.query
.
Example:
df = pandas.DataFrame({'foo': [1,2,15,17]})
y = 10
df >> query('foo > @y') # plydata
df.query('foo > @y') # pandas
You can trigger a newline by inserting Chunk.NEWLINE
into your document. Here's an example.
public static void main(String args[]) {
try {
// create a new document
Document document = new Document( PageSize.A4, 20, 20, 20, 20 );
PdfWriter.getInstance( document, new FileOutputStream( "HelloWorld.pdf" ) );
document.open();
document.add( new Paragraph( "Hello, World!" ) );
document.add( new Paragraph( "Hello, World!" ) );
// add a couple of blank lines
document.add( Chunk.NEWLINE );
document.add( Chunk.NEWLINE );
// add one more line with text
document.add( new Paragraph( "Hello, World!" ) );
document.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
Below is a screen shot showing part of the PDF that the code above produces.
It is possible to do this by overwriting the Environment Table within a specified process itself.
As a proof of concept I wrote this sample app, which just edited a single (known) environment variable in a cmd.exe process:
typedef DWORD (__stdcall *NtQueryInformationProcessPtr)(HANDLE, DWORD, PVOID, ULONG, PULONG);
int __cdecl main(int argc, char* argv[])
{
HMODULE hNtDll = GetModuleHandleA("ntdll.dll");
NtQueryInformationProcessPtr NtQueryInformationProcess = (NtQueryInformationProcessPtr)GetProcAddress(hNtDll, "NtQueryInformationProcess");
int processId = atoi(argv[1]);
printf("Target PID: %u\n", processId);
// open the process with read+write access
HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_VM_OPERATION, 0, processId);
if(hProcess == NULL)
{
printf("Error opening process (%u)\n", GetLastError());
return 0;
}
// find the location of the PEB
PROCESS_BASIC_INFORMATION pbi = {0};
NTSTATUS status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
if(status != 0)
{
printf("Error ProcessBasicInformation (0x%8X)\n", status);
}
printf("PEB: %p\n", pbi.PebBaseAddress);
// find the process parameters
char *processParamsOffset = (char*)pbi.PebBaseAddress + 0x20; // hard coded offset for x64 apps
char *processParameters = NULL;
if(ReadProcessMemory(hProcess, processParamsOffset, &processParameters, sizeof(processParameters), NULL))
{
printf("UserProcessParameters: %p\n", processParameters);
}
else
{
printf("Error ReadProcessMemory (%u)\n", GetLastError());
}
// find the address to the environment table
char *environmentOffset = processParameters + 0x80; // hard coded offset for x64 apps
char *environment = NULL;
ReadProcessMemory(hProcess, environmentOffset, &environment, sizeof(environment), NULL);
printf("environment: %p\n", environment);
// copy the environment table into our own memory for scanning
wchar_t *localEnvBlock = new wchar_t[64*1024];
ReadProcessMemory(hProcess, environment, localEnvBlock, sizeof(wchar_t)*64*1024, NULL);
// find the variable to edit
wchar_t *found = NULL;
wchar_t *varOffset = localEnvBlock;
while(varOffset < localEnvBlock + 64*1024)
{
if(varOffset[0] == '\0')
{
// we reached the end
break;
}
if(wcsncmp(varOffset, L"ENVTEST=", 8) == 0)
{
found = varOffset;
break;
}
varOffset += wcslen(varOffset)+1;
}
// check to see if we found one
if(found)
{
size_t offset = (found - localEnvBlock) * sizeof(wchar_t);
printf("Offset: %Iu\n", offset);
// write a new version (if the size of the value changes then we have to rewrite the entire block)
if(!WriteProcessMemory(hProcess, environment + offset, L"ENVTEST=def", 12*sizeof(wchar_t), NULL))
{
printf("Error WriteProcessMemory (%u)\n", GetLastError());
}
}
// cleanup
delete[] localEnvBlock;
CloseHandle(hProcess);
return 0;
}
Sample output:
>set ENVTEST=abc
>cppTest.exe 13796
Target PID: 13796
PEB: 000007FFFFFD3000
UserProcessParameters: 00000000004B2F30
environment: 000000000052E700
Offset: 1528
>set ENVTEST
ENVTEST=def
This approach would also be limited to security restrictions. If the target is run at higher elevation or a higher account (such as SYSTEM) then we wouldn't have permission to edit its memory.
If you wanted to do this to a 32-bit app, the hard coded offsets above would change to 0x10 and 0x48 respectively. These offsets can be found by dumping out the _PEB and _RTL_USER_PROCESS_PARAMETERS structs in a debugger (e.g. in WinDbg dt _PEB
and dt _RTL_USER_PROCESS_PARAMETERS
)
To change the proof-of-concept into a what the OP needs, it would just enumerate the current system and user environment variables (such as documented by @tsadok's answer) and write the entire environment table into the target process' memory.
Edit: The size of the environment block is also stored in the _RTL_USER_PROCESS_PARAMETERS struct, but the memory is allocated on the process' heap. So from an external process we wouldn't have the ability to resize it and make it larger. I played around with using VirtualAllocEx to allocate additional memory in the target process for the environment storage, and was able to set and read an entirely new table. Unfortunately any attempt to modify the environment from normal means will crash and burn as the address no longer points to the heap (it will crash in RtlSizeHeap).
In php.ini set :
error_reporting = E_ALL & ~E_NOTICE & ~E_STRICT
You could also change the viewChild 'type' to NgForm as in:
@ViewChild('loginForm') loginForm: NgForm;
And then reference your controls in the same way @Julia mentioned:
private login(formData: any): void {
this.authService.login(formData).subscribe(res => {
alert(`Congrats, you have logged in. We don't have anywhere to send you right now though, but congrats regardless!`);
}, error => {
this.loginFailed = true; // This displays the error message, I don't really like this, but that's another issue.
this.loginForm.controls['email'].setErrors({ 'incorrect': true});
this.loginForm.controls['password'].setErrors({ 'incorrect': true});
});
}
Setting the Errors to null will clear out the errors on the UI:
this.loginForm.controls['email'].setErrors(null);
i did try this and its working in windows machine to run a sql file on a specific schema.
psql -h localhost -p 5432 -U username -d databasename -v schema=schemaname < e:\Table.sql
First you need to start karma server with
karma start
Then, you can use grep to filter a specific test or describe block:
karma run -- --grep=testDescriptionFilter
Below solution worked for my Xiaomi mobile phone:
Go to Settings -> Additional settings -> Developer options and check Install via USB, if toast The device is temporarily restricted shown, please turn your WI-FI off, turn on mobile data. Then try it again.
If A.S. Instance Run is still not work when you finished all steps above, perhaps you turned on MIUI optimization, please follow below step and try again:
Settings -> Additional settings -> Developer options and uncheck Turn on MIUI optimization
Reference taken from this post:
You can also use this script to find lock in MySQL.
SELECT
pl.id
,pl.user
,pl.state
,it.trx_id
,it.trx_mysql_thread_id
,it.trx_query AS query
,it.trx_id AS blocking_trx_id
,it.trx_mysql_thread_id AS blocking_thread
,it.trx_query AS blocking_query
FROM information_schema.processlist AS pl
INNER JOIN information_schema.innodb_trx AS it
ON pl.id = it.trx_mysql_thread_id
INNER JOIN information_schema.innodb_lock_waits AS ilw
ON it.trx_id = ilw.requesting_trx_id
AND it.trx_id = ilw.blocking_trx_id
I put a getchar()
at the end of my programs as a simple "pause-method". Depending on your particular details, investigate getchar
, getch
, or getc
show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| datapass_schema |
| mysql |
| test |
+--------------------+
4 rows in set (0.05 sec)
mysql> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> show tables
-> ;
+---------------------------+
| Tables_in_mysql |
+---------------------------+
| columns_priv |
| db |
| event |
| func |
| general_log |
| help_category |
| help_keyword |
| help_relation |
| help_topic |
| host |
| ndb_binlog_index |
| plugin |
| proc |
| procs_priv |
| servers |
| slow_log |
| tables_priv |
| time_zone |
| time_zone_leap_second |
| time_zone_name |
| time_zone_transition |
| time_zone_transition_type |
| user |
+---------------------------+
23 rows in set (0.00 sec)
mysql> create user m identified by 'm';
Query OK, 0 rows affected (0.02 sec)
check for the database mysql and table user as shown above if that dosent work, your mysql installation is not proper.
use the below command as mention in other post to install tables again
mysql_install_db
The line-continuation will fail if you have whitespace (spaces or tab characters[1]) after the backslash and before the newline. With no such whitespace, your example works fine for me:
$ cat test.sh
if ! fab --fabfile=.deploy/fabfile.py \
--forward-agent \
--disable-known-hosts deploy:$target; then
echo failed
else
echo succeeded
fi
$ alias fab=true; . ./test.sh
succeeded
$ alias fab=false; . ./test.sh
failed
Some detail promoted from the comments: the line-continuation backslash in the shell is not really a special case; it is simply an instance of the general rule that a backslash "quotes" the immediately-following character, preventing any special treatment it would normally be subject to. In this case, the next character is a newline, and the special treatment being prevented is terminating the command. Normally, a quoted character winds up included literally in the command; a backslashed newline is instead deleted entirely. But otherwise, the mechanism is the same. Most importantly, the backslash only quotes the immediately-following character; if that character is a space or tab, you just get a literal space or tab, and any subsequent newline remains unquoted.
[1] or carriage returns, for that matter, as Czechnology points out. Bash does not get along with Windows-formatted text files, not even in WSL. Or Cygwin, but at least their Bash port has added a set -o igncr
option that you can set to make it carriage-return-tolerant.
The shortcut to comment out or uncomment the selected text or current line:
Alternatively, use the menu: Edit > Comment
For the block comment you may want to use:
In the case where item
and z
are sorted iterators, we can reduce the complexity from O(n^2)
to O(n+m)
by doing this
def iexclude(sorted_iterator, exclude_sorted_iterator):
next_val = next(exclude_sorted_iterator)
for item in sorted_iterator:
try:
while next_val < item:
next_val = next(exclude_sorted_iterator)
continue
if item == next_val:
continue
except StopIteration:
pass
yield item
If the two are iterators, we also have the opportunity to reduce the memory footprint not storing z
(exclude_sorted_iterator
) as a list.
JavaScript Pure:
<script type="text/javascript">
document.getElementById("modal").click();
</script>
JQuery:
<script type="text/javascript">
$(document).ready(function(){
$("#modal").trigger('click');
});
</script>
or
<script type="text/javascript">
$(document).ready(function(){
$("#modal").click();
});
</script>
Your class doesn't have a __init__()
, so by the time it's instantiated, the attribute atoms
is not present. You'd have to do C.setdata('something')
so C.atoms
becomes available.
>>> C = Residues()
>>> C.atoms.append('thing')
Traceback (most recent call last):
File "<pyshell#84>", line 1, in <module>
B.atoms.append('thing')
AttributeError: Residues instance has no attribute 'atoms'
>>> C.setdata('something')
>>> C.atoms.append('thing') # now it works
>>>
Unlike in languages like Java, where you know at compile time what attributes/member variables an object will have, in Python you can dynamically add attributes at runtime. This also implies instances of the same class can have different attributes.
To ensure you'll always have (unless you mess with it down the line, then it's your own fault) an atoms
list you could add a constructor:
def __init__(self):
self.atoms = []
For solving this issue i would recommend to define explicitly the version for the ext variables
at the android/build.gradle
at your root project
ext {
googlePlayServicesVersion = "16.1.0" // default: "+"
firebaseVersion = "15.0.2" // default: "+"
// Other settings
compileSdkVersion = <Your compile SDK version> // default: 23
buildToolsVersion = "<Your build tools version>" // default: "23.0.1"
targetSdkVersion = <Your target SDK version> // default: 23
supportLibVersion = "<Your support lib version>" // default: 23.1.1
}
reference https://github.com/zo0r/react-native-push-notification/issues/1109#issuecomment-506414941
In JavaScript this
refers to the element containing the action. For example, if you have a function called hide()
:
function hide(element){
element.style.display = 'none';
}
Calling hide
with this
will hide the element. It returns only the element clicked, even if it is similar to other elements in the DOM.
For example, you may have this
clicking a number in the HTML below will only hide the bullet point clicked.
<ul>
<li class="bullet" onclick="hide(this);">1</li>
<li class="bullet" onclick="hide(this);">2</li>
<li class="bullet" onclick="hide(this);">3</li>
<li class="bullet" onclick="hide(this);">4</li>
</ul>
Another way to use gson:
String json_String_to_print = ...
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
return gson.toJson(jp.parse(json_String_to_print));
It can be used when you don't have the bean as in susemi99's post.
Note: For MAC OS
Your HTML should include quotes for attributes : http://jsfiddle.net/dKWnb/4/
Not required when using a HTML5 doctype - thanks @bazmegakapa
You create the array each time and add a value to it ... its working as expected ?
Moving the array outside of the live() function works fine :
var myarray = []; // more efficient than new Array()
$("#test").live("click",function() {
myarray.push($("#drop").val());
alert(myarray);
});
Also note that in later versions of jQuery v1.7 -> the live() method is deprecated and replaced by the on() method.
I think your problem is that the match method is returning an array. The 0th item in the array is the original string, the 1st thru nth items correspond to the 1st through nth matched parenthesised items. Your "alert()" call is showing the entire array.
FYI: I know this is a bit late but for anyone who is interested. Depends on how RESTful you want to be, you will have to implement your own filtering strategies as the HTTP spec is not very clear on this. I'd like to suggest url-encoding all the filter parameters e.g.
GET api/users?filter=param1%3Dvalue1%26param2%3Dvalue2
I know it's ugly but I think it's the most RESTful way to do it and should be easy to parse on the server side :)
HAVING is like WHERE with aggregate functions, or you could use a subquery.
select EmployeeId, sum(amount)
from Sales
group by Employee
having sum(amount) > 20000
Or
select EmployeeId, sum(amount)
from Sales
group by Employee
where EmployeeId in (
select max(EmployeeId) from Employees)
The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:
ffmpeg -i input.mov -qscale 0 output.mp4
Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0
):
ffmpeg -i input.mov -q:v 0 output.mp4
Solution
DateTime.Now.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture)
Here is a tutorial from Google about mapping your App on custom domain: https://cloud.google.com/appengine/docs/domain?hl=FR
It should be the latest update. But please note these 2 things:
1- You may not find you App in the new developer console, then the only workaround for that is download your source code, create a new app from the new developer console and deploy it.
2- You find your App on the developer console, but under the Compute menu you may not find the App Engine Settings as mentioned in the tutorial, then you have to proceed the same as i explained in the first point (create another application)
I hope this helps !
You can groupby the 'name'
and 'month'
columns, then call transform
which will return data aligned to the original df and apply a lambda where we join
the text entries:
In [119]:
df['text'] = df[['name','text','month']].groupby(['name','month'])['text'].transform(lambda x: ','.join(x))
df[['name','text','month']].drop_duplicates()
Out[119]:
name text month
0 name1 hej,du 11
2 name1 aj,oj 12
4 name2 fin,katt 11
6 name2 mycket,lite 12
I sub the original df by passing a list of the columns of interest df[['name','text','month']]
here and then call drop_duplicates
EDIT actually I can just call apply
and then reset_index
:
In [124]:
df.groupby(['name','month'])['text'].apply(lambda x: ','.join(x)).reset_index()
Out[124]:
name month text
0 name1 11 hej,du
1 name1 12 aj,oj
2 name2 11 fin,katt
3 name2 12 mycket,lite
update
the lambda
is unnecessary here:
In[38]:
df.groupby(['name','month'])['text'].apply(','.join).reset_index()
Out[38]:
name month text
0 name1 11 du
1 name1 12 aj,oj
2 name2 11 fin,katt
3 name2 12 mycket,lite
It's !=
without type coercion. See the MDN documentation for comparison operators.
Also see this StackOverflow answer, which includes a quote from "JavaScript: The Good Parts" about the problems with ==
and !=
. (null == undefined
, false == "0"
, etc.)
Short answer: always use ===
and !==
unless you have a compelling reason to do otherwise. (Tools like JSLint, JSHint, ESLint, etc. will give you this same advice.)
You need to transform your Path into a File
and test for existence:
for(Path entry: stream){
if(entry.toFile().exists()){
log.info("working on file " + entry.getFileName());
}
}
If the previous answers do not solve your problem, check the source of the data that won't print/convert properly.
In my case, I was using json.load
on data incorrectly read from file by not using the encoding="utf-8"
. Trying to de-/encode the resulting string to latin-1
just does not help...
READ THIS FIRST https://packaging.python.org/en/latest/current.html
Installation Tool Recommendations
- Use pip to install Python packages from PyPI.
- Use virtualenv, or pyvenv to isolate application specific dependencies from a shared Python installation.
- Use pip wheel to create a cache of wheel distributions, for the purpose of > speeding up subsequent installations.
- If you’re looking for management of fully integrated cross-platform software stacks, consider buildout (primarily focused on the web development community) or Hashdist, or conda (both primarily focused on the scientific community).
Packaging Tool Recommendations
- Use setuptools to define projects and create Source Distributions.
- Use the bdist_wheel setuptools extension available from the wheel project to create wheels. This is especially beneficial, if your project contains binary extensions.
- Use twine for uploading distributions to PyPI.
This anwser has aged, and indeed there is a rescue plan for python packaging world called
I qoute pythonwheels.com here:
What are wheels?
Wheels are the new standard of python distribution and are intended to replace eggs. Support is offered in pip >= 1.4 and setuptools >= 0.8.
Advantages of wheels
The full story of correct python packaging (and about wheels) is covered at packaging.python.org
For scientific computing (this is also recommended on packaging.python.org, see above) I would consider using CONDA packaging which can be seen as a 3rd party service build on top of PyPI and pip tools. It also works great on setting up your own version of binstar so I would imagine it can do the trick for sophisticated custom enterprise package management.
Conda can be installed into a user folder (no super user permisssions) and works like magic with
conda install
and powerful virtual env expansion.
This option was related to python-distribute.org and is largerly outdated (as well as the site) so let me point you to one of the ready to use yet compact setup.py examples I like:
This quote was taken from the guide on the state of setup.py and still applies:
I add one more point (from me)
I would recommend to get some understanding of packaging-ecosystem (from the guide pointed by gotgenes) before attempting mindless copy-pasting.
Most of examples out there in the Internet start with
from distutils.core import setup
but this for example does not support building an egg python setup.py bdist_egg (as well as some other old features), which were available in
from setuptools import setup
And the reason is that they are deprecated.
Now according to the guide
Warning
Please use the Distribute package rather than the Setuptools package because there are problems in this package that can and will not be fixed.
deprecated setuptools are to be replaced by distutils2, which "will be part of the standard library in Python 3.3". I must say I liked setuptools and eggs and have not yet been completely convinced by convenience of distutils2. It requires
pip install Distutils2
and to install
python -m distutils2.run install
Packaging never was trivial (one learns this by trying to develop a new one), so I assume a lot of things have gone for reason. I just hope this time it will be is done correctly.
So - the solution of providing a base works given that all of the paths have the same base path. But if you want to provide different base paths, this still won't work.
One way I solved this problem was by making the beginning of the path relative. For your case:
gulp.src([
'index.php',
'*css/**/*',
'*js/**/*',
'*src/**/*',
])
.pipe(gulp.dest('/var/www/'));
The reason this works is that Gulp sets the base to be the end of the first explicit chunk - the leading * causes it to set the base at the cwd (which is the result that we all want!)
This only works if you can ensure your folder structure won't have certain paths that could match twice. For example, if you had randomjs/
at the same level as js
, you would end up matching both.
This is the only way that I have found to include these as part of a top-level gulp.src function. It would likely be simple to create a plugin/function that could separate out each of those globs so you could specify the base directory for them, however.