In order to add the file to the email as an attachment, it will need to be stored on the server briefly. It's trivial, though, to place it in a tmp location then delete it after you're done with it.
As for emailing, Zend Mail has a very easy to use interface for dealing with email attachments. We run with the whole Zend Framework installed, but I'm pretty sure you could just install the Zend_Mail library without needing any other modules for dependencies.
With Zend_Mail, sending an email with an attachment is as simple as:
$mail = new Zend_Mail();
$mail->setSubject("My Email with Attachment");
$mail->addTo("[email protected]");
$mail->setBodyText("Look at the attachment");
$attachment = $mail->createAttachment(file_get_contents('/path/to/file'));
$mail->send();
If you're looking for a one-file-package to do the whole form/email/attachment thing, I haven't seen one. But the individual components are certainly available and easy to assemble. Trickiest thing of the whole bunch is the email attachment, which the above recommendation makes very simple.
As an addition to mklement0's excellent answer:
Almost all executables accept \"
as an escaped "
. Safe usage in cmd however is almost only possible using DELAYEDEXPANSION.
To explicitely send a literal "
to some process, assign \"
to an environment variable, and then use that variable, whenever you need to pass a quote. Example:
SETLOCAL ENABLEDELAYEDEXPANSION
set q=\"
child "malicious argument!q!&whoami"
Note SETLOCAL ENABLEDELAYEDEXPANSION
seems to work only within batch files. To get DELAYEDEXPANSION in an interactive session, start cmd /V:ON
.
If your batchfile does't work with DELAYEDEXPANSION, you can enable it temporarily:
::region without DELAYEDEXPANSION
SETLOCAL ENABLEDELAYEDEXPANSION
::region with DELAYEDEXPANSION
set q=\"
echoarg.exe "ab !q! & echo danger"
ENDLOCAL
::region without DELAYEDEXPANSION
If you want to pass dynamic content from a variable that contains quotes that are escaped as ""
you can replace ""
with \"
on expansion:
SETLOCAL ENABLEDELAYEDEXPANSION
foo.exe "danger & bar=region with !dynamic_content:""=\"! & danger"
ENDLOCAL
This replacement is not safe with %...%
style expansion!
In case of OP bash -c "g++-linux-4.1 !v_params:"=\"!"
is the safe version.
If for some reason even temporarily enabling DELAYEDEXPANSION is not an option, read on:
Using \"
from within cmd is a little bit safer if one always needs to escape special characters, instead of just sometimes. (It's less likely to forget a caret, if it's consistent...)
To achieve this, one precedes any quote with a caret (^"
), quotes that should reach the child process as literals must additionally be escaped with a backlash (\^"
). ALL shell meta characters must be escaped with ^
as well, e.g. &
=> ^&
; |
=> ^|
; >
=> ^>
; etc.
Example:
child ^"malicious argument\^"^&whoami^"
Source: Everyone quotes command line arguments the wrong way, see "A better method of quoting"
To pass dynamic content, one needs to ensure the following:
The part of the command that contains the variable must be considered "quoted" by cmd.exe
(This is impossible if the variable can contain quotes - don't write %var:""=\"%
). To achieve this, the last "
before the variable and the first "
after the variable are not ^
-escaped. cmd-metacharacters between those two "
must not be escaped. Example:
foo.exe ^"danger ^& bar=\"region with %dynamic_content% & danger\"^"
This isn't safe, if %dynamic_content%
can contain unmatched quotes.
In a REST API, you shouldn't be overly concerned by predictable URI's. The very suggestion of URI predictability alludes to a misunderstanding of RESTful architecture. It assumes that a client should be constructing URIs themselves, which they really shouldn't have to.
However, I assume that you are not creating a true REST API, but a 'REST inspired' API (such as the Google Drive one). In these cases the rule of thumb is 'path params = resource identification' and 'query params = resource sorting'. So, the question becomes, can you uniquely identify your resource WITHOUT status / region? If yes, then perhaps its a query param. If no, then its a path param.
HTH.
You can simply play a setted ringtone with this:
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
On Linux, Unix, Git Bash, or Cygwin, try:
rm -f .git/index.lock
On Windows Command Prompt, try:
del .git\index.lock
For Windows:
From a PowerShell console opened as administrator, try
rm -Force ./.git/index.lock
If that does not work, you must kill all git.exe processes
taskkill /F /IM git.exe
SUCCESS: The process "git.exe" with PID 20448 has been terminated.
SUCCESS: The process "git.exe" with PID 11312 has been terminated.
SUCCESS: The process "git.exe" with PID 23868 has been terminated.
SUCCESS: The process "git.exe" with PID 27496 has been terminated.
SUCCESS: The process "git.exe" with PID 33480 has been terminated.
SUCCESS: The process "git.exe" with PID 28036 has been terminated. \
rm -Force ./.git/index.lock
I noticed that whilst the other answers explained what require is and that it is used to load modules in Node they did not give a full reply on how to load node modules when working in the Browser.
It is quite simple to do. Install your module using npm as you describe, and the module itself will be located in a folder usually called node_modules.
Now the simplest way to load it into your app is to reference it from your html with a script tag which points at this directory. i.e if your node_modules directory is in the root of the project at the same level as your index.html you would write this in your index.html:
<script src="node_modules/ng"></script>
That whole script will now be loaded into the page - so you can access its variables and methods directly.
There are other approaches which are more widely used in larger projects, such as a module loader like require.js. Of the two, I have not used Require myself, but I think it is considered by many people the way to go.
While some of the other answers have covered the simple cases using setjmp
and longjmp
, in a real application there's two concerns that really matter.
jmp_buf
will make these not work.jmp_buf
will cause all kinds of pain in this situation.The solution to these is to maintain a thread-local stack of jmp_buf
that get updated as you go. (I think this is what lua uses internally).
So instead of this (from JaredPar's awesome answer)
static jmp_buf s_jumpBuffer;
void Example() {
if (setjmp(s_jumpBuffer)) {
// The longjmp was executed and returned control here
printf("Exception happened\n");
} else {
// Normal code execution starts here
Test();
}
}
void Test() {
// Rough equivalent of `throw`
longjump(s_jumpBuffer, 42);
}
You'd use something like:
#define MAX_EXCEPTION_DEPTH 10;
struct exception_state {
jmp_buf s_jumpBuffer[MAX_EXCEPTION_DEPTH];
int current_depth;
};
int try_point(struct exception_state * state) {
if(current_depth==MAX_EXCEPTION_DEPTH) {
abort();
}
int ok = setjmp(state->jumpBuffer[state->current_depth]);
if(ok) {
state->current_depth++;
} else {
//We've had an exception update the stack.
state->current_depth--;
}
return ok;
}
void throw_exception(struct exception_state * state) {
longjump(state->current_depth-1,1);
}
void catch_point(struct exception_state * state) {
state->current_depth--;
}
void end_try_point(struct exception_state * state) {
state->current_depth--;
}
__thread struct exception_state g_exception_state;
void Example() {
if (try_point(&g_exception_state)) {
catch_point(&g_exception_state);
printf("Exception happened\n");
} else {
// Normal code execution starts here
Test();
end_try_point(&g_exception_state);
}
}
void Test() {
// Rough equivalent of `throw`
throw_exception(g_exception_state);
}
Again a more realistic version of this would include some way to store error information into the exception_state
, better handling of MAX_EXCEPTION_DEPTH
(maybe using realloc to grow the buffer, or something like that).
DISCLAIMER: The above code was written without any testing whatsoever. It is purely so you get an idea of how to structure things. Different systems and different compilers will need to implement the thread local storage differently. The code probably contains both compile errors and logic errors - so while you're free to use it as you choose, TEST it before using it ;)
Sure! Setup:
>>> import pandas as pd
>>> from random import randint
>>> df = pd.DataFrame({'A': [randint(1, 9) for x in range(10)],
'B': [randint(1, 9)*10 for x in range(10)],
'C': [randint(1, 9)*100 for x in range(10)]})
>>> df
A B C
0 9 40 300
1 9 70 700
2 5 70 900
3 8 80 900
4 7 50 200
5 9 30 900
6 2 80 700
7 2 80 400
8 5 80 300
9 7 70 800
We can apply column operations and get boolean Series objects:
>>> df["B"] > 50
0 False
1 True
2 True
3 True
4 False
5 False
6 True
7 True
8 True
9 True
Name: B
>>> (df["B"] > 50) & (df["C"] == 900)
0 False
1 False
2 True
3 True
4 False
5 False
6 False
7 False
8 False
9 False
[Update, to switch to new-style .loc
]:
And then we can use these to index into the object. For read access, you can chain indices:
>>> df["A"][(df["B"] > 50) & (df["C"] == 900)]
2 5
3 8
Name: A, dtype: int64
but you can get yourself into trouble because of the difference between a view and a copy doing this for write access. You can use .loc
instead:
>>> df.loc[(df["B"] > 50) & (df["C"] == 900), "A"]
2 5
3 8
Name: A, dtype: int64
>>> df.loc[(df["B"] > 50) & (df["C"] == 900), "A"].values
array([5, 8], dtype=int64)
>>> df.loc[(df["B"] > 50) & (df["C"] == 900), "A"] *= 1000
>>> df
A B C
0 9 40 300
1 9 70 700
2 5000 70 900
3 8000 80 900
4 7 50 200
5 9 30 900
6 2 80 700
7 2 80 400
8 5 80 300
9 7 70 800
Note that I accidentally typed == 900
and not != 900
, or ~(df["C"] == 900)
, but I'm too lazy to fix it. Exercise for the reader. :^)
You can use frame property of textfield to change frame Like-Textfield.frame=CGRECTMake(x axis,y axis,width,height)
Have you taken a look at jconsole?
This will list all threads running for a particular Java process.
You can start jconsole from the JDK bin folder.
You can also get a full stack trace for all threads by hitting Ctrl+Break
in Windows or by sending kill pid --QUIT
in Linux.
You may also use:
request.POST.get('section','') # => [39]
request.POST.get('MAINS','') # => [137]
request.GET.get('section','') # => [39]
request.GET.get('MAINS','') # => [137]
Using this ensures that you don't get an error. If the POST/GET data with any key is not defined then instead of raising an exception the fallback value (second argument of .get() will be used).
Best way to locate anchor elements is to use link=Re-Call
:
selenium.click("link=Re-Call");
It will work..
bsondump collection.bson > collection.json
and then
mongoimport -d <dbname> -c <collection> < collection.json
It's easier and cleaner to do it with CSS.
HTML:
<div ng-repeat="file in files" class="file">
{{ file.name }}
</div>
CSS:
.file:last-of-type {
color: #800;
}
The :last-of-type
selector is currently supported by 98% of browsers
Do not use communicate(input=""). It writes input to the process, closes its stdin and then reads all output.
Do it like this:
p=subprocess.Popen(["python","1st.py"],stdin=PIPE,stdout=PIPE)
# get output from process "Something to print"
one_line_output = p.stdout.readline()
# write 'a line\n' to the process
p.stdin.write('a line\n')
# get output from process "not time to break"
one_line_output = p.stdout.readline()
# write "n\n" to that process for if r=='n':
p.stdin.write('n\n')
# read the last output from the process "Exiting"
one_line_output = p.stdout.readline()
What you would do to remove the error:
all_the_process_will_tell_you = p.communicate('all you will ever say to this process\nn\n')[0]
But since communicate closes the stdout
and stdin
and stderr
, you can not read or write after you called communicate.
EDIT:
The website is now called appicon.co
I usually use assets.codly.io
It generates the assets locally in your browser, no upload, no download.
key 13 keycode is for ENTER key.
playsinline
attribute in video tag like this:<video class="video-background" autoplay loop muted playsinline>
It only worked when including playsinline
.
You can use the git command line as a terminal my dude you just know the commands are bash To create a file
touch file.txt
To open a file
code file.py
atom file.py
start file.py
ect
To open your current folder and everything inside of it in your text editor
code .
To make a folder
mkdir folder1 folder2 folder3
You can make as many as you want at once this works with touch to
Since ES2015 you can use the for of loop, to access the element directly:
// before ES2015
for(var key of elements){
console.log(elements[key]);
}
// ES2015
for(let element of elements){
console.log(element);
}
Hope this helps someone.
You can do this with the ImageMagick extension. I'm guessing that the combineImages() method will do what you want.
svn revert . -R
to reset everything.
svn revert path/to/file
for a single file
The example below shows the basic usage of the FileReader
to read the contents of an uploaded file. Here is a working Plunker of this example.
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
</head>
<body onload="init()">
<input id="fileInput" type="file" name="file" />
<pre id="fileContent"></pre>
</body>
</html>
script.js
function init(){
document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
}
function handleFileSelect(event){
const reader = new FileReader()
reader.onload = handleFileLoad;
reader.readAsText(event.target.files[0])
}
function handleFileLoad(event){
console.log(event);
document.getElementById('fileContent').textContent = event.target.result;
}
Also see: the official Which remote URL should I use? answer on help.github.com.
EDIT:
It seems that it's no longer necessary to have write access to a public repo to use an SSH URL, rendering my original explanation invalid.
ORIGINAL:
Apparently the main reason for favoring HTTPS URLs is that SSH URL's won't work with a public repo if you don't have write access to that repo.
The use of SSH URLs is encouraged for deployment to production servers, however - presumably the context here is services like Heroku.
If you want to sort based on first column (which contains number value), then try this:
arr.sort(function(a,b){
return a[0]-b[0]
})
If you want to sort based on second column (which contains string value), then try this:
arr.sort(function(a,b){
return a[1].charCodeAt(0)-b[1].charCodeAt(0)
})
P.S. for the second case, you need to compare between their ASCII values.
Hope this helps.
Short snippet for future visitors - how to center horizontal table-cell (+ vertically)
html, body {_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
.tab {_x000D_
display: table;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
.cell {_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
text-align: center; /* the key */_x000D_
background-color: #EEEEEE;_x000D_
}_x000D_
_x000D_
.content {_x000D_
display: inline-block; /* important !! */_x000D_
width: 100px;_x000D_
background-color: #00FF00;_x000D_
}
_x000D_
<div class="tab">_x000D_
<div class="cell">_x000D_
<div class="content" id="a">_x000D_
<p>Content</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
If you are using form data to upload file,in which a parameter name must be specified , you can use:
curl -X POST -i -F "parametername=@filename" -F "additional_parm=param2" host:port/xxx
Just using the command list did not work for me.
if you have a tuple just iterate until you have the elements there are necessary and after that append to a list. And if you go to the element level you can change it easily.
input:
level1 = (
(1,1,1,1,1,1),
(1,0,0,0,0,1),
(1,0,0,0,0,1),
(1,0,0,0,0,1),
(1,0,0,0,0,1),
(1,1,1,1,1,1))
level1_as_list=[]
for i in level1:
inside_list=[]
for j in i:
inside_list.append(j)
level1_as_list.append(inside_list)
print(level1_as_list)enter code here
output:
[[1, 1, 1, 1, 1, 1], [1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1]]
try removing the extra '/' after the operation name (authentication) when invoking through the client
/axis2/services/MyService/authentication?username=Denise345&password=xxxxx
To handle One-To-Many relationships in Django you need to use ForeignKey
.
The documentation on ForeignKey is very comprehensive and should answer all the questions you have:
https://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey
The current structure in your example allows each Dude to have one number, and each number to belong to multiple Dudes (same with Business).
If you want the reverse relationship, you would need to add two ForeignKey fields to your PhoneNumber model, one to Dude and one to Business. This would allow each number to belong to either one Dude or one Business, and have Dudes and Businesses able to own multiple Numbers. I think this might be what you are after.
class Business(models.Model):
...
class Dude(models.Model):
...
class PhoneNumber(models.Model):
dude = models.ForeignKey(Dude)
business = models.ForeignKey(Business)
You should generally use urllib2, since this makes things a bit easier at times by accepting Request objects and will also raise a URLException on protocol errors. With Google App Engine though, you can't use either. You have to use the URL Fetch API that Google provides in its sandboxed Python environment.
Use del /F /Q
to force deletion of read-only files (/F
) and directories and not ask to confirm (/Q
) when deleting via wildcard.
Java includes a scripting language extension package starting with version 6.
See the Rhino project documentation for embedding a JavaScript interpreter in Java.
[Edit]
Here is a small example of how you can expose Java objects to your interpreted script:
public class JS {
public static void main(String args[]) throws Exception {
ScriptEngine js = new ScriptEngineManager().getEngineByName("javascript");
Bindings bindings = js.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.put("stdout", System.out);
js.eval("stdout.println(Math.cos(Math.PI));");
// Prints "-1.0" to the standard output stream.
}
}
it seems you can directly call:
g = sns.factorplot("class", "survived", "sex",
data=titanic, kind="bar",
size=6, palette="muted",
legend_out=False)
g._legend.set_bbox_to_anchor((.7, 1.1))
I had the same issue with numeral, a JS library. The fix was to install the typings again with this command:
npm install --save @types/numeral
I know this is old but here is another one in a Linear Layout would be:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="35dp">
<TextView
android:id="@+id/lblExpenseCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/cancel"
android:textColor="#404040"
android:layout_marginLeft="10dp"
android:textSize="20sp"
android:layout_marginTop="9dp" />
<Button
android:id="@+id/btnAddExpense"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:background="@drawable/stitch_button"
android:layout_marginLeft="10dp"
android:text="@string/add"
android:layout_gravity="center_vertical|bottom|right|top"
android:layout_marginRight="15dp" />
Please note the layout_gravity as opposed to just gravity.
If you aren't comfortable with using negative margins, check this out.
div {
position: fixed;
left: 50%;
bottom: 20px;
transform: translate(-50%, -50%);
margin: 0 auto;
}
<div>
Your Text
</div>
Especially useful when you don't know the width of the div.
align="center"
has no effect.
Since you have position:absolute
, I would recommend positioning it 50% from the left and then subtracting half of its width from its left margin.
#manipulate {
position:absolute;
width:300px;
height:300px;
background:#063;
bottom:0px;
right:25%;
left:50%;
margin-left:-150px;
}
This is the answer, hope it helps someone :)
First there are two variations on how the xml can be written:
<row>
<IdInvernadero>8</IdInvernadero>
<IdProducto>3</IdProducto>
<IdCaracteristica1>8</IdCaracteristica1>
<IdCaracteristica2>8</IdCaracteristica2>
<Cantidad>25</Cantidad>
<Folio>4568457</Folio>
</row>
<row>
<IdInvernadero>3</IdInvernadero>
<IdProducto>3</IdProducto>
<IdCaracteristica1>1</IdCaracteristica1>
<IdCaracteristica2>2</IdCaracteristica2>
<Cantidad>72</Cantidad>
<Folio>4568457</Folio>
</row>
Answer:
SELECT
Tbl.Col.value('IdInvernadero[1]', 'smallint'),
Tbl.Col.value('IdProducto[1]', 'smallint'),
Tbl.Col.value('IdCaracteristica1[1]', 'smallint'),
Tbl.Col.value('IdCaracteristica2[1]', 'smallint'),
Tbl.Col.value('Cantidad[1]', 'int'),
Tbl.Col.value('Folio[1]', 'varchar(7)')
FROM @xml.nodes('//row') Tbl(Col)
<row IdInvernadero="8" IdProducto="3" IdCaracteristica1="8" IdCaracteristica2="8" Cantidad ="25" Folio="4568457" />
<row IdInvernadero="3" IdProducto="3" IdCaracteristica1="1" IdCaracteristica2="2" Cantidad ="72" Folio="4568457" />
Answer:
SELECT
Tbl.Col.value('@IdInvernadero', 'smallint'),
Tbl.Col.value('@IdProducto', 'smallint'),
Tbl.Col.value('@IdCaracteristica1', 'smallint'),
Tbl.Col.value('@IdCaracteristica2', 'smallint'),
Tbl.Col.value('@Cantidad', 'int'),
Tbl.Col.value('@Folio', 'varchar(7)')
FROM @xml.nodes('//row') Tbl(Col)
Taken from:
C++
bool isPrime(int number){
if (number != 2){
if (number < 2 || number % 2 == 0) {
return false;
}
for(int i=3; (i*i)<=number; i+=2){
if(number % i == 0 ){
return false;
}
}
}
return true;
}
Javascript
function isPrime(number)
{
if (number !== 2) {
if (number < 2 || number % 2 === 0) {
return false;
}
for (var i=3; (i*i)<=number; i+=2)
{
if (number % 2 === 0){
return false;
}
}
}
return true;
}
Python
def isPrime(number):
if (number != 2):
if (number < 2 or number % 2 == 0):
return False
i = 3
while (i*i) <= number:
if(number % i == 0 ):
return False;
i += 2
return True;
You may like to first create a dialogue by right clicking the project in solution explorer and in the code file type
dialogue1.show()
that's all !!!
Variable definitions right:
$ => SCSS, SASS
-- => CSS
@ => LESS
All answers is good but question a little different than answers
"about Sass. How is SCSS different from CSS" : scss is well formed CSS3 syntax. uses sass preprocessor to create that.
and if I use SCSS instead of CSS will it work the same? yes. if your ide supports sass preprocessor. than it will work same.
Sass has two syntaxes. The most commonly used syntax is known as “SCSS” (for “Sassy CSS”), and is a superset of CSS3’s syntax. This means that every valid CSS3 stylesheet is valid SCSS as well. SCSS files use the extension .scss.
The second, older syntax is known as the indented syntax (or just “.sass”). Inspired by Haml’s terseness, it’s intended for people who prefer conciseness over similarity to CSS. Instead of brackets and semicolons, it uses the indentation of lines to specify blocks. Files in the indented syntax use the extension .sass.
What Is A CSS Preprocessor?
CSS in itself is devoid of complex logic and functionality which is required to write reusable and organized code. As a result, a developer is bound by limitations and would face extreme difficulty in code maintenance and scalability, especially when working on large projects involving extensive code and multiple CSS stylesheets. This is where CSS Preprocessors come to the rescue.
A CSS Preprocessor is a tool used to extend the basic functionality of default vanilla CSS through its own scripting language. It helps us to use complex logical syntax like – variables, functions, mixins, code nesting, and inheritance to name a few, supercharging your vanilla CSS. By using CSS Preprocessors, you can seamlessly automate menial tasks, build reusable code snippets, avoid code repetition and bloating and write nested code blocks that are well organized and easy to read. However, browsers can only understand native vanilla CSS code and will be unable to interpret the CSS Preprocessor syntax. Therefore, the complex and advanced Preprocessor syntax needs to be first compiled into native CSS syntax which can then be interpreted by the browsers to avoid cross browser compatibility issues. While different Preprocessors have their own unique syntaxes, eventually all of them are compiled to the same native CSS code.
Moving forward in the article, we will take a look at the 3 most popular CSS Preprocessors currently being used by developers around the world i.e Sass, LESS, and Stylus. Before you decide the winner between Sass vs LESS vs Stylus, let us get to know them in detail first.
Sass – Syntactically Awesome Style Sheets
Sass is the acronym for “Syntactically Awesome Style Sheets”. Sass is not only the most popular CSS Preprocessor in the world but also one of the oldest, launched in 2006 by Hampton Catlin and later developed by Natalie Weizenbaum. Although Sass is written in Ruby language, a Precompiler LibSass allows Sass to be parsed in other languages and decouple it from Ruby. Sass has a massive active community and extensive learning resources available on the net for beginners. Thanks to its maturity, stability and powerful logical prowess, Sass has established itself to the forefront of CSS Preprocessor ahead of its rival peers.
Sass can be written in 2 syntaxes either using Sass or SCSS. What is the difference between the two? Let’s find out.
Syntax Declaration: Sass vs SCSS
Consider the example below with Sass vs SCSS syntax along with Compiled CSS code.
Sass SYNTAX
$font-color: #fff
$bg-color: #00f
#box
color: $font-color
background: $bg-color
SCSS SYNTAX
$font-color: #fff;
$bg-color: #00f;
#box{
color: $font-color;
background: $bg-color;
}
In both cases, be it Sass or SCSS, the compiled CSS code will be the same –
#box {
color: #fff;
background: #00f;
Usage of Sass
Arguably the most Popular front end framework Bootstrap is written in Sass. Up until version 3, Bootstrap was written in LESS but bootstrap 4 adopted Sass and boosted its popularity. A few of the big companies using Sass are – Zapier, Uber, Airbnb and Kickstarter.
LESS – Leaner Style Sheets
LESS is an acronym for “Leaner Stylesheets”. It was released in 2009 by Alexis Sellier, 3 years after the initial launch of Sass in 2006. While Sass is written in Ruby, LESS is written JavaScript. In fact, LESS is a JavaScript library that extends the functionality of native vanilla CSS with mixins, variables, nesting and rule set loop. Sass vs LESS has been a heated debate. It is no surprise that LESS is the strongest competitor to Sass and has the second-largest user base. However, When bootstrap dumped LESS in favor of Sass with the launch of Bootstrap 4, LESS has waned in popularity. One of the few disadvantages of LESS over Sass is that it does not support functions. Unlike Sass, LESS uses @ to declare variables which might cause confusion with @media and @keyframes. However, One key advantage of LESS over Sass and Stylus or any other preprocessors, is the ease of adding it in your project. You can do that either by using NPM or by incorporating Less.js file. Syntax Declaration: LESS Uses .less extension. Syntax of LESS is quite similar to SCSS with the exception that for declaring variables, instead of $ sign, LESS uses @.
@font-color: #fff;
@bg-color: #00f
#box{
color: @font-color;
background: @bg-color;
}
COMPILED CSS
#box {
color: #fff;
background: #00f;
}
Usage Of LESS The popular Bootstrap framework until the launch of version 4 was written in LESS. However, another popular framework called SEMANTIC UI is still written in LESS. Among the big companies using Sass are – Indiegogo, Patreon, and WeChat
Stylus
The stylus was launched in 2010 by former Node JS developer TJ Holowaychuk, nearly 4 years after the release of Sass and 1 year after the release of LESS. The stylus is written Node JS and fits perfectly with JS stack. The stylus was heavily influenced by the logical prowess of the Sass and simplicity of LESS. Even though Stylus is still popular with Node JS developers, it hasn’t managed to carve out a sizeable share for itself. One advantage of Stylus over Sass or LESS, is that it is armed with extremely powerful built-in functions and is capable of handling heavy computing.
Syntax Declaration: Stylus Uses .styl extension. Stylus offers a great deal of flexibility in writing syntax, supports native CSS as well as allows omission of brackets colons and semicolons. Also, note that Stylus does not use @ or $ symbols for defining variables. Instead, Stylus uses the assignment operators to indicate a variable declaration.
STYLUS SYNTAX WRITTEN LIKE NATIVE CSS
font-color = #fff;
bg-color = #00f;
#box {
color: font-color;
background: bg-color;
}
OR
STYLUS SYNTAX WITHOUT CURLY BRACES
font-color = #fff;
bg-color = #00f;
#box
color: font-color;
background: bg-color;
OR
STYLUS SYNTAX WITHOUT COLONS AND SEMICOLONS
font-color = #fff
bg-color = #00f
#box
color font-color
background bg-color
If you use RAC then you need to use GV$*
views instead V$*
.
Try to find your session by
select * from gv$session where username = 'test';
and then you can kill the session by
alter system kill session 'sid, serial#, @inst_id' immediate;
Aside from the one being ANSI and speed etc., there is a very important difference that always matters to me; more than ANSI and speed. The number of bugs I have fixed due to this important overlook is large. I look for this during code reviews all the time.
-- Arrange
create table Employee (EmployeeId int);
insert into dbo.Employee values (1);
insert into dbo.Employee values (2);
insert into dbo.Employee values (3);
-- Act
declare @employeeId int;
select @employeeId = e.EmployeeId from dbo.Employee e;
-- Assert
-- This will print 3, the last EmployeeId from the query (an arbitrary value)
-- Almost always, this is not what the developer was intending.
print @employeeId;
Almost always, that is not what the developer is intending. In the above, the query is straight forward but I have seen queries that are quite complex and figuring out whether it will return a single value or not, is not trivial. The query is often more complex than this and by chance it has been returning single value. During developer testing all is fine. But this is like a ticking bomb and will cause issues when the query returns multiple results. Why? Because it will simply assign the last value to the variable.
Now let's try the same thing with SET
:
-- Act
set @employeeId = (select e.EmployeeId from dbo.Employee e);
You will receive an error:
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
That is amazing and very important because why would you want to assign some trivial "last item in result" to the @employeeId
. With select
you will never get any error and you will spend minutes, hours debugging.
Perhaps, you are looking for a single Id and SET
will force you to fix your query. Thus you may do something like:
-- Act
-- Notice the where clause
set @employeeId = (select e.EmployeeId from dbo.Employee e where e.EmployeeId = 1);
print @employeeId;
Cleanup
drop table Employee;
In conclusion, use:
SET
: When you want to assign a single value to a variable and your variable is for a single value.SELECT
: When you want to assign multiple values to a variable. The variable may be a table, temp table or table variable etc. Python has a "not" operator, right? Is it not just "not"? As in,
return not bool
I had a similar question and this answer in question HTML: table of forms? solved it for me. (Not sure if it is XHTML, but it works in an HTML5 browser.)
You can use css to give table layout to other elements.
.table { display: table; }
.table>* { display: table-row; }
.table>*>* { display: table-cell; }
Then you use the following valid html.
<div class="table">
<form>
<div>snake<input type="hidden" name="cartitem" value="55"></div>
<div><input name="count" value="4" /></div>
</form>
</div>
What can be really convenient:
Find the commit hash you want to squash on top of, say d43e15
.
Now use
git reset d43e15
git commit -am 'new commit name'
$.ajax({
url:url,
type:"POST",
data:data,
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(){
...
}
})
See : jQuery.ajax()
This is the complete basic structure for 100% width layout in Bootstrap v3.0.0. You shouldn't wrap your <div class="row">
with container
class. Cause container
class will take lots of margin and this will not provide you full screen (100% width) layout where bootstrap has removed container-fluid class from their mobile-first version v3.0.0.
So just start writing <div class="row">
without container class and you are ready to go with 100% width layout.
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Basic 100% width Structure</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="http://getbootstrap.com/assets/js/html5shiv.js"></script>
<script src="http://getbootstrap.com/assets/js/respond.min.js"></script>
<![endif]-->
<style>
.red{
background-color: red;
}
.green{
background-color: green;
}
</style>
</head>
<body>
<div class="row">
<div class="col-md-3 red">Test content</div>
<div class="col-md-9 green">Another Content</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="//code.jquery.com/jquery.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
</body>
</html>
To see the result by yourself I have created a bootply. See the live output there. http://bootply.com/82136 And the complete basic bootstrap 3 100% width layout I have created a gist. you can use that. Get the gist from here
Reply me if you need more further assistance. Thanks.
Simple ASP.NET MVC subscription form with email textbox would be implemented like that:
The data from the form is mapped to this model
public class SubscribeModel
{
[Required]
public string Email { get; set; }
}
View name should match controller method name.
@model App.Models.SubscribeModel
@using (Html.BeginForm("Subscribe", "Home", FormMethod.Post))
{
@Html.TextBoxFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
<button type="submit">Subscribe</button>
}
Controller is responsible for request processing and returning proper response view.
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Subscribe(SubscribeModel model)
{
if (ModelState.IsValid)
{
//TODO: SubscribeUser(model.Email);
}
return View("Index", model);
}
}
Here is my project structure. Please notice, "Home" views folder matches HomeController name.
For rows you can simply use wc -l file
-l
stands for total line
for columns uou can simply use head -1 file | tr ";" "\n" | wc -l
Explanation
head -1 file
Grabbing the first line of your file, which should be the headers,
and sending to it to the next cmd through the pipe
| tr ";" "\n"
tr
stands for translate.
It will translate all ;
characters into a newline character.
In this example ;
is your delimiter.
Then it sends data to next command.
wc -l
Counts the total number of lines.
What you want is called a pivot, and it's not directly supported in MySQL, check this answer out for the options you've got:
The usage of org.apache.commons.httpclient.URI
is not strictly an issue; what is an issue is that you target the wrong constructor, which is depreciated.
Using just
new URI( [string] );
Will indeed flag it as depreciated. What is needed is to provide at minimum one additional argument (the first, below), and ideally two:
escaped
: true if URI character sequence is in escaped form. false otherwise.charset
: the charset string to do escape encoding, if
requiredThis will target a non-depreciated constructor within that class. So an ideal usage would be as such:
new URI( [string], true, StandardCharsets.UTF_8.toString() );
A bit crazy-late in the game (a hair over 11 years later - egad!), but I hope this helps someone else, especially if the method at the far end is still expecting a URI, such as org.apache.commons.httpclient.setURI()
.
I refined Twentyfortysix answer a bit, to only trigger the event after the resize is done.
In addition I added check for the width of the window, so it won't trigger the reinitialisation on Android.
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_EN/sdk.js#xfbml=1&version=v2.3";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
jQuery(document).ready(function($) {
var oldwidth = $(window).width();
var timeout;
var recalc = function() {
clearTimeout(timeout);
timeout = setTimeout(function() {
var container_width = $('#fbcontainer').width();
$('#fbcontainer').html('<div class="fb-page" ' +
'data-href="YOUR FACEBOOK PAGE URL"' +
' data-width="' + container_width + '" data-height="750" data-adapt-container-width="true" data-hide-cover="false" data-show-facepile="true" data-show-posts="true"><div class="fb-xfbml-parse-ignore"><blockquote cite="YOUR FACEBOOK PAGE URL"><a href="YOUR FACEBOOK PAGE URL">YOUR FACEBOOK PAGE TITLE</a></blockquote></div></div>');
if(typeof FB !== 'undefined') {
FB.XFBML.parse( );
}
}, 100);
};
recalc();
$(window).bind("resize", function(){
if(oldwidth !== $(window).width()) {
recalc();
oldwidth = $(window).width();
}
});
});
Not sure if this is still relevant, but I use this way
Public bEnableEvents As Boolean
Public bclickok As Boolean
Public booRestoreErrorChecking As Boolean 'put this at the top of the module
Private Declare Function apiGetComputerName Lib "kernel32" Alias _
"GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
Private Declare Function apiGetUserName Lib "advapi32.dll" Alias _
"GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long
Function GetUserID() As String
' Returns the network login name
On Error Resume Next
Dim lngLen As Long, lngX As Long
Dim strUserName As String
strUserName = String$(254, 0)
lngLen = 255
lngX = apiGetUserName(strUserName, lngLen)
If lngX <> 0 Then
GetUserID = Left$(strUserName, lngLen - 1)
Else
GetUserID = ""
End If
Exit Function
End Function
This next bit I save file as PDF, but can change to suit
Public Sub SaveToDesktop()
Dim LoginName As String
LoginName = UCase(GetUserID)
ChDir "C:\Users\" & LoginName & "\Desktop\"
Debug.Print LoginName
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\Users\" & LoginName & "\Desktop\MyFileName.pdf", Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
True
End Sub
You can use int casting which allows the base specification.
int(b, 2) # Convert a binary string to a decimal int.
Quote your args in Testscript 1:
echo "TestScript1 Arguments:"
echo "$1"
echo "$2"
echo "$#"
./testscript2 "$1" "$2"
I had to use the \COPY because I received the error message:
ERROR: could not open file "/filepath/places.csv" for writing: Permission denied
So I used:
\Copy (Select address, zip From manjadata) To '/filepath/places.csv' With CSV;
and it is functioning
If you are using Notepad++ editor Goto ctrl + F choose tab 3 find in files and enter:
Assuming there are a few ignore directories, why not use "git status node/logs/" which will tell you what files are to be added? In the directory I have a text file that is not part of status output, e.g.:
On branch master
Your branch is up-to-date with 'origin/master'.
Untracked files:
(use "git add ..." to include in what will be committed)
node/logs/.gitignore
.gitignore is:
*
!.gitignore
public string GetClientIp() {
var ipAddress = string.Empty;
if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null) {
ipAddress = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
} else if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"] != null &&
System.Web.HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"].Length != 0) {
ipAddress = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"];
} else if (System.Web.HttpContext.Current.Request.UserHostAddress.Length != 0) {
ipAddress = System.Web.HttpContext.Current.Request.UserHostName;
}
return ipAddress;
}
works perfect
postgres (since version 9.0) allows anonymous blocks in any of the supported server-side scripting languages
DO '
DECLARE somevariable int = -1;
BEGIN
INSERT INTO foo VALUES ( somevariable );
END
' ;
http://www.postgresql.org/docs/current/static/sql-do.html
As everything is inside a string, external string variables being substituted in will need to be escaped and quoted twice. Using dollar quoting instead will not give full protection against SQL injection.
AutopostBack :
AutopostBack is a property of the controls which enables the post back on the changes of the web control.
Difference between AutopostBack=True and AutoPostBack=False:
If the AutopostBack property is set to true, a post back is sent immediately to the server
If the AutopostBack property is set to false, then no post back occurs.
For completeness:
https://developer.chrome.com/multidevice/android/installtohomescreen
Does Add to homescreen work on Chrome for iOS?
No.
Having looked at the documentation, I believe that the following is cleaner:
let version =
NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString")
as? String
Source: "Use of this method is preferred over other access methods because it returns the localized value of a key when one is available."
In my index.php I'm loading maybe foobarfunc() like this:
foobar::foobarfunc(); // Wrong, it is not static method
but can also be
$foobar = new foobar; // correct
$foobar->foobarfunc();
You can not invoke method this way because it is not static method.
foobar::foobarfunc();
You should instead use:
foobar->foobarfunc();
If however you have created a static method something like:
static $foo; // your top variable set as static
public static function foo() {
return self::$foo;
}
then you can use this:
foobar::foobarfunc();
Two ways you can do that:
Removing JDK directly from Users-> Library -> Java -> VirtualMachines -> then delete the jdk folder directly to uninstall the java.
By following the command: (uninstall java 1.8 version )
make sure you are in home directory by using below command, before you write the command:
cd ~/
sudo rm -rf /Library/Java/JavaVirtualMachines/jdk1.8.jdk
sudo rm -rf /Library/PreferencePanes/JavaControlPanel.prefPane
sudo rm -rf /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin
sudo rm -rf /Library/Application\ Support/Oracle/Java
Call runnable whenever you want:
runOnUiThread(run);
OnCreate()
, you set your runnable thread:
run = new Runnable() {
public void run() {
//reload content
arraylist.clear();
arraylist.addAll(db.readAll());
adapter.notifyDataSetChanged();
listview.invalidateViews();
listview.refreshDrawableState();
}
};
First initialize Property values
MutablePropertyValues mutablePropertyValues = new MutablePropertyValues();
mutablePropertyValues.add("hostName", details.getHostName());
mutablePropertyValues.add("port", details.getPort());
DefaultListableBeanFactory context = new DefaultListableBeanFactory();
GenericBeanDefinition connectionFactory = new GenericBeanDefinition();
connectionFactory.setBeanClass(Class);
connectionFactory.setPropertyValues(mutablePropertyValues);
context.registerBeanDefinition("beanName", connectionFactory);
Add to the list of beans
ConfigurableListableBeanFactory beanFactory = ((ConfigurableApplicationContext) applicationContext).getBeanFactory();
beanFactory.registerSingleton("beanName", context.getBean("beanName"));
The TextBoxFor
is a newer MVC input extension introduced in MVC2.
The main benefit of the newer strongly typed extensions is to show any errors / warnings at compile-time rather than runtime.
See this page.
http://weblogs.asp.net/scottgu/archive/2010/01/10/asp-net-mvc-2-strongly-typed-html-helpers.aspx
The code compiles ok for me. May be you have forgotten to add the import:
import android.app.AlertDialog;
Anyway, you have a good tutorial here.
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
The following example demonstrates how to POST a JSON via WebClient.UploadString Method:
var vm = new { k = "1", a = "2", c = "3", v= "4" };
using (var client = new WebClient())
{
var dataString = JsonConvert.SerializeObject(vm);
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
client.UploadString(new Uri("http://www.contoso.com/1.0/service/action"), "POST", dataString);
}
Prerequisites: Json.NET library
public enum Gender {
MALE,
FEMALE
}
You can use this:
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
// Actions to do after 10 seconds
}
}, 10000);
For Stop the Handler, You can try this:
handler.removeCallbacksAndMessages(null);
I had similar issue/error while running JunitCore along side with Junit Jupiter(Junit5) JUnitCore.runClasses(classes);
after removing @RunWith(SpringRunner.class)
and
ran with @SpringBootTest @FixMethodOrder(MethodSorters.NAME_ASCENDING)
i am able to resolve the issue for my tests as said in the above comments.
https://stackoverflow.com/a/59563970/13542839
Simple jQuery solution
Use this if your selects have the readonly
class
jQuery('select.readonly option:not(:selected)').attr('disabled',true);
Or this if your selects have the readonly="readonly"
attribute
$('select[readonly="readonly"] option:not(:selected)').attr('disabled',true);
it can be like this as well:
-vm
C:\Program Files\Java\jre6\bin\server\jvm.dll
Your groups_main
table has a key column named id
. I believe you can only use the USING
syntax for the join if the groups_fans
table has a key column with the same name, which it probably does not. So instead, try this:
LEFT JOIN groups_fans AS m ON m.group_id = g.id
Or replace group_id
with whatever the appropriate column name is in the groups_fans
table.
In order to do this without FuncAnimation (eg you want to execute other parts of the code while the plot is being produced or you want to be updating several plots at the same time), calling draw
alone does not produce the plot (at least with the qt backend).
The following works for me:
import matplotlib.pyplot as plt
plt.ion()
class DynamicUpdate():
#Suppose we know the x range
min_x = 0
max_x = 10
def on_launch(self):
#Set up plot
self.figure, self.ax = plt.subplots()
self.lines, = self.ax.plot([],[], 'o')
#Autoscale on unknown axis and known lims on the other
self.ax.set_autoscaley_on(True)
self.ax.set_xlim(self.min_x, self.max_x)
#Other stuff
self.ax.grid()
...
def on_running(self, xdata, ydata):
#Update data (with the new _and_ the old points)
self.lines.set_xdata(xdata)
self.lines.set_ydata(ydata)
#Need both of these in order to rescale
self.ax.relim()
self.ax.autoscale_view()
#We need to draw *and* flush
self.figure.canvas.draw()
self.figure.canvas.flush_events()
#Example
def __call__(self):
import numpy as np
import time
self.on_launch()
xdata = []
ydata = []
for x in np.arange(0,10,0.5):
xdata.append(x)
ydata.append(np.exp(-x**2)+10*np.exp(-(x-7)**2))
self.on_running(xdata, ydata)
time.sleep(1)
return xdata, ydata
d = DynamicUpdate()
d()
git
isn't a centralized scm like svn
so you have two options:
It may be annoying to implement for many different platforms (GitHub, GitLab, BitBucket, SourceForge, Launchpad, Gogs, ...) but fetching data is pretty slow (we talk about seconds) - no solution is perfect.
An example with fetching into a temporary directory:
git clone https://github.com/rust-lang/rust.git -b master --depth 3 --bare --filter=blob:none -q .
git log -n 3 --no-decorate --format=oneline
Alternatively:
git init --bare -q
git remote add -t master origin https://github.com/rust-lang/rust.git
git fetch --depth 3 --filter=blob:none -q
git log -n 3 --no-decorate --format=oneline origin/master
Both are optimized for performance by restricting to exactly 3 commits of one branch into a minimal local copy without file contents and preventing console outputs. Though opening a connection and calculating deltas during fetch takes some time.
An example with GitHub:
GET https://api.github.com/repos/rust-lang/rust/commits?sha=master&per_page=3
An example with GitLab:
GET https://gitlab.com/api/v4/projects/inkscape%2Finkscape/repository/commits?ref_name=master&per_page=3
Both are really fast but have different interfaces (like every platform).
Disclaimer: Rust and Inkscape were chosen because of their size and safety to stay, no advertisement
Here's what you need to do to fix the issue on Arch Linux :
Enable the multilib
repository on your system if you have not already done so by uncommenting the [multilib]
section in /etc/pacman.conf
:
[multilib]
Include = /etc/pacman.d/mirrorlist
Update pacman :
# pacman -Suy
Install the 32 bit version of libstdc++5 :
# pacman -S lib32-libstdc++5
$request->flash('request',$request);
<input type="text" class="form-control" name="name" value="{{ old('name') }}">
It works for me.
Using Ref forwarding you can pass the ref from parent to further down to a child.
const FancyButton = React.forwardRef((props, ref) => (
<button ref={ref} className="FancyButton">
{props.children}
</button>
));
// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;
Note The second ref argument only exists when you define a component with React.forwardRef call. Regular functional or class components don’t receive the ref argument, and ref is not available in props either.
Ref forwarding is not limited to DOM components. You can forward refs to class component instances, too.
Reference: React Documentation.
You also need to replace your indexes:
class RenameOldTableToNewTable< ActiveRecord:Migration
def self.up
remove_index :old_table_name, :column_name
rename_table :old_table_name, :new_table_name
add_index :new_table_name, :column_name
end
def self.down
remove_index :new_table_name, :column_name
rename_table :new_table_name, :old_table_name
add_index :old_table_name, :column_name
end
end
And rename your files etc, manually as other answers here describe.
See: http://api.rubyonrails.org/classes/ActiveRecord/Migration.html
Make sure you can rollback and roll forward after you write this migration. It can get tricky if you get something wrong and get stuck with a migration that tries to effect something that no longer exists. Best trash the whole database and start again if you can't roll back. So be aware you might need to back something up.
Also: check schema_db for any relevant column names in other tables defined by a has_ or belongs_to or something. You'll probably need to edit those too.
And finally, doing this without a regression test suite would be nuts.
The solutions given here actually do not take into account multi-byte Unicode characters ("composed characters"), and could result in invalid Unicode strings.
In fact, the iOS header file which contains the declaration of substringToIndex
contains the following comment:
Hint: Use with rangeOfComposedCharacterSequencesForRange: to avoid breaking up composed characters
See how to use rangeOfComposedCharacterSequenceAtIndex:
to delete the last character correctly.
The solution to this problem depends on the version of the Android support library you're using:
26.0.0-beta2
This android support library version has a bug causing the mentioned problem
In your Gradle build file use:
compile 'com.android.support:appcompat-v7:26.0.0'
with:
buildToolsVersion '26.0.0'
and
classpath 'com.android.tools.build:gradle:3.0.0-alpha8'
everything should work fine now.
These new versions seem to suffer from similar difficulties again.
In your res/values/styles.xml
modify the AppTheme
style from
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
to
<style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">
(note the added Base.
)
Or alternatively downgrade the library until the problem is fixed:
implementation 'com.android.support:appcompat-v7:28.0.0-alpha1'
those icons are a way of Egit to show you status of the current file/folder in git. You might want to check this out:
Try passing it directly to the ng-click function:
<div class="col-lg-1 text-center">
<span class="glyphicon glyphicon-trash" data="{{event.id}}"
ng-click="deleteEvent(event.id)"></span>
</div>
Then it should be available in your handler:
$scope.deleteEvent=function(idPassedFromNgClick){
console.log(idPassedFromNgClick);
}
Here's an example
The MitM Me addon will do this - but I think self-signed certificates is probably a better solution.
You could do that like this:
<script type="text/javascript">
function product(a,b)
{
return a*b;
}
document.getElementById('myvalue').value = product(a,b);
</script>
<input type="hidden" value="THE OUTPUT OF PRODUCT FUNCTION" id="myvalue">
Adding to other answers already given above. If case insensivity is of any importance to you, then use Jackson. Gson does not support case insensitivity for key names, while jackson does.
Here are two related links
(No) Case sensitivity support in Gson : GSON: How to get a case insensitive element from Json?
Case sensitivity support in Jackson https://gist.github.com/electrum/1260489
As people have said, in Windows, I just dropped my pem file in C:\Users[user].ssh\ and that solved it. Although you can do chmod and other command line options from a bash or powershell prompt that didn't work. I didn't change rsa or anything else. Then when running the connection you have to put the path to the pem file in the .ssh folder:
ssh -i "C:\Users[user].ssh\ubuntukp01.pem" ubuntu@ec[ipaddress].us-west-2.compute.amazonaws.com
Try this:
SELECT table_name
FROM information_schema.tables
WHERE table_schema='public' AND table_type='BASE TABLE'
this one works!
i myself do it with directx and think it's as fast as you would want it to be. i don't have a quick code sample, but i found this which should be useful. the directx11 version should not differ a lot, directx9 maybe a little more, but thats the way to go
dynDiv.Attributes["class"] = "myCssClass";
This work for me:
public static void main(String[] args) {
Properties props = new Properties();
props.load(new FileInputStream("src/log4j.properties"));
PropertyConfigurator.configure(props);
In ~/.subversion/auth/svn.simple/
you should find a file with a long hexadecimal name. The password is in there in plaintext.
If there is more than one file you'll need to find that one that references the server you need the password for.
My application failed to start via "Task Scheduler".
The error in "Event Viewer" is: System.IO.DirectoryNotFoundException
The "Task Scheduler" tries to run this application with the "SYSTEM" user. The problem was that a "network drive" was not mapped for the "SYSTEM" user. So what I did was, I created a ".bat" file and mapped the "network drive" before starting the application:
net use T: \\172.20.2.215\images
cd C:\MyApplication
start MyApplication.exe
So check your logs first: "Event Viewer" -> Windows Logs -> Application
git reset --hard
This command will completely remove all the local changes from your local repository. This is the best way to avoid conflicts during pull command, only if you don't want to keep your local changes at all.
If you want to pull the new changes from remote and want to ignore the local changes during this pull then,
git stash
It will stash all the local changes, now you can pull the remote changes,
git pull
Now, you can bring back your local changes by,
git stash pop
@echo off
title Test
echo Select a language. (de/en)
set /p language=
IF /i "%language%"=="de" goto languageDE
IF /i "%language%"=="en" goto languageEN
echo Not found.
goto commonexit
:languageDE
echo German
goto commonexit
:languageEN
echo English
goto commonexit
:commonexit
pause
The point is that batch simply continues through instructions, line by line until it reaches a goto
, exit
or end-of-file. It has no concept of sections
to control flow.
Hence, entering de
would jump to :languagede
then simply continue executing instructions until the file ends, showing de
then en
then not found
.
If you use linq and want to keep your code short, I recommand to always use !=null
And this is why:
Let imagine we have some class Foo
with a nullable double variable SomeDouble
public class Foo
{
public double? SomeDouble;
//some other properties
}
If somewhere in our code we want to get all Foo with a non null SomeDouble values from a collection of Foo (assuming some foos in the collection can be null too), we end up with at least three way to write our function (if we use C# 6) :
public IEnumerable<Foo> GetNonNullFoosWithSomeDoubleValues(IEnumerable<Foo> foos)
{
return foos.Where(foo => foo?.SomeDouble != null);
return foos.Where(foo=>foo?.SomeDouble.HasValue); // compile time error
return foos.Where(foo=>foo?.SomeDouble.HasValue == true);
return foos.Where(foo=>foo != null && foo.SomeDouble.HasValue); //if we don't use C#6
}
And in this kind of situation I recommand to always go for the shorter one
For me, when I was about to unpair my device from xcode, I noticed it was just Preparing debugger support for my iPhone and it told me that "Xcode will continue when iPhone is finished." Similar to this issue
From the .NET blog Announcing .NET 2015 Preview: A New Era for .NET:
.NET Core has two major components. It includes a small runtime that is built from the same codebase as the .NET Framework CLR. The .NET Core runtime includes the same GC and JIT (RyuJIT), but doesn’t include features like Application Domains or Code Access Security. The runtime is delivered via NuGet, as part of the [ASP.NET Core] package.
.NET Core also includes the base class libraries. These libraries are largely the same code as the .NET Framework class libraries, but have been factored (removal of dependencies) to enable us to ship a smaller set of libraries. These libraries are shipped as System.* NuGet packages on NuGet.org.
And:
[ASP.NET Core] is the first workload that has adopted .NET Core. [ASP.NET Core] runs on both the .NET Framework and .NET Core. A key value of [ASP.NET Core] is that it can run on multiple versions of [.NET Core] on the same machine. Website A and website B can run on two different versions of .NET Core on the same machine, or they can use the same version.
In short: first, there was the Microsoft .NET Framework, which consists of a runtime that executes application and library code, and a nearly fully documented standard class library.
The runtime is the Common Language Runtime, which implements the Common Language Infrastructure, works with The JIT compiler to run the CIL (formerly MSIL) bytecode.
Microsoft's specification and implementation of .NET were, given its history and purpose, very Windows- and IIS-centered and "fat". There are variations with fewer libraries, namespaces and types, but few of them were useful for web or desktop development or are troublesome to port from a legal standpoint.
So in order to provide a non-Microsoft version of .NET, which could run on non-Windows machines, an alternative had to be developed. Not only the runtime has to be ported for that, but also the entire Framework Class Library to become well-adopted. On top of that, to be fully independent from Microsoft, a compiler for the most commonly used languages will be required.
Mono is one of few, if not the only alternative implementation of the runtime, which runs on various OSes besides Windows, almost all namespaces from the Framework Class Library as of .NET 4.5 and a VB and C# compiler.
Enter .NET Core: an open-source implementation of the runtime, and a minimal base class library. All additional functionality is delivered through NuGet packages, deploying the specific runtime, framework libraries and third-party packages with the application itself.
ASP.NET Core is a new version of MVC and WebAPI, bundled together with a thin HTTP server abstraction, that runs on the .NET Core runtime - but also on the .NET Framework.
app.js add
app.set('view engine','ejs')
add your partial file(ejs) in views/partials
in index.ejs
<%- include('partials/header.ejs') %>
//1 year from today's date
echo date('d-m-Y', strtotime('+1 year'));
//1 year from from specific date
echo date('22-09-Y', strtotime('+1 year'));
hope this simpler bit of code helps someone in future :)
Change below path in httpd.conf file to your setup. This will fix the issue.
Define SRVROOT "C:\Apache24"
ServerRoot "${SRVROOT}"
The asker should use STAS answer, but for readers who use prism and no galasoft/mvvmlight, they may want to try what I used:
In the definition at the top for window or usercontrol, etc define namespace:
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
And just below that definition:
<i:Interaction.Triggers>
<i:EventTrigger EventName="Closing">
<i:InvokeCommandAction Command="{Binding WindowClosing}" CommandParameter="{Binding}" />
</i:EventTrigger>
</i:Interaction.Triggers>
Property in your viewmodel:
public ICommand WindowClosing { get; private set; }
Attach delegatecommand in your viewmodel constructor:
this.WindowClosing = new DelegateCommand<object>(this.OnWindowClosing);
Finally, your code you want to reach on close of the control/window/whatever:
private void OnWindowClosing(object obj)
{
//put code here
}
You can use
"Hello World ".replace(/\s+/g, '');
trim()
only removes trailing spaces on the string (first and last on the chain).
In this case this regExp is faster because you can remove one or more spaces at the same time.
If you change the replacement empty string to '$', the difference becomes much clearer:
var string= ' Q W E R TY ';
console.log(string.replace(/\s/g, '$')); // $$Q$$W$E$$$R$TY$
console.log(string.replace(/\s+/g, '#')); // #Q#W#E#R#TY#
Performance comparison - /\s+/g
is faster. See here: http://jsperf.com/s-vs-s
You can run something like this:
sqlcmd -S MyServer -d myDB -E -Q "select col1, col2, col3 from SomeTable"
-o "MyData.csv" -h-1 -s"," -w 700
-h-1
removes column name headers from the result-s","
sets the column seperator to , -w 700
sets the row width to 700 chars (this will need to be as wide as the longest row or it will wrap to the next line)A typical way would be to use stringstream
:
#include <iomanip>
#include <sstream>
double pi = 3.14159265359;
std::stringstream stream;
stream << std::fixed << std::setprecision(2) << pi;
std::string s = stream.str();
See fixed
Use fixed floating-point notation
Sets the
floatfield
format flag for the str stream tofixed
.When
floatfield
is set tofixed
, floating-point values are written using fixed-point notation: the value is represented with exactly as many digits in the decimal part as specified by the precision field (precision
) and with no exponent part.
and setprecision.
For conversions of technical purpose, like storing data in XML or JSON file, C++17 defines to_chars family of functions.
Assuming a compliant compiler (which we lack at the time of writing), something like this can be considered:
#include <array>
#include <charconv>
double pi = 3.14159265359;
std::array<char, 128> buffer;
auto [ptr, ec] = std::to_chars(buffer.data(), buffer.data() + buffer.size(), pi,
std::chars_format::fixed, 2);
if (ec == std::errc{}) {
std::string s(buffer.data(), ptr);
// ....
}
else {
// error handling
}
Try to do an UPDATE. If it doesn't modify any row that means it didn't exist, so do an insert. Obviously, you do this inside a transaction.
You can of course wrap this in a function if you don't want to put the extra code on the client side. You also need a loop for the very rare race condition in that thinking.
There's an example of this in the documentation: http://www.postgresql.org/docs/9.3/static/plpgsql-control-structures.html, example 40-2 right at the bottom.
That's usually the easiest way. You can do some magic with rules, but it's likely going to be a lot messier. I'd recommend the wrap-in-function approach over that any day.
This works for single row, or few row, values. If you're dealing with large amounts of rows for example from a subquery, you're best of splitting it into two queries, one for INSERT and one for UPDATE (as an appropriate join/subselect of course - no need to write your main filter twice)
Create specific .yml files in the resources directory for each and every environment(Eg: dev,qa,stg etc.) that you need to run the application. image of .yml files in resources directory
If you are using spring-boot-maven-plugin 2.0.5.RELEASE in your pom.xml file you can add the profiles within the dependency tag as follows. image of pom.xml spring-boot-maven-plugin (you can configure multiple profiles using multiple profile tags)
Then you can use the following commands to build and run the project.
1) mvn clean install
2) mvn spring-boot:run -Dspring-boot.run.default==qa
Then you will see that the default profile is set as qa while running the project. displaying the default profile when running the application
Check this answer: Set CORS header in Tomcat
Note that you need Tomcat 7.0.41 or higher.
To know where the current instance of Tomcat is located try this:
System.out.println(System.getProperty("catalina.base"));
You'll see the path in the console view.
Then look for /conf/web.xml on that folder, open it and add the lines of the above link.
In my experience, first name/last name fields should be at least 48 characters -- there are names from some countries such as Malaysia or India that are very long in their full form.
Phone numbers and postcodes you should always treat as text, not numbers. The normal reason given is that there are postcodes that begin with 0, and in some countries, phone numbers can also begin with 0. But the real reason is that they aren't numbers -- they're identifiers that happen to be made up of numerical digits (and that's ignoring countries like Canada that have letters in their postcodes). So store them in a text field.
In MySQL you can use VARCHAR fields for this type of information. Whilst it sounds lazy, it means you don't have to be too concerned about the right minimum size.
There's no need to use extra large tables or ALL_OBJECTS table:
SELECT TRUNC (SYSDATE - ROWNUM) dt
FROM DUAL CONNECT BY ROWNUM < 366
will do the trick.
You can use: <xsl:text> </xsl:text>
see the example
<xsl:variable name="module-info">
<xsl:value-of select="@name" /> = <xsl:value-of select="@rev" />
<xsl:text> </xsl:text>
</xsl:variable>
if you write this in file e.g.
<redirect:write file="temp.prop" append="true">
<xsl:value-of select="$module-info" />
</redirect:write>
this variable will produce a new line infile as:
commons-dbcp_commons-dbcp = 1.2.2
junit_junit = 4.4
org.easymock_easymock = 2.4
$ pip install pickle5
import pickle5 as pickle
pb = pickle.PickleBuffer(b"foo")
data = pickle.dumps(pb, protocol=5)
assert pickle.loads(data) == b"foo"
This package backports all features and APIs added in the pickle module in Python 3.8.3, including the PEP 574 additions. It should work with Python 3.5, 3.6 and 3.7.
Basic usage is similar to the pickle module, except that the module to be imported is pickle5:
SELECT Reservations.idCustomer FROM Reservations (nolock)
LEFT OUTER JOIN @reservations ExcludedReservations (nolock) ON Reservations.idCustomer=ExcludedReservations.idCustomer AND DATEPART(hour, ExcludedReservations.insertDate) < 2
WHERE ExcludedReservations.idCustomer IS NULL AND Reservations.idCustomer IS NOT NULL
GROUP BY Reservations.idCustomer
[Update: Added additional criteria to handle idCustomer being NULL, which was apparently the main issue the original poster had]
This works:
@media not all and (min-resolution:.001dpcm) {
@media {
/* your code for Safari Desktop & Mobile */
body {
background-color: red;
color: blue;
}
/* end */
}
}
I moved a database mdf from the default Data folder to my asp.net app_data folder and ran into this problem trying to set the database back online.
I compared the security settings of the other file databases in the original location to the moved files and noticed that MSSQL$SQLEXPRESS was not assigned permissions to the files in their new location. I added Full control for "NT SERVICE\MSSQL$SQLEXPRESS" (must include that NT SERVICE) and it attached just fine.
It appears that the original Data folder has these permissions and the files inherit it. Move the files and the inheritance breaks of course.
I checked another project's mdf file which I created directly into its app_data folder. it does not have MSSQL$SQLEXPRESS permissions. Hmmm. I wonder why SQL Express likes one but not the other?
And for those of you using an anonymous expression:
await Task.Run(async () =>
{
SQLLiteUtils slu = new SQLiteUtils();
await slu.DeleteGroupAsync(groupname);
});
That isn't the Node.js command prompt window. That is a language shell to run JavaScript commands, also known as a REPL.
In Windows, there should be a Node.js command prompt in your Start menu or start screen:
Which will open a command prompt window that looks like this:
From there you can switch directories using the cd
command.
FYI, this is probably faster,
SELECT count(1) FROM (SELECT distinct productId WHERE keyword = '$keyword') temp
than this,
SELECT COUNT(DISTINCT productId) WHERE keyword='$keyword'
Custom SerDe might be a way to do it. Or you could use some kind of mediation process with regex_replace:
create table tableB as
select
columnA
regexp_replace(description, '\\t', '') as description
from tableA
;
Is not nice to define textbox width without using CSS, be warned ;-)
<input type="text" name="d" value="4" size="4" />
To fully overload it you also need to implement the __setitem__
and __delitem__
methods.
edit
I almost forgot... if you want to completely emulate a list, you also need __getslice__, __setslice__ and __delslice__
.
There are all documented in http://docs.python.org/reference/datamodel.html
Why not just use this?
var interopHelper = new WindowInteropHelper(System.Windows.Application.Current.MainWindow);
var activeScreen = Screen.FromHandle(interopHelper.Handle);
Horizontal scrollbars in a HTML Select are not natively supported. However, here's a way to create the appearance of a horizontal scrollbar:
1. First create a css class
<style type="text/css">
.scrollable{
overflow: auto;
width: 70px; /* adjust this width depending to amount of text to display */
height: 80px; /* adjust height depending on number of options to display */
border: 1px silver solid;
}
.scrollable select{
border: none;
}
</style>
2. Wrap the SELECT inside a DIV - also, explicitly set the size to the number of options.
<div class="scrollable">
<select size="6" multiple="multiple">
<option value="1" selected>option 1 The Long Option</option>
<option value="2">option 2</option>
<option value="3">option 3</option>
<option value="4">option 4</option>
<option value="5">option 5 Another Longer than the Long Option ;)</option>
<option value="6">option 6</option>
</select>
</div>
It's been a while since you asked but I just had the same issue. As already mentioned by Estel the problem with key listeners is that they only work with hardware keyboards. To do this with an IME (soft keyboard), the solution is a bit more elaborate.
The single method we actually want to override is sendKeyEvent
in the EditText
's InputConnection
class. This method is called when key events occur in an IME. But in order to override this, we need to implement a custom EditText
which overrides the onCreateInputConnection
method, wrapping the default InputConnection
object in a proxy class! :|
Sounds complicated, but here's the simplest example I could contrive:
public class ZanyEditText extends EditText {
private Random r = new Random();
public ZanyEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public ZanyEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ZanyEditText(Context context) {
super(context);
}
public void setRandomBackgroundColor() {
setBackgroundColor(Color.rgb(r.nextInt(256), r.nextInt(256), r
.nextInt(256)));
}
@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
return new ZanyInputConnection(super.onCreateInputConnection(outAttrs),
true);
}
private class ZanyInputConnection extends InputConnectionWrapper {
public ZanyInputConnection(InputConnection target, boolean mutable) {
super(target, mutable);
}
@Override
public boolean sendKeyEvent(KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN
&& event.getKeyCode() == KeyEvent.KEYCODE_DEL) {
ZanyEditText.this.setRandomBackgroundColor();
// Un-comment if you wish to cancel the backspace:
// return false;
}
return super.sendKeyEvent(event);
}
}
}
The line with the call to setRandomBackgroundColor
is where my special backspace action occurs. In this case, changing the EditText
's background colour.
If you're inflating this from XML remember to use the full package name as the tag:
<cc.buttfu.test.ZanyEditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/somefield"
></cc.buttfu.test.ZanyEditText>
for swift4 code, first enable editing:
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
then you add delete action to the edit delegate:
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let action = UITableViewRowAction(style: .destructive, title: "Delete") { (_, index) in
// delete model object at the index
self.models[index.row]
// then delete the cell
tableView.beginUpdates()
tableView.deleteRows(at: [index], with: .automatic)
tableView.endUpdates()
}
return [action]
}
Using the java.time package in Java 8:
Instant start = Instant.now();
Thread.sleep(63553);
Instant end = Instant.now();
System.out.println(Duration.between(start, end));
Output is in ISO 8601 Duration format: PT1M3.553S
(1 minute and 3.553 seconds).
MAC OS
if you have mac and useing mongodb4.4, you can run:
brew services start [email protected]
The top answer of create tag in mounted is good, but it has some problems: If you change your link multiple times, it will repeat create tag over and over.
So I created a script to resolve this, and you can delete the tag if you want.
It's very simple, but can save your time to create it by yourself.
// PROJECT/src/assets/external.js
function head_script(src) {
if(document.querySelector("script[src='" + src + "']")){ return; }
let script = document.createElement('script');
script.setAttribute('src', src);
script.setAttribute('type', 'text/javascript');
document.head.appendChild(script)
}
function body_script(src) {
if(document.querySelector("script[src='" + src + "']")){ return; }
let script = document.createElement('script');
script.setAttribute('src', src);
script.setAttribute('type', 'text/javascript');
document.body.appendChild(script)
}
function del_script(src) {
let el = document.querySelector("script[src='" + src + "']");
if(el){ el.remove(); }
}
function head_link(href) {
if(document.querySelector("link[href='" + href + "']")){ return; }
let link = document.createElement('link');
link.setAttribute('href', href);
link.setAttribute('rel', "stylesheet");
link.setAttribute('type', "text/css");
document.head.appendChild(link)
}
function body_link(href) {
if(document.querySelector("link[href='" + href + "']")){ return; }
let link = document.createElement('link');
link.setAttribute('href', href);
link.setAttribute('rel', "stylesheet");
link.setAttribute('type', "text/css");
document.body.appendChild(link)
}
function del_link(href) {
let el = document.querySelector("link[href='" + href + "']");
if(el){ el.remove(); }
}
export {
head_script,
body_script,
del_script,
head_link,
body_link,
del_link,
}
And you can use it like this:
// PROJECT/src/views/xxxxxxxxx.vue
......
<script>
import * as external from '@/assets/external.js'
export default {
name: "xxxxxxxxx",
mounted(){
external.head_script('/assets/script1.js');
external.body_script('/assets/script2.js');
external.head_link('/assets/style1.css');
external.body_link('/assets/style2.css');
},
destroyed(){
external.del_script('/assets/script1.js');
external.del_script('/assets/script2.js');
external.del_link('/assets/style1.css');
external.del_link('/assets/style2.css');
},
}
</script>
......
This is what the equals method does:
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
As you can see, there's no hash code calculation, but there are a few other operations taking place there. Although x.intValue() == y.intValue()
might be slightly faster, you're getting into micro-optimization territory there. Plus the compiler might optimize the equals()
call anyway, though I don't know that for certain.
I generally would use the primitive int
, but if I had to use Integer
, I would stick with equals()
.
I prefer TIMESTAMPDIFF because you can easily change the unit if need be.
Old post, but I have a solution that could be usefull for next people. Why not just use file length to know what is the progression? Of course, lines has to be almost the same size, but it works very well for big files:
public static void main(String[] args) throws IOException {
File file = new File("yourfilehere");
double fileSize = file.length();
System.out.println("=======> File size = " + fileSize);
InputStream inputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "iso-8859-1");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
int totalRead = 0;
try {
while (bufferedReader.ready()) {
String line = bufferedReader.readLine();
// LINE PROCESSING HERE
totalRead += line.length() + 1; // we add +1 byte for the newline char.
System.out.println("Progress ===> " + ((totalRead / fileSize) * 100) + " %");
}
} finally {
bufferedReader.close();
}
}
It allows to see the progression without doing any full read on the file. I know it depends on lot of elements, but I hope it will be usefull :).
[Edition] Here is a version with estimated time. I put some SYSO to show progress and estimation. I see that you have a good time estimation errors after you have treated enough line (I try with 10M lines, and after 1% of the treatment, the time estimation was exact at 95%). I know, some values has to be set in variable. This code is quickly written but has be usefull for me. Hope it will be for you too :).
long startProcessLine = System.currentTimeMillis();
int totalRead = 0;
long progressTime = 0;
double percent = 0;
int i = 0;
int j = 0;
int fullEstimation = 0;
try {
while (bufferedReader.ready()) {
String line = bufferedReader.readLine();
totalRead += line.length() + 1;
progressTime = System.currentTimeMillis() - startProcessLine;
percent = (double) totalRead / fileSize * 100;
if ((percent > 1) && i % 10000 == 0) {
int estimation = (int) ((progressTime / percent) * (100 - percent));
fullEstimation += progressTime + estimation;
j++;
System.out.print("Progress ===> " + percent + " %");
System.out.print(" - current progress : " + (progressTime) + " milliseconds");
System.out.print(" - Will be finished in ===> " + estimation + " milliseconds");
System.out.println(" - estimated full time => " + (progressTime + estimation));
}
i++;
}
} finally {
bufferedReader.close();
}
System.out.println("Ended in " + (progressTime) + " seconds");
System.out.println("Estimative average ===> " + (fullEstimation / j));
System.out.println("Difference: " + ((((double) 100 / (double) progressTime)) * (progressTime - (fullEstimation / j))) + "%");
Feel free to improve this code if you think it's a good solution.
mysqldump --no-create-info ...
Also you may use:
--skip-triggers
: if you are using triggers--no-create-db
: if you are using --databases ...
option--compact
: if you want to get rid of extra commentsYou can use Excel Automation (it is basically a COM Base stuff) e.g:
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open("1.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
I realise that this is a rather old post and you have probably moved on.
But I had the same problem as you so I decided to write my own program.
The problem with the "xml -> xsd -> classes" route for me was that it just generated a lump of code that was completely unmaintainable and I ended up turfing it.
It is in no way elegant but it did the job for me.
You can get it here: Please make suggestions if you like it.
From Sql Server 2008 you have "date" format.
So you can use
SELECT * FROM LOGS WHERE CONVERT(date,[CHECK_IN]) BETWEEN '2013-10-18' AND '2013-10-18'
https://docs.microsoft.com/en-us/sql/t-sql/data-types/date-transact-sql
Problem Cause
In mac os image rendering back end of matplotlib (what-is-a-backend to render using the API of Cocoa by default). There are Qt4Agg and GTKAgg and as a back-end is not the default. Set the back end of macosx that is differ compare with other windows or linux os.
Solution
~/.matplotlib
. ~/.matplotlib/matplotlibrc
there and add the following code: backend: TkAgg
From this link you can try different diagrams.
I have now spent quite some time trying to find a good date picker that support interval ranges, and eventually found this one:
http://keith-wood.name/datepick.html
I believe this may be the best jquery date picker for selecting a range or multiple dates, and it is claimed to have been the base for the jQuery UI datepicker, and I see no reason to doubt that since it seems to be really powerful, and also good documented !
If there are no spaces in paths, and you are interested, like I was, in files of specific extension only, you can use
git checkout otherBranch -- $(git ls-tree --name-only -r otherBranch | egrep '*.java')
Define the width as 960px, or whatever you prefer, and you're good to go!
#main {
margin: 0 auto !important;
float: none !important;
text-align: center;
width: 960px;
}
(I couldn't figure this out until I fixed the width, nothing else worked.)
I came across this issue yesterday, but none of the solutions here worked exactly, however they did point me in the right direction.
Our application is a workflow tool written in C# and, overly simplified, has several stored procedures on the database, as well as a table of metadata about each parameter used by each stored procedure (name, order, data type, size, etc), allowing us to create as many new stored procedures as we need without having to change the C#.
Analysis of the problem showed that our code was setting all the correct parameters on the SqlCommand
object, however once it was executed, it threw the same error as the OP got.
Further analysis revealed that some parameters had a value of null
. I therefore must draw the conclusion that SqlCommand
objects ignore any SqlParameter
object in their .Parameters
collection with a value of null
.
There are two solutions to this problem that I found.
In our stored procedures, give a default value to each parameter, so from @Parameter int
to @Parameter int = NULL
(or some other default value as required).
In our code that generates the individual SqlParameter
objects, assigning DBNull.Value
instead of null
where the intended value is a SQL NULL
does the trick.
The original coder has moved on and the code was originally written with Solution 1 in mind, and having weighed up the benefits of both, I think I'll stick with Solution 1. It's much easier to specify a default value for a specific stored procedure when writing it, rather than it always being NULL
as defined in the code.
Hope that helps someone.
Under normal circumstances,out of bound of array when you encounter the error. So,check uo your array subscript.
Its very simple.
Example JSON:
{
"value":1
}
int z = jsonObject.getInt("value");
There's a good article on the topic in the Python wiki: Why Lists Can't Be Dictionary Keys. As explained there:
What would go wrong if you tried to use lists as keys, with the hash as, say, their memory location?
It can be done without really breaking any of the requirements, but it leads to unexpected behavior. Lists are generally treated as if their value was derived from their content's values, for instance when checking (in-)equality. Many would - understandably - expect that you can use any list [1, 2]
to get the same key, where you'd have to keep around exactly the same list object. But lookup by value breaks as soon as a list used as key is modified, and for lookup by identity requires you to keep around exactly the same list - which isn't requires for any other common list operation (at least none I can think of).
Other objects such as modules and object
make a much bigger deal out of their object identity anyway (when was the last time you had two distinct module objects called sys
?), and are compared by that anyway. Therefore, it's less surprising - or even expected - that they, when used as dict keys, compare by identity in that case as well.
Have you tried plugin called " Youtube Live Stream Auto Embed"
Its seems to be working. Check it once.
You can find creation time - aka birth time - using stat and also match using find.
We have these files showing last modified time:
$ ls -l --time-style=long-iso | sort -k6
total 692
-rwxrwx---+ 1 XXXX XXXX 249159 2013-05-31 14:47 Getting Started.pdf
-rwxrwx---+ 1 XXXX XXXX 275799 2013-12-30 21:12 TheScienceofGettingRich.pdf
-rwxrwx---+ 1 XXXX XXXX 25600 2015-05-07 18:52 Thumbs.db
-rwxrwx---+ 1 XXXX XXXX 148051 2015-05-07 18:55 AsAManThinketh.pdf
To find files created within a certain time frame using find as below.
Clearly, the filesystem knows about the birth time of a file:
$ find -newerBt '2014-06-13' ! -newerBt '2014-06-13 12:16:10' -ls
20547673299906851 148 -rwxrwx--- 1 XXXX XXXX 148051 May 7 18:55 ./AsAManThinketh.pdf
1407374883582246 244 -rwxrwx--- 1 XXXX XXXX 249159 May 31 2013 ./Getting\ Started.pdf
We can confirm this using stat:
$ stat -c "%w %n" * | sort
2014-06-13 12:16:03.873778400 +0100 AsAManThinketh.pdf
2014-06-13 12:16:04.006872500 +0100 Getting Started.pdf
2014-06-13 12:16:29.607075500 +0100 TheScienceofGettingRich.pdf
2015-05-07 18:32:26.938446200 +0100 Thumbs.db
stat man pages explains %w:
%w time of file birth, human-readable; - if unknown
Default user for MySQL is "root", and server "localhost".
Extending your requirements a bit and assuming you do not care about the order of lines and want to get them grouped under categories, the following solution may work for you:
>>> fname = "lines.txt"
>>> from collections import defaultdict
>>> dct = defaultdict(list)
>>> with open(fname) as f:
... for line in f:
... text, cat = line.rstrip("\n").split(",", 1)
... dct[cat].append(text)
...
>>> dct
defaultdict(<type 'list'>, {' CatA': ['This is the first line', 'This is the another line'], ' CatC': ['This is the third line'], ' CatB': ['This is the second line', 'This is the last line']})
This way you get all relevant lines available in the dictionary under key being the category.
If you’re not opposed to jquery, this can be done in one line:
jQuery 1.7+
$("#myEl").off()
jQuery < 1.7
$('#myEl').replaceWith($('#myEl').clone());
Here’s an example:
Create a global variable in and apply the value
<script>
var isPostBack = <%=Convert.ToString(Page.IsPostBack).ToLower()%>;
</script>
Then you can reference it from elsewhere
Your problem is basically that you never specified the right path to the file.
Try instead, from your main script:
from folder.file import Klasa
Or, with from folder import file
:
from folder import file
k = file.Klasa()
Or again:
import folder.file as myModule
k = myModule.Klasa()
I can't find toByteArray()
as @atrioom said, so I use StringWriter
, please try:
public void writeListToJsonArray() throws IOException {
//your list
final List<Event> list = new ArrayList<Event>(2);
list.add(new Event("a1","a2"));
list.add(new Event("b1","b2"));
final StringWriter sw =new StringWriter();
final ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(sw, list);
System.out.println(sw.toString());//use toString() to convert to JSON
sw.close();
}
Or just use ObjectMapper#writeValueAsString
:
final ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(list));
Need to add lazy for TapGestureRecognizer to register
since the 'self' in UITapGestureRecognizer(target: self ...) will be nil if it's not a lazy var. Even if you set isUserInteractionEnable = true, it won't register without lazy var.
lazy var imageSelector : UIImageView = {
let image = UIImageView(image: "imageName.png")
//now add tap gesture
image.isUserInteractionEnabled = true
image.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleImageSelector)))
return image
}()
@objc private func handleImageSelector() {
print("Pressed image selector")
}
just setting width
and adding float
worked for me :-)
width:100%;
float:left;
It is a bad practice to involve any exception throwing/handling into such a typical scenario.
Therefore a parseInt() is not nice, but a regex is an elegant solution for this, but take care of the following:
-fractions
-negative numbers
-decimal separator might differ in contries (e.g. ',' or '.')
-sometimes it is allowed to have a so called thousand separator, like a space or a comma e.g. 12,324,1000.355
To handle all the necessary cases in your application you have to be careful, but this regex covers the typical scenarios (positive/negative and fractional, separated by a dot): ^[-+]?\d*.?\d+$
For testing, I recommend regexr.com.
I have recently encountered this problem. Here are the steps to resolve
<servers>_x000D_
<server>_x000D_
<id>serverId</id>_x000D_
<username>username</username>_x000D_
<password>password</password>_x000D_
</server>_x000D_
</servers>
_x000D_
<repositories>_x000D_
<repository>_x000D_
<id>serverId</id> _x000D_
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>_x000D_
</repository>_x000D_
</repositories>
_x000D_
<profiles>_x000D_
<profile>_x000D_
<repositories>_x000D_
<repository>_x000D_
<id>serverId</id>_x000D_
<name>aliyun</name>_x000D_
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>_x000D_
</repository>_x000D_
</repositories>_x000D_
</profile>_x000D_
</profiles>
_x000D_
Note that you should ensure that the id of the server tag should be the same as the id of the repository tag.
In Python 2.7, the /
operator is an integer division if inputs are integers:
>>>20/15
1
>>>20.0/15.0
1.33333333333
>>>20.0/15
1.33333333333
In Python 3.3, the /
operator is a float division even if the inputs are integer.
>>> 20/15
1.33333333333
>>>20.0/15
1.33333333333
For integer division in Python 3, we will use the //
operator.
The //
operator is an integer division operator in both Python 2.7 and Python 3.3.
In Python 2.7 and Python 3.3:
>>>20//15
1
Now, see the comparison
>>>a = 7.0/4.0
>>>b = 7/4
>>>print a == b
For the above program, the output will be False in Python 2.7 and True in Python 3.3.
In Python 2.7 a = 1.75 and b = 1.
In Python 3.3 a = 1.75 and b = 1.75, just because /
is a float division.
Check your internet connection is stable or not. May be this will work with you
Be warned that the Unicode property \p{xdigit}
includes the FULLWIDTH versions. You might prefer \p{ASCII_Hex_Digit}
instead.
The answer to the question asked might be best answered — provided you have a certain venerable CPAN module installed — by typing:
% perl -MRegexp::Common -lE 'say $RE{net}{MAC}'
I show the particular pattern it outputs here as lucky pattern number 13; there are many others.
This program:
#!/usr/bin/env perl
use 5.010;
use strict;
use warnings qw<FATAL all>;
my $mac_rx = qr{
^ (?&MAC_addr) $
(?(DEFINE)
(?<MAC_addr>
(?&pair) (?<it> (?&either) )
(?: (?&pair) \k<it> ) {4}
(?&pair)
)
(?<pair> [0-9a-f] {2} )
(?<either> [:\-] )
)
}xi;
while (<DATA>) {
chomp;
printf("%-25s %s\n", $_ => /$mac_rx/ ? "ok" : "not ok");
}
__END__
3D:F2:C9:A6:B3:4F
3D:F2:AC9:A6:B3:4F
3D:F2:C9:A6:B3:4F:00
:F2:C9:A6:B3:4F
F2:C9:A6:B3:4F
3d:f2:c9:a6:b3:4f
3D-F2-C9-A6-B3-4F
3D-F2:C9-A6:B3-4F
generates this output:
3D:F2:C9:A6:B3:4F ok
3D:F2:AC9:A6:B3:4F not ok
3D:F2:C9:A6:B3:4F:00 not ok
:F2:C9:A6:B3:4F not ok
F2:C9:A6:B3:4F not ok
3d:f2:c9:a6:b3:4f ok
3D-F2-C9-A6-B3-4F ok
3D-F2:C9-A6:B3-4F not ok
Which seems the sort of thing you're looking for.
GIT=/usr/bin/git # STORE THE RELATIVE PATH
# GIT=$(which git) # USE THIS COMMAND TO SEARCH FOR THE RELATIVE PATH
if [[ ! -e $GIT ]]; then # CHECK IF THE FILE EXISTS
echo "PROGRAM DOES NOT EXIST."
exit 1 # EXIT THE PROGRAM IF IT DOES NOT
fi
# DO SOMETHING ...
exit 0 # EXIT THE PROGRAM IF IT DOES
Here is what I had and what caused my "incomplete type error":
#include "X.h" // another already declared class
class Big {...} // full declaration of class A
class Small : Big {
Small() {}
Small(X); // line 6
}
//.... all other stuff
What I did in the file "Big.cpp", where I declared the A2's constructor with X as a parameter is..
Small::Big(X my_x) { // line 9 <--- LOOK at this !
}
I wrote "Small::Big" instead of "Small::Small", what a dumb mistake.. I received the error "incomplete type is now allowed" for the class X all the time (in lines 6 and 9), which made a total confusion..
Anyways, that is where a mistake can happen, and the main reason is that I was tired when I wrote it and I needed 2 hours of exploring and rewriting the code to reveal it.
NOLOCK
is equivalent to READ UNCOMMITTED
, however Microsoft says you should not use it for UPDATE
or DELETE
statements:
For UPDATE or DELETE statements: This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work, and plan to modify applications that currently use this feature.
http://msdn.microsoft.com/en-us/library/ms187373.aspx
This article applies to SQL Server 2005, so the support for NOLOCK
exists if you are using that version. In order to future-proof you code (assuming you've decided to use dirty reads) you could use this in your stored procedures:
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
In addition to previous answers, I recommend to first calculate the ratio in the exponent, then taking the square:
def gaussian(x,x0,sigma):
return np.exp(-np.power((x - x0)/sigma, 2.)/2.)
That way, you can also calculate the gaussian of very small or very large numbers:
In: gaussian(1e-12,5e-12,3e-12)
Out: 0.64118038842995462
span.middle {
margin: 0 10px 0 10px; /*top right bottom left */
}
<span>text</span> <span class="middle">text</span> <span>text</span>
Here's my take on it. I needed to create a URL by collecting the value from a text box , when the user presses a Submit button.
<html>_x000D_
<body>_x000D_
_x000D_
Hi everyone_x000D_
_x000D_
<p id="result"></p>_x000D_
_x000D_
<textarea cols="40" id="SearchText" rows="2"></textarea>_x000D_
_x000D_
<button onclick="myFunction()" type="button">Submit!</button>_x000D_
_x000D_
<script>_x000D_
function myFunction() {_x000D_
var result = document.getElementById("SearchText").value;_x000D_
document.getElementById("result").innerHTML = result;_x000D_
document.getElementById("abc").href="http://arindam31.pythonanywhere.com/hello/" + result;_x000D_
} _x000D_
</script>_x000D_
_x000D_
_x000D_
<a href="#" id="abc">abc</a>_x000D_
_x000D_
</body>_x000D_
<html>
_x000D_
It seams you need to versionate, so when some change happens browser will catch something new and user won't need to clear browser's cache.
You can do it by subfolders (example /css/v1/style.css)
or by filename (example: css/style_v1.css)
or even by setting different folders for your website, example:
www.mywebsite.com/site1
www.mywebsite.com/site2
www.mywebsite.com/site3
And use a .htaccess or even change httpd.conf to redirect to your current application.
If's about one image or page:
<?$time = date("H:i:s");?>
<img src="myfile.jpg?time=<?$time;?>">
You can use $time on parts when you don't wanna cache. So it will always pull a new image. Versionate it seams a better approach, otherwise it can overload your server. Remember, browser's cache it's not only good to user experience, but also for your server.
I've been using the Output("doc.pdf", "I");
and it doesn't work, I'm always asked for saving the file.
I took a look in documentation and found that
I send the file inline to the browser (default). The plug-in is used if available. The name given by name is used when one selects the "Save as" option on the link generating the PDF. http://www.tcpdf.org/doc/classTCPDF.html#a3d6dcb62298ec9d42e9125ee2f5b23a1
Then I think you have to use a plugin to print it, otherwise it is going to be downloaded.
user1207523's script works fine for me. Here is a variant that searches for jar files recusively using find instead of simple expansion;
#!/bin/bash
for i in `find . -name '*.jar'`; do jar -tf "$i" | grep $1 | xargs -I{} echo -e "$i : {}" ; done
Using Date object guarantees that. For eg if you try to create April 31st
:
new Date(2014,3,31) // Thu May 01 2014 00:00:00
Please note that it's zero indexed, so Jan. is
0
, Feb. is1
etc.
For future purposes, this may help too:
It's ok to use setState in useEffect
you just need to have attention as described already to not create a loop.
But it's not the only problem that may occur. See below:
Imagine that you have a component Comp
that receives props
from parent and according to a props
change you want to set Comp
's state. For some reason, you need to change for each prop in a different useEffect
:
DO NOT DO THIS
useEffect(() => {
setState({ ...state, a: props.a });
}, [props.a]);
useEffect(() => {
setState({ ...state, b: props.b });
}, [props.b]);
It may never change the state of a as you can see in this example: https://codesandbox.io/s/confident-lederberg-dtx7w
The reason why this happen in this example it's because both useEffects run in the same react cycle when you change both prop.a
and prop.b
so the value of {...state}
when you do setState
are exactly the same in both useEffect
because they are in the same context. When you run the second setState
it will replace the first setState
.
DO THIS INSTEAD
The solution for this problem is basically call setState
like this:
useEffect(() => {
setState(state => ({ ...state, a: props.a }));
}, [props.a]);
useEffect(() => {
setState(state => ({ ...state, b: props.b }));
}, [props.b]);
Check the solution here: https://codesandbox.io/s/mutable-surf-nynlx
Now, you always receive the most updated and correct value of the state when you proceed with the setState
.
I hope this helps someone!
I used VML(Vector Markup Language) based formatting in my email template. In VML Based you have write your code within comment I took help from this site.
https://litmus.com/blog/a-guide-to-bulletproof-buttons-in-email-design#supporttable
Try
if (!(i == 'InvKey' || i == 'PostDate')) {
or
if (i != 'InvKey' || i != 'PostDate') {
that says if i does not equals InvKey
OR PostDate
Identity of entities is defined by their primary keys. Since firstname
and lastname
are not parts of the primary key, you cannot tell JPA to treat User
s with the same firstname
s and lastname
s as equal if they have different userId
s.
So, if you want to update a User
identified by its firstname
and lastname
, you need to find that User
by a query, and then change appropriate fields of the object your found. These changes will be flushed to the database automatically at the end of transaction, so that you don't need to do anything to save these changes explicitly.
EDIT:
Perhaps I should elaborate on overall semantics of JPA. There are two main approaches to design of persistence APIs:
insert/update approach. When you need to modify the database you should call methods of persistence API explicitly: you call insert
to insert an object, or update
to save new state of the object to the database.
Unit of Work approach. In this case you have a set of objects managed by persistence library. All changes you make to these objects will be flushed to the database automatically at the end of Unit of Work (i.e. at the end of the current transaction in typical case). When you need to insert new record to the database, you make the corresponding object managed. Managed objects are identified by their primary keys, so that if you make an object with predefined primary key managed, it will be associated with the database record of the same id, and state of this object will be propagated to that record automatically.
JPA follows the latter approach. save()
in Spring Data JPA is backed by merge()
in plain JPA, therefore it makes your entity managed as described above. It means that calling save()
on an object with predefined id will update the corresponding database record rather than insert a new one, and also explains why save()
is not called create()
.
Although this feature is only implemented in webkit, and it doesn't have browser compatibility, but It's worth taking a look at:
.image img {
max-width: 100%;
max-height: 100%;
-webkit-transition: .2s all;
}
.image img:hover {
-webkit-filter: brightness(50%);
}
It solved throung second parameter in Model load:
$this->load->model('user','User');
first parameter is the model's filename, and second it defining the name of model to be used in the controller:
function alluser()
{
$this->load->model('User');
$result = $this->User->showusers();
}
$query = "SELECT * FROM tableName";
$query_run = mysql_query($query);
$qty= 0;
while ($num = mysql_fetch_assoc ($query_run)) {
$qty += $num['ColumnName'];
}
echo $qty;
This will show original dimensions of Image on Hover using jQuery custom code
HTML
<ul class="thumb">
<li>
<a href="javascript:void(0)">
<div class="thumbnail-wrap" style="background-image:url(./images/1.jpg)"></div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<div class="thumbnail-wrap" style="background-image:url(./images/2.jpg)"></div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<div class="thumbnail-wrap" style="background-image:url(./images/3.jpg)"></div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<div class="thumbnail-wrap" style="background-image:url(./images/4.jpg)"></div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<div class="thumbnail-wrap" style="background-image:url(./images/5.jpg)"></div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<div class="thumbnail-wrap" style="background-image:url(./images/6.jpg)"></div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<div class="thumbnail-wrap" style="background-image:url(./images/7.jpg)"></div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<div class="thumbnail-wrap" style="background-image:url(./images/8.jpg)"></div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<div class="thumbnail-wrap" style="background-image:url(./images/9.jpg)"></div>
</a>
</li>
</ul>
CSS
ul.thumb {
float: left;
list-style: none;
padding: 10px;
width: 360px;
margin: 80px;
}
ul.thumb li {
margin: 0;
padding: 5px;
float: left;
position: relative;
/* Set the absolute positioning base coordinate */
width: 110px;
height: 110px;
}
ul.thumb li .thumbnail-wrap {
width: 100px;
height: 100px;
/* Set the small thumbnail size */
-ms-interpolation-mode: bicubic;
/* IE Fix for Bicubic Scaling */
border: 1px solid #ddd;
padding: 5px;
position: absolute;
left: 0;
top: 0;
background-size: cover;
background-repeat: no-repeat;
-webkit-box-shadow: inset -3px 0px 40px -15px rgba(0, 0, 0, 1);
-moz-box-shadow: inset -3px 0px 40px -15px rgba(0, 0, 0, 1);
box-shadow: inset -3px 0px 40px -15px rgba(0, 0, 0, 1);
}
ul.thumb li .thumbnail-wrap.hover {
-webkit-box-shadow: -2px 1px 22px -1px rgba(0, 0, 0, 0.75);
-moz-box-shadow: -2px 1px 22px -1px rgba(0, 0, 0, 0.75);
box-shadow: -2px 1px 22px -1px rgba(0, 0, 0, 0.75);
}
.thumnail-zoomed-wrapper {
display: none;
position: fixed;
top: 0px;
left: 0px;
height: 100vh;
width: 100%;
background: rgba(0, 0, 0, 0.2);
z-index: 99;
}
.thumbnail-zoomed-image {
margin: auto;
display: block;
text-align: center;
margin-top: 12%;
}
.thumbnail-zoomed-image img {
max-width: 100%;
}
.close-image-zoom {
z-index: 10;
float: right;
margin: 10px;
cursor: pointer;
}
jQuery
var perc = 40;
$("ul.thumb li").hover(function () {
$("ul.thumb li").find(".thumbnail-wrap").css({
"z-index": "0"
});
$(this).find(".thumbnail-wrap").css({
"z-index": "10"
});
var imageval = $(this).find(".thumbnail-wrap").css("background-image").slice(5);
var img;
var thisImage = this;
img = new Image();
img.src = imageval.substring(0, imageval.length - 2);
img.onload = function () {
var imgh = this.height * (perc / 100);
var imgw = this.width * (perc / 100);
$(thisImage).find(".thumbnail-wrap").addClass("hover").stop()
.animate({
marginTop: "-" + (imgh / 4) + "px",
marginLeft: "-" + (imgw / 4) + "px",
width: imgw + "px",
height: imgh + "px"
}, 200);
}
}, function () {
var thisImage = this;
$(this).find(".thumbnail-wrap").removeClass("hover").stop()
.animate({
marginTop: "0",
marginLeft: "0",
top: "0",
left: "0",
width: "100px",
height: "100px",
padding: "5px"
}, 400, function () {});
});
//Show thumbnail in fullscreen
$("ul.thumb li .thumbnail-wrap").click(function () {
var imageval = $(this).css("background-image").slice(5);
imageval = imageval.substring(0, imageval.length - 2);
$(".thumbnail-zoomed-image img").attr({
src: imageval
});
$(".thumnail-zoomed-wrapper").fadeIn();
return false;
});
//Close fullscreen preview
$(".thumnail-zoomed-wrapper .close-image-zoom").click(function () {
$(".thumnail-zoomed-wrapper").hide();
return false;
});
Just to clarify, there is a big difference between these two actions, as suggested by Jean-François Corbett.
One action is to copy / load the actual data FROM the Range("A2:A9")
INTO a Variant Array called vArray
(Changed to avoid confusion between Variant Array and Sheet both called Src):
vArray = Sheets("Src").Range("A2:A9").Value
while the other simply sets up a Range variable (SrcRange) with the ADDRESS of the range Sheets("Src").Range("A2:A9")
:
Set SrcRange = Sheets("Src").Range("A2:A9")
In this case, the data is not copied, and remains where it is, but can now be accessed in much the same way as an Array. That is often perfectly adequate, but if you need to repeatedly access, test or calculate with that data, loading it into an Array first will be MUCH faster.
For example, say you want to check a "database" (large sheet) against a list of known Suburbs and Postcodes. Both sets of data are in separate sheets, but if you want it to run fast, load the suburbs and postcodes into an Array (lives in memory), then run through each line of the main database, testing against the array data. This will be much faster than if you access both from their original sheets.
I use the following code to create PDF
protected void CreatePDF(Stream stream)
{
using (var document = new Document(PageSize.A4, 40, 40, 40, 30))
{
var writer = PdfWriter.GetInstance(document, stream);
writer.PageEvent = new ITextEvents();
document.Open();
// instantiate custom tag processor and add to `HtmlPipelineContext`.
var tagProcessorFactory = Tags.GetHtmlTagProcessorFactory();
tagProcessorFactory.AddProcessor(
new TableProcessor(),
new string[] { HTML.Tag.TABLE }
);
//Register Fonts.
XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
fontProvider.Register(HttpContext.Current.Server.MapPath("~/Content/Fonts/GothamRounded-Medium.ttf"), "Gotham Rounded Medium");
CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);
var htmlPipelineContext = new HtmlPipelineContext(cssAppliers);
htmlPipelineContext.SetTagFactory(tagProcessorFactory);
var pdfWriterPipeline = new PdfWriterPipeline(document, writer);
var htmlPipeline = new HtmlPipeline(htmlPipelineContext, pdfWriterPipeline);
// get an ICssResolver and add the custom CSS
var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);
cssResolver.AddCss(CSSSource, "utf-8", true);
var cssResolverPipeline = new CssResolverPipeline(
cssResolver, htmlPipeline
);
var worker = new XMLWorker(cssResolverPipeline, true);
var parser = new XMLParser(worker);
using (var stringReader = new StringReader(HTMLSource))
{
parser.Parse(stringReader);
document.Close();
HttpContext.Current.Response.ContentType = "application /pdf";
if (base.View)
HttpContext.Current.Response.AddHeader("content-disposition", "inline;filename=\"" + OutputFileName + ".pdf\"");
else
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=\"" + OutputFileName + ".pdf\"");
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.WriteFile(OutputPath);
HttpContext.Current.Response.End();
}
}
}
Probably the machine or web.config in prod has the settings in the configuration; you probably won't need the proxy tag.
<system.net>
<defaultProxy useDefaultCredentials="true" >
<proxy usesystemdefault="False"
proxyaddress="http://<ProxyLocation>:<port>"
bypassonlocal="True"
autoDetect="False" />
</defaultProxy>
</system.net>
Charles is written in Java and runs on Macs. It's not free though.
You can point your Mac at your Windows+Fiddler machine: http://www.fiddler2.com/fiddler/help/hookup.asp#Q-NonWindows
And as of 2013, there's an Alpha download of Fiddler for the Mono Framework, which runs on Mac and Linux. Also, the very latest version of Fiddler can import .PCAP files captured from WireShark or other tools run on the Mac.
A good hash function has the following properties:
Given a hash of a message it is computationally infeasible for an attacker to find another message such that their hashes are identical.
Given a pair of message, m' and m, it is computationally infeasible to find two such that that h(m) = h(m')
The two cases are not the same. In the first case, there is a pre-existing hash that you're trying to find a collision for. In the second case, you're trying to find any two messages that collide. The second task is significantly easier due to the birthday "paradox."
Where performance is not that great an issue, you should always use a secure hash function. There are very clever attacks that can be performed by forcing collisions in a hash. If you use something strong from the outset, you'll secure yourself against these.
Don't use MD5 or SHA-1 in new designs. Most cryptographers, me included, would consider them broken. The principle source of weakness in both of these designs is that the second property, which I outlined above, does not hold for these constructions. If an attacker can generate two messages, m and m', that both hash to the same value they can use these messages against you. SHA-1 and MD5 also suffer from message extension attacks, which can fatally weaken your application if you're not careful.
A more modern hash such as Whirpool is a better choice. It does not suffer from these message extension attacks and uses the same mathematics as AES uses to prove security against a variety of attacks.
Hope that helps!
If you use the gson.JsonObject you can have something like that:
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
String jsonString = "{'test1':'value1','test2':{'id':0,'name':'testName'}}"
JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonString)
There might be a more elegant way to do this but here is my solution. With Jquery
fileEle.value = "";
var parEle = $(fileEle).parent();
var newEle = $(fileEle).clone()
$(fileEle).remove();
parEle.append(newEle);
Basically you cleat the value of the input. Clone it and put the clone in place of the old one.
If you have Ubuntu 20.04 LTS (Focal Fossa) you can install python-is-python3
:
sudo apt install python-is-python3
which replaces the symlink in /usr/bin/python
to point to /usr/bin/python3
.
.container { . . . . align-items: stretch; . . . . }
For those looking for OBJC solution, to be added in App Delegate didFinishLaunchingWithOptions method:
[[UINavigationBar appearance] setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
[UINavigationBar appearance].shadowImage = [UIImage new];
[UINavigationBar appearance].backgroundColor = [UIColor clearColor];
[UINavigationBar appearance].translucent = YES;
Escaping a double quote can absolutely be necessary in sed: for instance, if you are using double quotes in the entire sed expression (as you need to do when you want to use a shell variable).
Here's an example that touches on escaping in sed but also captures some other quoting issues in bash:
# cat inventory
PURCHASED="2014-09-01"
SITE="Atlanta"
LOCATION="Room 154"
Let's say you wanted to change the room using a sed script that you can use over and over, so you variablize the input as follows:
# i="Room 101" (these quotes are there so the variable can contains spaces)
This script will add the whole line if it isn't there, or it will simply replace (using sed) the line that is there with the text plus the value of $i.
if grep -q LOCATION inventory; then
## The sed expression is double quoted to allow for variable expansion;
## the literal quotes are both escaped with \
sed -i "/^LOCATION/c\LOCATION=\"$i\"" inventory
## Note the three layers of quotes to get echo to expand the variable
## AND insert the literal quotes
else
echo LOCATION='"'$i'"' >> inventory
fi
P.S. I wrote out the script above on multiple lines to make the comments parsable but I use it as a one-liner on the command line that looks like this:
i="your location"; if grep -q LOCATION inventory; then sed -i "/^LOCATION/c\LOCATION=\"$i\"" inventory; else echo LOCATION='"'$i'"' >> inventory; fi
In Excel 2010 it is easy, just takes a few more steps for each list items.
The following steps must be completed for each item within the validation list. (Have the worksheet open to where the drop down was created)
1) Click on cell with drop down list.
2) Select which answer to apply format to.
3) Click on "Home" tab, then click the "Styles" tool button on the ribbon.
4) Click "Conditional Formatting", in drop down list click the "*New Rule" option.
5) Select a Rule Type: "Format only cells that contain"
6) Edit the Rule Description: "Cell Value", "equal to", click the cell formula icon in
the formula bar (far right), select which worksheet the validation list was created in,
select the cell within the list to which you wish to apply the formatting.
Formula should look something like:
='Workbook Data'!$A$2
7) Click the formula icon again to return to format menu.
8) Click on Format button beside preview pane.
9) Select all format options desired.
10) Press "OK" twice.
You are finished with only one item within list. Repeat steps 1 thru 10 until all drop down list items are finished.
Update August 2019
In Android Studio 3.5 Instant Run was replaced with Apply Changes. And it works in different way: APK is not modified on the fly anymore but instead runtime instrumentation is used to redefine classes on the fly (more info). So since Android Studio 3.5 instant run settings are replaced with Deployment (Settings -> Build, Execution, Deployment -> Deployment):
I had the same problem... solved it by adding the code shown below to the Into "$(document).ready" part of my "functions.js" file which is included in every page footer. It's pretty simple. It gets the full current URL of the displayed page and compares it to the full anchor href URL. If they are the same, set anchor (li) parent as active. And do this only if anchor href value is not "#", then the bootstrap will solve it.
$(document).ready(function () {
$(function(){
var current_page_URL = location.href;
$( "a" ).each(function() {
if ($(this).attr("href") !== "#") {
var target_URL = $(this).prop("href");
if (target_URL == current_page_URL) {
$('nav a').parents('li, ul').removeClass('active');
$(this).parent('li').addClass('active');
return false;
}
}
}); }); });
TreeMap<String,String>
HashMap
entries with the value as the key.If the values are nonunique, you would need a list in the second position.
By referring to https://jwt.io/ you can find jwt
implementations in many languages including java
. Also the site provide some comparison between these implementation (the algorithms they support and ....).
For java
these are mentioned libraries: