Only if the people who created the computers are bad with boolean logic. Which they shouldn't be.
Every comparison (>=
<=
>
<
) can be done in the same speed.
What every comparison is, is just a subtraction (the difference) and seeing if it's positive/negative.
(If the msb
is set, the number is negative)
How to check a >= b
? Sub a-b >= 0
Check if a-b
is positive.
How to check a <= b
? Sub 0 <= b-a
Check if b-a
is positive.
How to check a < b
? Sub a-b < 0
Check if a-b
is negative.
How to check a > b
? Sub 0 > b-a
Check if b-a
is negative.
Simply put, the computer can just do this underneath the hood for the given op:
a >= b
== msb(a-b)==0
a <= b
== msb(b-a)==0
a > b
== msb(b-a)==1
a < b
== msb(a-b)==1
and of course the computer wouldn't actually need to do the ==0
or ==1
either.
for the ==0
it could just invert the msb
from the circuit.
Anyway, they most certainly wouldn't have made a >= b
be calculated as a>b || a==b
lol
The withColumn function in pyspark enables you to make a new variable with conditions, add in the when and otherwise functions and you have a properly working if then else structure. For all of this you would need to import the sparksql functions, as you will see that the following bit of code will not work without the col() function. In the first bit, we declare a new column -'new column', and then give the condition enclosed in when function (i.e. fruit1==fruit2) then give 1 if the condition is true, if untrue the control goes to the otherwise which then takes care of the second condition (fruit1 or fruit2 is Null) with the isNull() function and if true 3 is returned and if false, the otherwise is checked again giving 0 as the answer.
from pyspark.sql import functions as F
df=df.withColumn('new_column',
F.when(F.col('fruit1')==F.col('fruit2'), 1)
.otherwise(F.when((F.col('fruit1').isNull()) | (F.col('fruit2').isNull()), 3))
.otherwise(0))
This also works for me
>>> val_int = int(a)
>>> val_fract = a - val_int
Try this:
<script type="text/javascript">
$.fn.toggleFuncs = function() {
var functions = Array.prototype.slice.call(arguments),
_this = this.click(function(){
var i = _this.data('func_count') || 0;
functions[i%functions.length]();
_this.data('func_count', i+1);
});
}
$('$showmenu').toggleFuncs(
function() {
$( ".menu" ).toggle( "drop" );
},
function() {
$( ".menu" ).toggle( "drop" );
}
);
</script>
First fuction is an alternative to JQuery deprecated toggle :) . Works good with JQuery 2.0.3 and JQuery UI 1.10.3
I found the links and tips under this question to be helpful.
SO what i have decided to do finally is here and its working fine on all mobile browsers including iPhones and Androids.
$(document).ready(function(){_x000D_
_x000D_
$('input[type="date"]').each(function(e) {_x000D_
var $el = $(this), _x000D_
$this_placeholder = $(this).closest('label').find('.custom-placeholder');_x000D_
$el.on('change',function(){_x000D_
if($el.val()){_x000D_
$this_placeholder.text('');_x000D_
}else {_x000D_
$this_placeholder.text($el.attr('placeholder'));_x000D_
}_x000D_
});_x000D_
});_x000D_
_x000D_
});
_x000D_
label {_x000D_
position: relative; _x000D_
}_x000D_
.custom-placeholder {_x000D_
#font > .proxima-nova-light(26px,40px);_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
z-index: 10;_x000D_
color: #999;_x000D_
}
_x000D_
<label>_x000D_
<input type="date" placeholder="Date">_x000D_
<span class="custom-placeholder">Date</span>_x000D_
</label>
_x000D_
Date
They are not managed, but measured and possibly limited (see getrlimit
system call, also on getrlimit(2)).
RSS means resident set size (the part of your virtual address space sitting in RAM).
You can query the virtual address space of process 1234 using proc(5) with cat /proc/1234/maps
and its status (including memory consumption) thru cat /proc/1234/status
In case you have multiple hosts using the same namespace in your solution, be sure to have them on a separate IISExpress port (and delete the .vs folder and restart vs).
MediaWiki's API is running on Wikipedia (docs). You can also use the Special:Export feature to dump data and parse it yourself.
It's as simple as iterating the array and looking for the regexp
function searchStringInArray (str, strArray) {
for (var j=0; j<strArray.length; j++) {
if (strArray[j].match(str)) return j;
}
return -1;
}
Edit - make str
as an argument to function.
Yes, a menu gives you the bar but it doesn't give you any items to put in the bar. You need something like (from one of my own projects):
<!-- Menu. -->
<Menu Width="Auto" Height="20" Background="#FFA9D1F4" DockPanel.Dock="Top">
<MenuItem Header="_Emulator">
<MenuItem Header="Load..." Click="MenuItem_Click" />
<MenuItem Header="Load again" Click="menuEmulLoadLast" />
<Separator />
<MenuItem Click="MenuItem_Click">
<MenuItem.Header>
<DockPanel>
<TextBlock>Step</TextBlock>
<TextBlock Width="10"></TextBlock>
<TextBlock HorizontalAlignment="Right">F2</TextBlock>
</DockPanel>
</MenuItem.Header>
</MenuItem>
:
Your user settings are in ~/Library/Application\ Support/Code/User
.
If you're not concerned about syncing and it's a one time thing, you can just copy the files keybindings.json
and settings.json
to the corresponding folder on your new machine.
Your extensions are in the ~/.vscode
folder. Most extensions aren't using any native bindings and they should be working properly when copied over.
You can manually re-install those who do not.
Wasted a lot of time on this silly issue!
add a cd command to where your batch file resides at the first line of your batch file and see if it resolves the issue.
cd D:\wherever\yourBatch\fileIs
TIP: please use absolute paths, relative paths ideally should not be an issue, but scheduler has an difficult time understanding them.
Try this:
import matplotlib as plt
after importing the file we can use matplotlib library but remember to use it as plt
df.plt(kind='line',figsize=(10,5))
after that the plot will be done and size increased. In figsize the 10 is for breadth and 5 is for height. Also other attributes can be added to the plot too.
In addition to other answers need to add that parameters not only helps prevent sql injection but can improve performance of queries. Sql server caching parameterized query plans and reuse them on repeated queries execution. If you not parameterized your query then sql server would compile new plan on each query(with some exclusion) execution if text of query would differ.
We can add additional columns to DataFrame directly with below steps:
from pyspark.sql.functions import when
df = spark.createDataFrame([["amit", 30], ["rohit", 45], ["sameer", 50]], ["name", "age"])
df = df.withColumn("profile", when(df.age >= 40, "Senior").otherwise("Executive"))
df.show()
Use setDataAndType on the Intent
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(newVideoPath), "video/mp4");
startActivity(intent);
Use "video/mp4" as MIME or use "video/*" if you don't know the type.
In c++ struct and c++ class have only one difference by default struct members are public and class members are private.
/*Here, C++ program constructor in struct*/
#include <iostream>
using namespace std;
struct hello
{
public: //by default also it is public
hello();
~hello();
};
hello::hello()
{
cout<<"calling constructor...!"<<endl;
}
hello::~hello()
{
cout<<"calling destructor...!"<<endl;
}
int main()
{
hello obj; //creating a hello obj, calling hello constructor and destructor
return 0;
}
set the "Dock" property of datagridview in layoutto one of these properties : top, left, bottom, right. ok?
It's best if you judge on your own,
1) Sublime works on Mac & Linux that may be its plus point, with VI mode that makes things easily searchable for the VI lover(UNIX & Linux).
http://text-editors.findthebest.com/compare/9-45/Notepad-vs-Sublime-Text
This Link is no more working so please watch this video for similar details Video
Initial observation revealed that everything else should work fine and almost similar;(with help of available plugins in notepad++)
Some Variation: Some user find plugins useful for PHP coders on that
http://codelikeapoem.com/2013/01/goodbye-notepad-hellooooo-sublime-text.html
although, there are many plugins for Notepad Plus Plus ..
I am not sure of your requirements, nor I am promoter of either of these editors :)
So, judge on basis of your requirements, this should satisfy you query...
Yes we can add that both are evolving and changing fast..
Use defined? YourVariable
Keep it simple silly .. ;)
If you wish to not show the button moving back and forth, you can put the original placement into your code then just check against those. Turn off screen updating when button is clicked, check to see if the the placement is different on the control, change it back, if needed, turn screen updating back on
DP
Sometimes, XCode does not forget the line which had an "Editor Placeholder" even if you have replaced it with a value. Cut the portion of the code where XCode is complaining and paste the code back to the same place to make the error message go away. This worked for me.
Hi You need to change the Button properties from private to public. You can change Under Button >> properties >> Design >> Modifiers >> "public" Once change the protection error will gone.
Budi
There’s also SenTestingKitAsync that lets you write code like this:
- (void)testAdditionAsync {
[Calculator add:2 to:2 block^(int result) {
STAssertEquals(result, 4, nil);
STSuccess();
}];
STFailAfter(2.0, @"Timeout");
}
(See objc.io article for details.) And since Xcode 6 there’s an AsynchronousTesting
category on XCTest
that lets you write code like this:
XCTestExpectation *somethingHappened = [self expectationWithDescription:@"something happened"];
[testedObject doSomethigAsyncWithCompletion:^(BOOL succeeded, NSError *error) {
[somethingHappened fulfill];
}];
[self waitForExpectationsWithTimeout:1 handler:NULL];
There are two reasons I see to use cte's.
To use a calculated value in the where clause. This seems a little cleaner to me than a derived table.
Suppose there are two tables - Questions and Answers joined together by Questions.ID = Answers.Question_Id (and quiz id)
WITH CTE AS
(
Select Question_Text,
(SELECT Count(*) FROM Answers A WHERE A.Question_ID = Q.ID) AS Number_Of_Answers
FROM Questions Q
)
SELECT * FROM CTE
WHERE Number_Of_Answers > 0
Here's another example where I want to get a list of questions and answers. I want the Answers to be grouped with the questions in the results.
WITH cte AS
(
SELECT [Quiz_ID]
,[ID] AS Question_Id
,null AS Answer_Id
,[Question_Text]
,null AS Answer
,1 AS Is_Question
FROM [Questions]
UNION ALL
SELECT Q.[Quiz_ID]
,[Question_ID]
,A.[ID] AS Answer_Id
,Q.Question_Text
,[Answer]
,0 AS Is_Question
FROM [Answers] A INNER JOIN [Questions] Q ON Q.Quiz_ID = A.Quiz_ID AND Q.Id = A.Question_Id
)
SELECT
Quiz_Id,
Question_Id,
Is_Question,
(CASE WHEN Answer IS NULL THEN Question_Text ELSE Answer END) as Name
FROM cte
GROUP BY Quiz_Id, Question_Id, Answer_id, Question_Text, Answer, Is_Question
order by Quiz_Id, Question_Id, Is_Question Desc, Name
It depends on which version of Oracle? Older versions require exp (export), newer versions use expdp (data pump); exp was deprecated but still works most of the time.
Before starting, note that Data Pump exports to the server-side Oracle "directory", which is an Oracle symbolic location mapped in the database to a physical location. There may be a default directory (DATA_PUMP_DIR), check by querying DBA_DIRECTORIES:
SQL> select * from dba_directories;
... and if not, create one
SQL> create directory DATA_PUMP_DIR as '/oracle/dumps';
SQL> grant all on directory DATA_PUMP_DIR to myuser; -- DBAs dont need this grant
Assuming you can connect as the SYSTEM user, or another DBA, you can export any schema like so, to the default directory:
$ expdp system/manager schemas=user1 dumpfile=user1.dpdmp
Or specifying a specific directory, add directory=<directory name>
:
C:\> expdp system/manager schemas=user1 dumpfile=user1.dpdmp directory=DUMPDIR
With older export utility, you can export to your working directory, and even on a client machine that is remote from the server, using:
$ exp system/manager owner=user1 file=user1.dmp
Make sure the export is done in the correct charset. If you haven't setup your environment, the Oracle client charset may not match the DB charset, and Oracle will do charset conversion, which may not be what you want. You'll see a warning, if so, then you'll want to repeat the export after setting NLS_LANG environment variable so the client charset matches the database charset. This will cause Oracle to skip charset conversion.
Example for American UTF8 (UNIX):
$ export NLS_LANG=AMERICAN_AMERICA.AL32UTF8
Windows uses SET, example using Japanese UTF8:
C:\> set NLS_LANG=Japanese_Japan.AL32UTF8
More info on Data Pump here: http://docs.oracle.com/cd/B28359_01/server.111/b28319/dp_export.htm#g1022624
You are not providing a lot of information, but assuming you want to open just any file on your computer with the application that is specified for the default handler for that filetype, you can use something like this:
var fileToOpen = "SomeFilePathHere";
var process = new Process();
process.StartInfo = new ProcessStartInfo()
{
UseShellExecute = true,
FileName = fileToOpen
};
process.Start();
process.WaitForExit();
The UseShellExecute parameter tells Windows to use the default program for the type of file you are opening.
The WaitForExit will cause your application to wait until the application you luanched has been closed.
Handlebars partials take a second parameter which becomes the context for the partial:
{{> person this}}
In versions v2.0.0 alpha and later, you can also pass a hash of named parameters:
{{> person headline='Headline'}}
You can see the tests for these scenarios: https://github.com/wycats/handlebars.js/blob/ce74c36118ffed1779889d97e6a2a1028ae61510/spec/qunit_spec.js#L456-L462 https://github.com/wycats/handlebars.js/blob/e290ec24f131f89ddf2c6aeb707a4884d41c3c6d/spec/partials.js#L26-L32
I have achieved this with following
Edit > Blank Operations > Remove Unnecessary Blank and EOL
Select count(*) from table_name into @var1;
Select @var1;
it means ONLY one byte will be allocated per character - so if you're using multi-byte charsets, your 1 character won't fit
if you know you have to have at least room enough for 1 character, don't use the BYTE syntax unless you know exactly how much room you'll need to store that byte
when in doubt, use VARCHAR2(1 CHAR)
same thing answered here Difference between BYTE and CHAR in column datatypes
Also, in 12c the max for varchar2 is now 32k, not 4000. If you need more than that, use CLOB
in Oracle, don't use VARCHAR
On a Windows machine I was able to log to to ssh from git bash with
ssh vagrant@VAGRANT_SERVER_IP
without providing a password
Using Bitvise SSH client on window
Server host: VAGRANT_SERVER_IP
Server port: 22
Username: vagrant
Password: vagrant
Try the following:
var $tabs = $('#tabs-menu').tabs();
var selected = $tabs.tabs('option', 'selected');
var divAssocAtual = $('#tabs-menu ul li').tabs()[selected].hash;
I think this code may be help you:
string str = char.ConvertFromUtf32(65)
Well generally you shouldn't need to classify an element specified by id, because id is always unique, but if you really need to, the following should work:
div#content.sectionA {
/* ... */
}
use sep='\s*,\s*'
so that you will take care of spaces in column-names:
transactions = pd.read_csv('transactions.csv', sep=r'\s*,\s*',
header=0, encoding='ascii', engine='python')
alternatively you can make sure that you don't have unquoted spaces in your CSV file and use your command (unchanged)
prove:
print(transactions.columns.tolist())
Output:
['product_id', 'customer_id', 'store_id', 'promotion_id', 'month_of_year', 'quarter', 'the_year', 'store_sales', 'store_cost', 'unit_sales', 'fact_count']
Use a lambda function.
Let's say you have an array:
nums = [0,1,5]
Check whether 5 is in nums
in Python 3.X:
(len(list(filter (lambda x : x == 5, nums))) > 0)
Check whether 5 is in nums
in Python 2.7:
(len(filter (lambda x : x == 5, nums)) > 0)
This solution is more robust. You can now check whether any number satisfying a certain condition is in your array nums
.
For example, check whether any number that is greater than or equal to 5 exists in nums
:
(len(filter (lambda x : x >= 5, nums)) > 0)
I have a quick solution for finding Waldo using OpenCV.
I used the template matching function available in OpenCV to find Waldo.
To do this a template is needed. So I cropped Waldo from the original image and used it as a template.
Next I called the cv2.matchTemplate()
function along with the normalized correlation coefficient as the method used. It returned a high probability at a single region as shown in white below (somewhere in the top left region):
The position of the highest probable region was found using cv2.minMaxLoc()
function, which I then used to draw the rectangle to highlight Waldo:
Run in command prompt.
pip list
Check what version you have installed on your system if you have an old version.
Try to uninstall the package...
pip uninstall requests
Try after to install it:
pip install requests
You can also test if pip does not do the job.
easy_install requests
Here is one possible way. Use the exists
function to check for something unique in your util.R
code.
For example:
if(!exists("foo", mode="function")) source("util.R")
(Edited to include mode="function"
, as Gavin Simpson pointed out)
For the record, you can also use a std::stringstream
if you want to create the string before it's actually output.
CSS is not HTML.
is a named character reference in HTML; equivalent to the decimal numeric character reference  
. 160 is the decimal code point of the NO-BREAK SPACE
character in Unicode (or UCS-2; see the HTML 4.01 Specification). The hexadecimal representation of that code point is U+00A0 (160 = 10 × 161 + 0 × 160). You will find that in the Unicode Code Charts and Character Database.
In CSS you need to use a Unicode escape sequence for such characters, which is based on the hexadecimal value of the code point of a character. So you need to write
.breadcrumbs a:before {
content: '\a0';
}
This works as long as the escape sequence comes last in a string value. If characters follow, there are two ways to avoid misinterpretation:
a) (mentioned by others) Use exactly six hexadecimal digits for the escape sequence:
.breadcrumbs a:before {
content: '\0000a0foo';
}
b) Add one white-space (e. g., space) character after the escape sequence:
.breadcrumbs a:before {
content: '\a0 foo';
}
(Since f
is a hexadecimal digit, \a0f
would otherwise mean GURMUKHI LETTER EE
here, or ? if you have a suitable font.)
The delimiting white-space will be ignored, and this will be displayed foo
, where the displayed space here would be a NO-BREAK SPACE
character.
The white-space approach ('\a0 foo'
) has the following advantages over the six-digit approach ('\0000a0foo'
):
Thus, to display a space after an escaped character, use two spaces in the stylesheet –
.breadcrumbs a:before {
content: '\a0 foo';
}
– or make it explicit:
.breadcrumbs a:before {
content: '\a0\20 foo';
}
See CSS 2.1, section "4.1.3 Characters and case" for details.
According to the source code of codeigniter, the function set
is defined as:
public function set($key, $value = '', $escape = TRUE)
{
$key = $this->_object_to_array($key);
if ( ! is_array($key))
{
$key = array($key => $value);
}
foreach ($key as $k => $v)
{
if ($escape === FALSE)
{
$this->ar_set[$this->_protect_identifiers($k)] = $v;
}
else
{
$this->ar_set[$this->_protect_identifiers($k, FALSE, TRUE)] = $this->escape($v);
}
}
return $this;
}
Apparently, if $key
is an array, codeigniter will simply ignore the second parameter $value
, but the third parameter $escape
will still work throughout the iteration of $key
, so in this situation, the following codes work (using the chain method):
$this->db->set(array(
'name' => $name ,
'email' => $email,
'time' => 'NOW()'), '', FALSE)->insert('mytable');
However, this will unescape all the data, so you can break your data into two parts:
$this->db->set(array(
'name' => $name ,
'email' => $email))->set(array('time' => 'NOW()'), '', FALSE)->insert('mytable');
This because every runtime.exec(..)
returns a Process
class that should be used after the execution instead that invoking other commands by the Runtime
class
If you look at Process doc you will see that you can use
getInputStream()
getOutputStream()
on which you should work by sending the successive commands and retrieving the output..
It should just be:
git diff --cached
--cached
means show the changes in the cache/index (i.e. staged changes) against the current HEAD
. --staged
is a synonym for --cached
.
--staged
and --cached
does not point to HEAD
, just difference with respect to HEAD
. If you cherry pick what to commit using git add --patch
(or git add -p
), --staged
will return what is staged.
A slightly different approach is to create your formula from a string. In the formula
help page you will find the following example :
## Create a formula for a model with a large number of variables:
xnam <- paste("x", 1:25, sep="")
fmla <- as.formula(paste("y ~ ", paste(xnam, collapse= "+")))
Then if you look at the generated formula, you will get :
R> fmla
y ~ x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 +
x12 + x13 + x14 + x15 + x16 + x17 + x18 + x19 + x20 + x21 +
x22 + x23 + x24 + x25
I've tried all of above solutions, all failed.
I ended up with using -h 127.0.0.1
instead of using default var/run/mysqld/mysqld.sock
.
In Supervised Learning we know what the input and output should be. For example , given a set of cars. We have to find out which ones red and which ones blue.
Whereas, Unsupervised learning is where we have to find out the answer with a very little or without any idea about how the output should be. For example, a learner might be able to build a model that detects when people are smiling based on correlation of facial patterns and words such as "what are you smiling about?".
Try this command:
sudo gedit helloWorld.txt
it, will open up a text editor to edit your file.
OR
sudo nano helloWorld.txt
Here, you can edit your file in the terminal window.
It can do so if you have implicitly or explicitly set the alignment of the struct. A struct that is aligned 4 will always be a multiple of 4 bytes even if the size of its members would be something that's not a multiple of 4 bytes.
Also a library may be compiled under x86 with 32-bit ints and you may be comparing its components on a 64-bit process would would give you a different result if you were doing this by hand.
You can't but you can do it anyway like this. I needed this for jQuery-File-Upload
import json
# get this object
from flask import Response
#example data:
js = [ { "name" : filename, "size" : st.st_size ,
"url" : url_for('show', filename=filename)} ]
#then do this
return Response(json.dumps(js), mimetype='application/json')
A common idiom for clearing standard containers is swapping with an empty version of the container:
void clear( std::queue<int> &q )
{
std::queue<int> empty;
std::swap( q, empty );
}
It is also the only way of actually clearing the memory held inside some containers (std::vector)
It is a unary operator (taking a single argument) that is borrowed from C, where all data types are just different ways of interpreting bytes. It is the "invert" or "complement" operation, in which all the bits of the input data are reversed.
In Python, for integers, the bits of the twos-complement representation of the integer are reversed (as in b <- b XOR 1
for each individual bit), and the result interpreted again as a twos-complement integer. So for integers, ~x
is equivalent to (-x) - 1
.
The reified form of the ~
operator is provided as operator.invert
. To support this operator in your own class, give it an __invert__(self)
method.
>>> import operator
>>> class Foo:
... def __invert__(self):
... print 'invert'
...
>>> x = Foo()
>>> operator.invert(x)
invert
>>> ~x
invert
Any class in which it is meaningful to have a "complement" or "inverse" of an instance that is also an instance of the same class is a possible candidate for the invert operator. However, operator overloading can lead to confusion if misused, so be sure that it really makes sense to do so before supplying an __invert__
method to your class. (Note that byte-strings [ex: '\xff'
] do not support this operator, even though it is meaningful to invert all the bits of a byte-string.)
Admittedly, I haven't tried any of the solutions listed above but I was (eventually) jumping for joy when I tried jschr's Bootstrap-modal project in Bootstrap 3 (linked to in the top answer). The js was giving me trouble so I abandoned it (maybe mine was a unique issue or it works fine for Bootstrap 2) but the CSS files on their own seem to do the trick in Android's native 2.3.4 browser.
In my case, I've resorted so far to using (sub-optimal) user-agent detection before using the overrides to allow expected behaviour in modern phones.
For example, if you wanted all Android phones ver 3.x and below only to use the full set of hacks you could add a class "oldPhoneModalNeeded" to the body after user agent detection using javascript and then modify jschr's Bootstrap-modal CSS properties to always have .oldPhoneModalNeeded as an ancestor.
You may have imported,
project/controllers/base
inside the
project/controllers/routes
You have already imported before. That's not supported.
static means that the variable or method marked as such is available at the class level. In other words, you don't need to create an instance of the class to access it.
public class Foo {
public static void doStuff(){
// does stuff
}
}
So, instead of creating an instance of Foo and then calling doStuff
like this:
Foo f = new Foo();
f.doStuff();
You just call the method directly against the class, like so:
Foo.doStuff();
Try to restart the adb server as follows:
adb kill-server
adb start-server
I have also came across the same problems as yours. And restarting the adb server will resolve this problem.
Just some hint to that accepted answer, if you are using position absolute, negative margins will not work, but you can still set the top, bottom, left and right to a negative value, and make the parent element overflow hidden.
The answer about adding clip to position absolute image has a problem if you don't know the image size.
You can use from the pd.to_numeric(s)
For the case I met, I found there are missing modules after make. So I did the following:
I did the following
python manage.py makemigrations
python manage.py migrate
It renewed the database and fixed the issues without affecting my project. Please note you might need to do python manage.py createsuperuser
because it will affect all your objects being created.
I want to do the same thing but to append a script tag in other frame!
var url = 'library.js';
var script = window.parent.frames[1].document.createElement('script' );
script.type = 'text/javascript';
script.src = url;
$('head',window.parent.frames[1].document).append(script);
Little addition to all these posts.
Sometimes you may want to declare a class and yet not know how to define all of the methods that belong to that class. For example, you may want to declare a class called Writer and include in it a member method called write(). However, you don't know how to code write() because it is different for each type of Writer devices. Of course, you plan to handle this by deriving subclass of Writer, such as Printer, Disk, Network and Console.
> grepl("^[^_]+_1",s)
[1] FALSE
> grepl("^[^_]+_2",s)
[1] TRUE
basically, look for everything at the beginning except _
, and then the _2
.
+1 to @Ananda_Mahto for suggesting grepl
instead of grep
.
Neither collection will let you add items that way.
You can make an extension to make for examle List(Of String)
have an Add
method that can do that:
Imports System.Runtime.CompilerServices
Module StringExtensions
<Extension()>
Public Sub Add(ByVal list As List(Of String), ParamArray values As String())
For Each s As String In values
list.Add(s)
Next
End Sub
End Module
Now you can add multiple value in one call:
Dim lstOfStrings as New List(Of String)
lstOfStrings.Add(String1, String2, String3, String4)
A character in Java is a Unicode code-unit which is treated as an unsigned number. So if you perform c = (char)b
the value you get is 2^16 - 56 or 65536 - 56.
Or more precisely, the byte is first converted to a signed integer with the value 0xFFFFFFC8
using sign extension in a widening conversion. This in turn is then narrowed down to 0xFFC8
when casting to a char
, which translates to the positive number 65480
.
From the language specification:
5.1.4. Widening and Narrowing Primitive Conversion
First, the byte is converted to an int via widening primitive conversion (§5.1.2), and then the resulting int is converted to a char by narrowing primitive conversion (§5.1.3).
To get the right point use char c = (char) (b & 0xFF)
which first converts the byte value of b
to the positive integer 200
by using a mask, zeroing the top 24 bits after conversion: 0xFFFFFFC8
becomes 0x000000C8
or the positive number 200
in decimals.
Above is a direct explanation of what happens during conversion between the byte
, int
and char
primitive types.
If you want to encode/decode characters from bytes, use Charset
, CharsetEncoder
, CharsetDecoder
or one of the convenience methods such as new String(byte[] bytes, Charset charset)
or String#toBytes(Charset charset)
. You can get the character set (such as UTF-8 or Windows-1252) from StandardCharsets
.
.NET can do it with its System.Speech namespace.
You would have to convert to .wav first or capture the audio live from the mic.
Details on implementation can be found here: Transcribing Audio with .NET
You have some errors in your appcontext.xml:
Use *-2.5.xsd
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"
Typos in tx:annotation-driven
and context:component-scan
(. instead of -)
<tx:annotation-driven transaction-manager="transactionManager" />
<context:component-scan base-package="com.mmycompany" />
There's a few ways to do it.
sys.stdin
is a file-like object on which you can call functions read
or readlines
if you want to read everything or you want to read everything and split it by newline automatically. (You need to import sys
for this to work.)
If you want to prompt the user for input, you can use raw_input
in Python 2.X, and just input
in Python 3.
If you actually just want to read command-line options, you can access them via the sys.argv list.
You will probably find this Wikibook article on I/O in Python to be a useful reference as well.
Download and run the following script to recursively convert hard tabs to soft tabs in plain text files.
Execute the script from inside the folder which contains the plain text files.
#!/bin/bash
find . -type f -and -not -path './.git/*' -exec grep -Iq . {} \; -and -print | while read -r file; do {
echo "Converting... "$file"";
data=$(expand --initial -t 4 "$file");
rm "$file";
echo "$data" > "$file";
}; done;
You can go to jwt.io
, paste your token and read the contents. This is jarring for a lot of people initially.
The short answer is that JWT doesn't concern itself with encryption. It cares about validation. That is to say, it can always get the answer for "Have the contents of this token been manipulated"? This means user manipulation of the JWT token is futile because the server will know and disregard the token. The server adds a signature based on the payload when issuing a token to the client. Later on it verifies the payload and matching signature.
The logical question is what is the motivation for not concerning itself with encrypted contents?
The simplest reason is because it assumes this is a solved problem for the most part. If dealing with a client like the web browser for example, you can store the JWT tokens in a cookie that is secure
(is not transmitted via HTTP, only via HTTPS) and httpOnly
(can't be read by Javascript) and talks to the server over an encrypted channel (HTTPS). Once you know you have a secure channel between the server and client you can securely exchange JWT or whatever else you want.
This keeps thing simple. A simple implementation makes adoption easier but it also lets each layer do what it does best (let HTTPS handle encryption).
JWT isn't meant to store sensitive data. Once the server receives the JWT token and validates it, it is free to lookup the user ID in its own database for additional information for that user (like permissions, postal address, etc). This keeps JWT small in size and avoids inadvertent information leakage because everyone knows not to keep sensitive data in JWT.
It's not too different from how cookies themselves work. Cookies often contain unencrypted payloads. If you are using HTTPS then everything is good. If you aren't then it's advisable to encrypt sensitive cookies themselves. Not doing so will mean that a man-in-the-middle attack is possible--a proxy server or ISP reads the cookies and then replays them later on pretending to be you. For similar reasons, JWT should always be exchanged over a secure layer like HTTPS.
points
or lines
comes handy if
y2
is generated later, orx
but still should go into the same coordinate system.As your y
s share the same x
, you can also use matplot
:
matplot (x, cbind (y1, y2), pch = 19)
(without the pch
matplopt
will plot the column numbers of the y
matrix instead of dots).
t
indicates for text mode
https://docs.python.org/release/3.1.5/library/functions.html#open
on linux, there's no difference between text mode and binary mode,
however, in windows, they converts \n
to \r\n
when text mode.
I agree with the points dnmckee mentions, plus:
There is a library called BoofCV which claims to better than ZBar and other libraries.
Here are the steps to use that (any OS).
Pre-requisites:
pip install pyboof
Class to decode:
import os
import numpy as np
import pyboof as pb
pb.init_memmap() #Optional
class QR_Extractor:
# Src: github.com/lessthanoptimal/PyBoof/blob/master/examples/qrcode_detect.py
def __init__(self):
self.detector = pb.FactoryFiducial(np.uint8).qrcode()
def extract(self, img_path):
if not os.path.isfile(img_path):
print('File not found:', img_path)
return None
image = pb.load_single_band(img_path, np.uint8)
self.detector.detect(image)
qr_codes = []
for qr in self.detector.detections:
qr_codes.append({
'text': qr.message,
'points': qr.bounds.convert_tuple()
})
return qr_codes
Usage:
qr_scanner = QR_Extractor()
output = qr_scanner.extract('Your-Image.jpg')
print(output)
Tested and works on Python 3.8 (Windows & Ubuntu)
While the rules in C++03 about when you need typename
and template
are largely reasonable, there is one annoying disadvantage of its formulation
template<typename T>
struct A {
typedef int result_type;
void f() {
// error, "this" is dependent, "template" keyword needed
this->g<float>();
// OK
g<float>();
// error, "A<T>" is dependent, "typename" keyword needed
A<T>::result_type n1;
// OK
result_type n2;
}
template<typename U>
void g();
};
As can be seen, we need the disambiguation keyword even if the compiler could perfectly figure out itself that A::result_type
can only be int
(and is hence a type), and this->g
can only be the member template g
declared later (even if A
is explicitly specialized somewhere, that would not affect the code within that template, so its meaning cannot be affected by a later specialization of A
!).
To improve the situation, in C++11 the language tracks when a type refers to the enclosing template. To know that, the type must have been formed by using a certain form of name, which is its own name (in the above, A
, A<T>
, ::A<T>
). A type referenced by such a name is known to be the current instantiation. There may be multiple types that are all the current instantiation if the type from which the name is formed is a member/nested class (then, A::NestedClass
and A
are both current instantiations).
Based on this notion, the language says that CurrentInstantiation::Foo
, Foo
and CurrentInstantiationTyped->Foo
(such as A *a = this; a->Foo
) are all member of the current instantiation if they are found to be members of a class that is the current instantiation or one of its non-dependent base classes (by just doing the name lookup immediately).
The keywords typename
and template
are now not required anymore if the qualifier is a member of the current instantiation. A keypoint here to remember is that A<T>
is still a type-dependent name (after all T
is also type dependent). But A<T>::result_type
is known to be a type - the compiler will "magically" look into this kind of dependent types to figure this out.
struct B {
typedef int result_type;
};
template<typename T>
struct C { }; // could be specialized!
template<typename T>
struct D : B, C<T> {
void f() {
// OK, member of current instantiation!
// A::result_type is not dependent: int
D::result_type r1;
// error, not a member of the current instantiation
D::questionable_type r2;
// OK for now - relying on C<T> to provide it
// But not a member of the current instantiation
typename D::questionable_type r3;
}
};
That's impressive, but can we do better? The language even goes further and requires that an implementation again looks up D::result_type
when instantiating D::f
(even if it found its meaning already at definition time). When now the lookup result differs or results in ambiguity, the program is ill-formed and a diagnostic must be given. Imagine what happens if we defined C
like this
template<>
struct C<int> {
typedef bool result_type;
typedef int questionable_type;
};
A compiler is required to catch the error when instantiating D<int>::f
. So you get the best of the two worlds: "Delayed" lookup protecting you if you could get in trouble with dependent base classes, and also "Immediate" lookup that frees you from typename
and template
.
In the code of D
, the name typename D::questionable_type
is not a member of the current instantiation. Instead the language marks it as a member of an unknown specialization. In particular, this is always the case when you are doing DependentTypeName::Foo
or DependentTypedName->Foo
and either the dependent type is not the current instantiation (in which case the compiler can give up and say "we will look later what Foo
is) or it is the current instantiation and the name was not found in it or its non-dependent base classes and there are also dependent base classes.
Imagine what happens if we had a member function h
within the above defined A
class template
void h() {
typename A<T>::questionable_type x;
}
In C++03, the language allowed to catch this error because there could never be a valid way to instantiate A<T>::h
(whatever argument you give to T
). In C++11, the language now has a further check to give more reason for compilers to implement this rule. Since A
has no dependent base classes, and A
declares no member questionable_type
, the name A<T>::questionable_type
is neither a member of the current instantiation nor a member of an unknown specialization. In that case, there should be no way that that code could validly compile at instantiation time, so the language forbids a name where the qualifier is the current instantiation to be neither a member of an unknown specialization nor a member of the current instantiation (however, this violation is still not required to be diagnosed).
You can try this knowledge on this answer and see whether the above definitions make sense for you on a real-world example (they are repeated slightly less detailed in that answer).
The C++11 rules make the following valid C++03 code ill-formed (which was not intended by the C++ committee, but will probably not be fixed)
struct B { void f(); };
struct A : virtual B { void f(); };
template<typename T>
struct C : virtual B, T {
void g() { this->f(); }
};
int main() {
C<A> c; c.g();
}
This valid C++03 code would bind this->f
to A::f
at instantiation time and everything is fine. C++11 however immediately binds it to B::f
and requires a double-check when instantiating, checking whether the lookup still matches. However when instantiating C<A>::g
, the Dominance Rule applies and lookup will find A::f
instead.
I have a pure javascript library to do that https://github.com/robertodecurnex/J50Npi/blob/master/J50Npi.js
Take a look at it and let me know if you need any help using or understanding the code.
Btw, you have simple usage example here: http://robertodecurnex.github.com/J50Npi/
It seems to based on advertisement data, particularly the manufacturer data:
4C00 02 15 585CDE931B0142CC9A1325009BEDC65E 0000 0000 C5
<company identifier (2 bytes)> <type (1 byte)> <data length (1 byte)>
<uuid (16 bytes)> <major (2 bytes)> <minor (2 bytes)> <RSSI @ 1m>
I have this node.js script working on Linux with the sample AirLocate app example.
Its not possible have two return statement. However it doesn't throw error but when function is called you will receive only first return statement value. We can use return of array to get multiple values in return. For Example:
function test($testvar)
{
// do something
//just assigning a string for example, we can assign any operation result
$var1 = "result1";
$var2 = "result2";
return array('value1' => $var1, 'value2' => $var2);
}
Try this: parseInt(jQuery.offset().top, 10)
you can make two function one for Ascending and another for Descending the next two functions work after convert array to List
public List<Integer> sortDescending(List<Integer> arr){
Comparator<Integer> c = Collections.reverseOrder();
Collections.sort(arr,c);
return arr;
}
next function
public List<Integer> sortAscending(List<Integer> arr){
Collections.sort(arr);
return arr;
}
Without a RE (which I assume is what you want):
def remafterellipsis(text):
where_ellipsis = text.find('...')
if where_ellipsis == -1:
return text
return text[:where_ellipsis + 3]
or, with a RE:
import re
def remwithre(text, there=re.compile(re.escape('...')+'.*')):
return there.sub('', text)
You can create a local computer policy on Windows. See the TechNet at http://technet.microsoft.com/en-us/magazine/dd630947
gpedit.msc
to open the Group Policy Editor,Single elements of a tuple a
can be accessed -in an indexed array-like fashion-
via a[0]
, a[1]
, ... depending on the number of elements in the tuple.
If your tuple is a=(3,"a")
a[0]
yields 3
,a[1]
yields "a"
def tup():
return (3, "hello")
tup()
returns a 2-tuple.
In order to "solve"
i = 5 + tup() # I want to add just the three
you select the 3 by
tup()[0| #first element
so in total
i = 5 + tup()[0]
Go with namedtuple that allows you to access tuple elements by name (and by index). Details at https://docs.python.org/3/library/collections.html#collections.namedtuple
>>> import collections
>>> MyTuple=collections.namedtuple("MyTuple", "mynumber, mystring")
>>> m = MyTuple(3, "hello")
>>> m[0]
3
>>> m.mynumber
3
>>> m[1]
'hello'
>>> m.mystring
'hello'
If you're working in PowerShell you can use something like the following, given a pfx file InputBundle.pfx, to produce a DER encoded (binary) certificate file OutputCert.der:
Get-PfxCertificate -FilePath InputBundle.pfx |
Export-Certificate -FilePath OutputCert.der -Type CERT
Newline added for clarity, but you can of course have this all on a single line.
If you need the certificate in ASCII/Base64 encoded PEM format, you can take extra steps to do so as documented elsewhere, such as here: https://superuser.com/questions/351548/windows-integrated-utility-to-convert-der-to-pem
If you need to export to a different format than DER encoded, you can change the -Type
parameter for Export-Certificate to use the types supported by .NET, as seen in help Export-Certificate -Detailed
:
-Type <CertType>
Specifies the type of output file for the certificate export as follows.
-- SST: A Microsoft serialized certificate store (.sst) file format which can contain one or more certificates. This is the default value for multiple certificates.
-- CERT: A .cer file format which contains a single DER-encoded certificate. This is the default value for one certificate.
-- P7B: A PKCS#7 file format which can contain one or more certificates.
All done in XML
(no .png
images). The clever bit is border_shadow.xml
.
All about the vectors
these days...
Screenshot:
This is your SeekBar
(res/layout/???.xml
):
<SeekBar
android:id="@+id/seekBar_luminosite"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:progress="@integer/luminosite_defaut"
android:progressDrawable="@drawable/seekbar_style"
android:thumb="@drawable/custom_thumb"/>
Let's make it stylish (so you can easily customize it later):
res/drawable/seekbar_style.xml
:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@android:id/background"
android:drawable="@drawable/border_shadow" >
</item>
<item
android:id="@android:id/progress" >
<clip
android:drawable="@drawable/seekbar_progress" />
</item>
</layer-list>
res/drawable/custom_thumb.xml:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="oval">
<solid android:color="@color/colorDekraOrange"/>
<size
android:width="35dp"
android:height="35dp"/>
</shape>
</item>
</layer-list>
res/drawable/seekbar_progress.xml
:
<?xml version="1.0" encoding="utf-8"?>
<layer-list
xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/progressshape" >
<clip>
<shape
android:shape="rectangle" >
<size android:height="5dp"/>
<corners
android:radius="5dp" />
<solid android:color="@color/colorDekraYellow"/>
</shape>
</clip>
</item>
</layer-list>
res/drawable/border_shadow.xml
:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<corners
android:radius="5dp" />
<gradient
android:angle="270"
android:startColor="#33000000"
android:centerColor="#11000000"
android:endColor="#11000000"
android:centerY="0.2"
android:type="linear"
/>
</shape>
</item>
</layer-list>
You mention the most commonly implemented, which is Adjacency List: https://blogs.msdn.microsoft.com/mvpawardprogram/2012/06/25/hierarchies-convert-adjacency-list-to-nested-sets
There are other models as well, including materialized path and nested sets: http://communities.bmc.com/communities/docs/DOC-9902
Joe Celko has written a book on this subject, which is a good reference from a general SQL perspective (it is mentioned in the nested set article link above).
Also, Itzik Ben-Gann has a good overview of the most common options in his book "Inside Microsoft SQL Server 2005: T-SQL Querying".
The main things to consider when choosing a model are:
1) Frequency of structure change - how frequently does the actual structure of the tree change. Some models provide better structure update characteristics. It is important to separate structure changes from other data changes however. For example, you may want to model a company's organizational chart. Some people will model this as an adjacency list, using the employee ID to link an employee to their supervisor. This is usually a sub-optimal approach. An approach that often works better is to model the org structure separate from employees themselves, and maintain the employee as an attribute of the structure. This way, when an employee leaves the company, the organizational structure itself does not need to be changes, just the association with the employee that left.
2) Is the tree write-heavy or read-heavy - some structures work very well when reading the structure, but incur additional overhead when writing to the structure.
3) What types of information do you need to obtain from the structure - some structures excel at providing certain kinds of information about the structure. Examples include finding a node and all its children, finding a node and all its parents, finding the count of child nodes meeting certain conditions, etc. You need to know what information will be needed from the structure to determine the structure that will best fit your needs.
The synchronized
keyword prevents concurrent access to a block of code or object by multiple threads. All the methods of Hashtable
are synchronized
, so only one thread can execute any of them at a time.
When using non-synchronized
constructs like HashMap
, you must build thread-safety features in your code to prevent consistency errors.
xcopy "%userprofile%\Desktop\?????????" "D:\Backup\" /s/h/e/k/f/c
should work, assuming that your language setting allows Cyrillic (or you use Unicode fonts in the console).
For reference about the arguments: http://ss64.com/nt/xcopy.html
Run the following command on terminal.
sudo apt-add-repository ppa:paolorotolo/android-studio
sudo apt-get update
sudo apt-get install android-studio
check if your field with the primary key is set to auto increment
Permissions
You need the s3:GetObject permission for this operation. For more information, see Specifying Permissions in a Policy. If the object you request does not exist, the error Amazon S3 returns depends on whether you also have the s3:ListBucket permission.
If you have the s3:ListBucket permission on the bucket, Amazon S3 returns an HTTP status code 404 ("no such key") error. If you don’t have the s3:ListBucket permission, Amazon S3 returns an HTTP status code 403 ("access denied") error.
The following operation is related to HeadObject:
GetObject
Source: https://docs.aws.amazon.com/AmazonS3/latest/API/API_HeadObject.html
Working off the best answer and addressing my comment, here is a function for the conversion
def bunch_to_dataframe(bunch):
fnames = bunch.feature_names
features = fnames.tolist() if isinstance(fnames, np.ndarray) else fnames
features += ['target']
return pd.DataFrame(data= np.c_[bunch['data'], bunch['target']],
columns=features)
CREATE OR REPLACE PROCEDURE insert_into (
p_errcode OUT NUMBER,
p_errmesg OUT VARCHAR2,
p_rowsaffected OUT INTEGER
)
AS
v_param0 VARCHAR2 (30) := '0.25,2.25,33.689, abc, 99';
v_param1 VARCHAR2 (30) := '2.65,66.32, abc-def, 21.5';
BEGIN
FOR i IN (SELECT COLUMN_VALUE
FROM TABLE (SPLIT (v_param0, ',')))
LOOP
INSERT INTO tempo
(col1
)
VALUES (i.COLUMN_VALUE
);
END LOOP;
FOR i IN (SELECT COLUMN_VALUE
FROM TABLE (SPLIT (v_param1, ',')))
LOOP
INSERT INTO tempo
(col2
)
VALUES (i.COLUMN_VALUE
);
END LOOP;
END;
After copying the the app to the iPhone in the way described by @Jason Weathered, make sure to "chmod +x" of the app, otherwise it won't run.
A O(n) solution:
import java.util.*;
import java.io.*;
public class String_Duplicate_Removal
{
public static String duplicate_removal(String s)
{
if(s.length()<2)
return s;
else if(s.length()==2)
{
if(s.charAt(0)==s.charAt(1))
s = Character.toString(s.charAt(0));
return s;
}
boolean [] arr = new boolean[26];
for(int i=0;i<s.length();i++)
{
if(arr[s.charAt(i)-'a']==false)
arr[s.charAt(i)-'a']=true;
else
{
s= ((new StringBuilder(s)).deleteCharAt(i)).toString();
i--;
}
}
return s;
}
public static void main(String [] args)
{
String s = "abbashbhqa";
System.out.println(duplicate_removal(s));
}
}
You just can use doStuff($event) in your markup and get the data-attribute values via currentTarget.getAttribute("data-id")) in angular. HTML:
<div ng-controller="TestCtrl">
<button data-id="345" ng-click="doStuff($event)">Button</button>
</div>
JS:
var app = angular.module("app", []);
app.controller("TestCtrl", function ($scope) {
$scope.doStuff = function (item) {
console.log(item.currentTarget);
console.log(item.currentTarget.getAttribute("data-id"));
};
});
Forked your initial jsfiddle: http://jsfiddle.net/9mmd1zht/116/
The problem is that the timer
variable is local, and its value is lost after each function call.
You need to persist it, you can put it outside the function, or if you don't want to expose the variable as global, you can store it in a closure, e.g.:
var endAndStartTimer = (function () {
var timer; // variable persisted here
return function () {
window.clearTimeout(timer);
//var millisecBeforeRedirect = 10000;
timer = window.setTimeout(function(){alert('Hello!');},10000);
};
})();
Select ColumnB and as two CF formula rules apply:
Green: =AND(B1048576="X",B1="Y")
Red: =AND(B1048576="X",B1="W")
One-liner. No transpose needed:
df.loc[~(df==0).all(axis=1)]
And for those who like symmetry, this also works...
df.loc[(df!=0).any(axis=1)]
Try using an AppSettingsSection
instead of a NameValueCollection
. Something like this:
var section = (AppSettingsSection)config.GetSection(sectionName);
string results = section.Settings[key].Value;
Use serialize
and deserialize
methods in SerializationUtils
from commons-lang.
I am surprised that none of the answers mentioned the insertAdjacentHTML()
method. Check it out here. The first parameter is where you want the string appended and takes ("beforebegin", "afterbegin", "beforeend", "afterend"). In the OP's situation you would use "beforeend". The second parameter is just the html string.
Basic usage:
var d1 = document.getElementById('one');
d1.insertAdjacentHTML('beforeend', '<div id="two">two</div>');
The following code is in plain c language and handles blank spaces. It only allocates memory once, so one free() is needed, for each processed line.
/* Tiny CSV Reader */
/* Copyright (C) 2015, Deligiannidis Konstantinos
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://w...content-available-to-author-only...u.org/licenses/>. */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/* For more that 100 columns or lines (when delimiter = \n), minor modifications are needed. */
int getcols( const char * const line, const char * const delim, char ***out_storage )
{
const char *start_ptr, *end_ptr, *iter;
char **out;
int i; //For "for" loops in the old c style.
int tokens_found = 1, delim_size, line_size; //Calculate "line_size" indirectly, without strlen() call.
int start_idx[100], end_idx[100]; //Store the indexes of tokens. Example "Power;": loc('P')=1, loc(';')=6
//Change 100 with MAX_TOKENS or use malloc() for more than 100 tokens. Example: "b1;b2;b3;...;b200"
if ( *out_storage != NULL ) return -4; //This SHOULD be NULL: Not Already Allocated
if ( !line || !delim ) return -1; //NULL pointers Rejected Here
if ( (delim_size = strlen( delim )) == 0 ) return -2; //Delimiter not provided
start_ptr = line; //Start visiting input. We will distinguish tokens in a single pass, for good performance.
//Then we are allocating one unified memory region & doing one memory copy.
while ( ( end_ptr = strstr( start_ptr, delim ) ) ) {
start_idx[ tokens_found -1 ] = start_ptr - line; //Store the Index of current token
end_idx[ tokens_found - 1 ] = end_ptr - line; //Store Index of first character that will be replaced with
//'\0'. Example: "arg1||arg2||end" -> "arg1\0|arg2\0|end"
tokens_found++; //Accumulate the count of tokens.
start_ptr = end_ptr + delim_size; //Set pointer to the next c-string within the line
}
for ( iter = start_ptr; (*iter!='\0') ; iter++ );
start_idx[ tokens_found -1 ] = start_ptr - line; //Store the Index of current token: of last token here.
end_idx[ tokens_found -1 ] = iter - line; //and the last element that will be replaced with \0
line_size = iter - line; //Saving CPU cycles: Indirectly Count the size of *line without using strlen();
int size_ptr_region = (1 + tokens_found)*sizeof( char* ); //The size to store pointers to c-strings + 1 (*NULL).
out = (char**) malloc( size_ptr_region + ( line_size + 1 ) + 5 ); //Fit everything there...it is all memory.
//It reserves a contiguous space for both (char**) pointers AND string region. 5 Bytes for "Out of Range" tests.
*out_storage = out; //Update the char** pointer of the caller function.
//"Out of Range" TEST. Verify that the extra reserved characters will not be changed. Assign Some Values.
//char *extra_chars = (char*) out + size_ptr_region + ( line_size + 1 );
//extra_chars[0] = 1; extra_chars[1] = 2; extra_chars[2] = 3; extra_chars[3] = 4; extra_chars[4] = 5;
for ( i = 0; i < tokens_found; i++ ) //Assign adresses first part of the allocated memory pointers that point to
out[ i ] = (char*) out + size_ptr_region + start_idx[ i ]; //the second part of the memory, reserved for Data.
out[ tokens_found ] = (char*) NULL; //[ ptr1, ptr2, ... , ptrN, (char*) NULL, ... ]: We just added the (char*) NULL.
//Now assign the Data: c-strings. (\0 terminated strings):
char *str_region = (char*) out + size_ptr_region; //Region inside allocated memory which contains the String Data.
memcpy( str_region, line, line_size ); //Copy input with delimiter characters: They will be replaced with \0.
//Now we should replace: "arg1||arg2||arg3" with "arg1\0|arg2\0|arg3". Don't worry for characters after '\0'
//They are not used in standard c lbraries.
for( i = 0; i < tokens_found; i++) str_region[ end_idx[ i ] ] = '\0';
//"Out of Range" TEST. Wait until Assigned Values are Printed back.
//for ( int i=0; i < 5; i++ ) printf("c=%x ", extra_chars[i] ); printf("\n");
// *out memory should now contain (example data):
//[ ptr1, ptr2,...,ptrN, (char*) NULL, "token1\0", "token2\0",...,"tokenN\0", 5 bytes for tests ]
// |__________________________________^ ^ ^ ^
// |_______________________________________| | |
// |_____________________________________________| These 5 Bytes should be intact.
return tokens_found;
}
int main()
{
char in_line[] = "Arg1;;Th;s is not Del;m;ter;;Arg3;;;;Final";
char delim[] = ";;";
char **columns;
int i;
printf("Example1:\n");
columns = NULL; //Should be NULL to indicate that it is not assigned to allocated memory. Otherwise return -4;
int cols_found = getcols( in_line, delim, &columns);
for ( i = 0; i < cols_found; i++ ) printf("Column[ %d ] = %s\n", i, columns[ i ] ); //<- (1st way).
// (2nd way) // for ( i = 0; columns[ i ]; i++) printf("start_idx[ %d ] = %s\n", i, columns[ i ] );
free( columns ); //Release the Single Contiguous Memory Space.
columns = NULL; //Pointer = NULL to indicate it does not reserve space and that is ready for the next malloc().
printf("\n\nExample2, Nested:\n\n");
char example_file[] = "ID;Day;Month;Year;Telephone;email;Date of registration\n"
"1;Sunday;january;2009;123-124-456;[email protected];2015-05-13\n"
"2;Monday;March;2011;(+30)333-22-55;[email protected];2009-05-23";
char **rows;
int j;
rows = NULL; //getcols() requires it to be NULL. (Avoid dangling pointers, leaks e.t.c).
getcols( example_file, "\n", &rows);
for ( i = 0; rows[ i ]; i++) {
{
printf("Line[ %d ] = %s\n", i, rows[ i ] );
char **columnX = NULL;
getcols( rows[ i ], ";", &columnX);
for ( j = 0; columnX[ j ]; j++) printf(" Col[ %d ] = %s\n", j, columnX[ j ] );
free( columnX );
}
}
free( rows );
rows = NULL;
return 0;
}
You can not use input for it, you need to use textarea instead.
Use textarea with the wrap="soft"
code and optional the rest of the attributes like this:
<textarea name="text" rows="14" cols="10" wrap="soft"> </textarea>
Atributes: To limit the amount of text in it for example to "40" characters you can add the attribute maxlength="40"
like this: <textarea name="text" rows="14" cols="10" wrap="soft" maxlength="40"></textarea>
To hide the scroll the style for it. if you only use overflow:scroll;
or overflow:hidden;
or overflow:auto;
it will only take affect for one scroll bar. If you want different attributes for each scroll bar then use the attributes like this overflow:scroll; overflow-x:auto; overflow-y:hidden;
in the style area:
To make the textarea not resizable you can use the style with resize:none;
like this:
<textarea name="text" rows="14" cols="10" wrap="soft" maxlength="40" style="overflow:hidden; resize:none;></textarea>
That way you can have or example a textarea with 14 rows and 10 cols with word wrap and max character length of "40" characters that works exactly like a input text box does but with rows instead and without using input text.
NOTE: textarea works with rows unlike like input <input type="text" name="tbox" size="10"></input>
that is made to not work with rows at all.
If you're willing to include the jQuery UI library, in addition to jQuery itself, then you can simply use hide()
, with additional arguments, as follows:
$(document).ready(
function(){
$('#slider').click(
function(){
$(this).hide('slide',{direction:'right'},1000);
});
});
Without using jQuery UI, you could achieve your aim just using animate()
:
$(document).ready(
function(){
$('#slider').click(
function(){
$(this)
.animate(
{
'margin-left':'1000px'
// to move it towards the right and, probably, off-screen.
},1000,
function(){
$(this).slideUp('fast');
// once it's finished moving to the right, just
// removes the the element from the display, you could use
// `remove()` instead, or whatever.
}
);
});
});
If you do choose to use jQuery UI, then I'd recommend linking to the Google-hosted code, at: https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js
Since following 2 reasons, you should run my solution in CMD:
Login username & password is sometimes necessary to query a remote SQL Server instance
sqlcmd -U [your_User] -P[your_password] -S [your_remote_Server] -d [your_databasename] -i "query.txt" -o "output.csv" -s"," -w 700
If you are utilizing arrays too much then you should include cstring.h
because it has too many functions including finding substrings.
ng g c folderName/SubFolder/.../componentName --spec=false
MYSQL 5.5 One sql insert statement took ~300 to ~450ms. while the below stats is for inline multiple insert statments.
(25492 row(s) affected)
Execution Time : 00:00:03:343
Transfer Time : 00:00:00:000
Total Time : 00:00:03:343
I would say inline is way to go :)
I use this script. If you change your XML Comments to display as black text on a yellow background you get the effect of highlighting the text you're looking for in the xml column of the results. (Tools -> Options -> Environment -> Fonts and Colors [Display items: XML Comment]
---------------------------------------------
-------------- Start FINDTEXT ----------
---------------------------------------------
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SET NOCOUNT ON
GO
DECLARE @SearchString VARCHAR(MAX)
SET @SearchString = 'the text you''re looking for'
DECLARE @OverrideSearchStringWith VARCHAR(MAX)
--#############################################################################
-- Use Escape chars in Brackets [] like [%] to find percent char.
--#############################################################################
DECLARE @ReturnLen INT
SET @ReturnLen = 50;
with lastrun
as (select DEPS.OBJECT_ID
,MAX(last_execution_time) as LastRun
from sys.dm_exec_procedure_stats DEPS
group by deps.object_id
)
SELECT OL.Type
,OBJECT_NAME(OL.Obj_ID) AS 'Name'
,LTRIM(RTRIM(REPLACE(SUBSTRING(REPLACE(OBJECT_DEFINITION(OL.Obj_ID), NCHAR(0x001F), ''), CHARINDEX(@SearchString, OBJECT_DEFINITION(OL.Obj_ID)) - @ReturnLen, @ReturnLen * 2), @SearchString, ' ***-->>' + @SearchString + '<<--*** '))) AS SourceLine
,CAST(REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(MAX), REPLACE(OBJECT_DEFINITION(OL.Obj_ID), NCHAR(0x001F), '')), '&', '(A M P)'), '<', '(L T)'), '>', '(G T)'), @SearchString, '<!-->' + @SearchString + '<-->') AS XML) AS 'Hilight Search'
,(SELECT [processing-instruction(A)] = REPLACE(OBJECT_DEFINITION(OL.Obj_ID), NCHAR(0x001F), '')
FOR
XML PATH('')
,TYPE
) AS 'code'
,Modded AS Modified
,LastRun as LastRun
FROM (SELECT CASE P.type
WHEN 'P' THEN 'Proc'
WHEN 'V' THEN 'View'
WHEN 'TR' THEN 'Trig'
ELSE 'Func'
END AS 'Type'
,P.OBJECT_ID AS OBJ_id
,P.modify_Date AS modded
,LastRun.LastRun
FROM sys.Objects P WITH (NOLOCK)
LEFT join lastrun on P.object_id = lastrun.object_id
WHERE OBJECT_DEFINITION(p.OBJECT_ID) LIKE '%' + @SearchString + '%'
AND type IN ('P', 'V', 'TR', 'FN', 'IF', 'TF')
-- AND lastrun.LastRun IS NOT null
) OL
OPTION (FAST 10)
---------------------------------------------
---------------- END -----------------
---------------------------------------------
---------------------------------------------
I came up against this problem too, and in trying to solve it I kept crashing the chrome tab that was running my app. It looks like the spread operator for objects was the culprit.
With a little help from adrianolsk’s comment and sidonaldson's answer above, I used Object.assign() the output of the spread operator from babel, like so:
this.options.map(option => {
// New properties to be added
const newPropsObj = {
newkey1:value1,
newkey2:value2
};
// Assign new properties and return
return Object.assign(option, newPropsObj);
});
If you are using this for Angular, then export a function via a named export. Such as:
function someFunc(){}
export { someFunc as someFuncName }
otherwise, Angular will complain that object is not a function.
Have you tried setting the selection properties of your tableView like this:
tableView.allowsMultipleSelection = NO; tableView.allowsMultipleSelectionDuringEditing = YES; tableView.allowsSelection = NO; tableView.allowsSelectionDuringEditing YES;
If you want more fine-grain control over when selection is allowed you can override - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
in your UITableView delegate. The documentation states:
Return Value An index-path object that confirms or alters the selected row. Return an NSIndexPath object other than indexPath if you want another cell to be selected. Return nil if you don't want the row selected.
You can have this method return nil in cases where you don't want the selection to happen.
function checkTime(i) {_x000D_
if (i < 10) {_x000D_
i = "0" + i;_x000D_
}_x000D_
return i;_x000D_
}_x000D_
_x000D_
function startTime() {_x000D_
var today = new Date();_x000D_
var h = today.getHours();_x000D_
var m = today.getMinutes();_x000D_
var s = today.getSeconds();_x000D_
// add a zero in front of numbers<10_x000D_
m = checkTime(m);_x000D_
s = checkTime(s);_x000D_
document.getElementById('time').innerHTML = h + ":" + m + ":" + s;_x000D_
t = setTimeout(function() {_x000D_
startTime()_x000D_
}, 500);_x000D_
}_x000D_
startTime();
_x000D_
<div id="time"></div>
_x000D_
DEMO using javaScript only
Update
(function () {
function checkTime(i) {
return (i < 10) ? "0" + i : i;
}
function startTime() {
var today = new Date(),
h = checkTime(today.getHours()),
m = checkTime(today.getMinutes()),
s = checkTime(today.getSeconds());
document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
t = setTimeout(function () {
startTime()
}, 500);
}
startTime();
})();
Recently, I used this .NET Metadata API. I have also written a blog post about it, that shows reading, updating, and removing the EXIF data from images using C#.
using (Metadata metadata = new Metadata("image.jpg"))
{
IExif root = metadata.GetRootPackage() as IExif;
if (root != null && root.ExifPackage != null)
{
Console.WriteLine(root.ExifPackage.DateTime);
}
}
Node.js
introduced async await
in 7.6
so this makes Javascript
more beautiful.
var results = [];
var config = JSON.parse(queries);
for (var key in config) {
var query = config[key].query;
results.push(await search(query));
}
res.writeHead( ... );
res.end(results);
For this to work search
fucntion has to return a promise
or it has to be async
function
If it is not returning a Promise
you can help it to return a Promise
function asyncSearch(query) {
return new Promise((resolve, reject) => {
search(query,(result)=>{
resolve(result);
})
})
}
Then replace this line await search(query);
by await asyncSearch(query);
You could search for:
<li><a href="#">[^\n]+
And replace with:
$0</a>
Where $0
is the whole match. The exact semantics will depend on the language are you using though.
WARNING: You should avoid parsing HTML with regex. Here's why.
https://developer.mozilla.org/en/DOM/window.postMessage
window.postMessage()
window.postMessage is a method for safely enabling cross-origin communication. Normally, scripts on different pages are only allowed to access each other if and only if the pages which executed them are at locations with the same protocol (usually both http), port number (80 being the default for http), and host (modulo document.domain being set by both pages to the same value). window.postMessage provides a controlled mechanism to circumvent this restriction in a way which is secure when properly used.
Summary
window.postMessage, when called, causes a MessageEvent to be dispatched at the target window when any pending script that must be executed completes (e.g. remaining event handlers if window.postMessage is called from an event handler, previously-set pending timeouts, etc.). The MessageEvent has the type message, a data property which is set to the string value of the first argument provided to window.postMessage, an origin property corresponding to the origin of the main document in the window calling window.postMessage at the time window.postMessage was called, and a source property which is the window from which window.postMessage is called. (Other standard properties of events are present with their expected values.)
The iFrame-Resizer library uses postMessage to keep an iFrame sized to it's content, along with MutationObserver to detect changes to the content and doesn't depend on jQuery.
https://github.com/davidjbradshaw/iframe-resizer
jQuery: Cross-domain scripting goodness
http://benalman.com/projects/jquery-postmessage-plugin/
Has demo of resizing iframe window...
http://benalman.com/code/projects/jquery-postmessage/examples/iframe/
This article shows how to remove the dependency on jQuery... Plus has a lot of useful info and links to other solutions.
http://www.onlineaspect.com/2010/01/15/backwards-compatible-postmessage/
Barebones example...
http://onlineaspect.com/uploads/postmessage/parent.html
HTML 5 working draft on window.postMessage
http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages
John Resig on Cross-Window Messaging
You need to download log4j and add in your classpath.
I went overkill and came up with the following. My motivation behind this was to append to hash keys to avoid scope conflicts when merging together/flattening hashes.
Adds rekey method to Hash instances.
# Adds additional methods to Hash
class ::Hash
# Changes the keys on a hash
# Takes a block that passes the current key
# Whatever the block returns becomes the new key
# If a hash is returned for the key it will merge the current hash
# with the returned hash from the block. This allows for nested rekeying.
def rekey
self.each_with_object({}) do |(key, value), previous|
new_key = yield(key, value)
if new_key.is_a?(Hash)
previous.merge!(new_key)
else
previous[new_key] = value
end
end
end
end
my_feelings_about_icecreams = {
vanilla: 'Delicious',
chocolate: 'Too Chocolatey',
strawberry: 'It Is Alright...'
}
my_feelings_about_icecreams.rekey { |key| "#{key}_icecream".to_sym }
# => {:vanilla_icecream=>"Delicious", :chocolate_icecream=>"Too Chocolatey", :strawberry_icecream=>"It Is Alright..."}
{ _id: 1, ___something_: 'what?!' }.rekey do |key|
trimmed = key.to_s.tr('_', '')
trimmed.to_sym
end
# => {:id=>1, :something=>"what?!"}
If you pass a hash back to rekey it will merge the hash which allows you to flatten collections. This allows us to add scope to our keys when flattening a hash to avoid overwriting a key upon merging.
people = {
bob: {
name: 'Bob',
toys: [
{ what: 'car', color: 'red' },
{ what: 'ball', color: 'blue' }
]
},
tom: {
name: 'Tom',
toys: [
{ what: 'house', color: 'blue; da ba dee da ba die' },
{ what: 'nerf gun', color: 'metallic' }
]
}
}
people.rekey do |person, person_info|
person_info.rekey do |key|
"#{person}_#{key}".to_sym
end
end
# =>
# {
# :bob_name=>"Bob",
# :bob_toys=>[
# {:what=>"car", :color=>"red"},
# {:what=>"ball", :color=>"blue"}
# ],
# :tom_name=>"Tom",
# :tom_toys=>[
# {:what=>"house", :color=>"blue; da ba dee da ba die"},
# {:what=>"nerf gun", :color=>"metallic"}
# ]
# }
You may want to have a look at the code here. Although it doesn't answer your question directly you could adapt the generic class types that are used to map between data classes and business objects.
Also by using generic you run the conversion process as quickly as possible.
your panel class don't have a constructor that accepts a string
try change
RLS_strid_panel p = new RLS_strid_panel(namn1);
to
RLS_strid_panel p = new RLS_strid_panel();
p.setName1(name1);
I faced same issue (VS 2015), but my application is running under 32-bit application pool. So even though machine is 64-bit. I installed 32-bit installation and it works.
You're adding the event handler to the <select>
element.
Therefore, $(this)
will be the dropdown itself, not the selected <option>
.
You need to find the selected <option>
, like this:
var option = $('option:selected', this).attr('mytag');
Try this way:
dataGridView.CurrentCell.Value = newValue;
dataGridView.EndEdit();
dataGridView.CurrentCell.Value = newValue;
dataGridView.EndEdit();
Need to write two times...
I use this command for simple rotate a file:
mv output.log `date +%F`-output.log
In local folder I have 2019-09-25-output.log
You need to access the matches in order to get at the SDI number. Here is a function that will do it (assuming there is only 1 SDI number per cell).
For the regex, I used "sdi followed by a space and one or more numbers". You had "sdi followed by a space and zero or more numbers". You can simply change the + to * in my pattern to go back to what you had.
Function ExtractSDI(ByVal text As String) As String
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.pattern = "(sdi \d+)"
RE.Global = True
RE.IgnoreCase = True
Set allMatches = RE.Execute(text)
If allMatches.count <> 0 Then
result = allMatches.Item(0).submatches.Item(0)
End If
ExtractSDI = result
End Function
If a cell may have more than one SDI number you want to extract, here is my RegexExtract function. You can pass in a third paramter to seperate each match (like comma-seperate them), and you manually enter the pattern in the actual function call:
Ex) =RegexExtract(A1, "(sdi \d+)", ", ")
Here is:
Function RegexExtract(ByVal text As String, _
ByVal extract_what As String, _
Optional seperator As String = "") As String
Dim i As Long, j As Long
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.pattern = extract_what
RE.Global = True
Set allMatches = RE.Execute(text)
For i = 0 To allMatches.count - 1
For j = 0 To allMatches.Item(i).submatches.count - 1
result = result & seperator & allMatches.Item(i).submatches.Item(j)
Next
Next
If Len(result) <> 0 Then
result = Right(result, Len(result) - Len(seperator))
End If
RegexExtract = result
End Function
*Please note that I have taken "RE.IgnoreCase = True" out of my RegexExtract, but you could add it back in, or even add it as an optional 4th parameter if you like.
just to answer your question...btw sry that i'm 9 months late:D...there's a "workaround" 4 this kind of problems. i.e.
new AlertDialog.Builder(some_class.this).setTitle("bla").setMessage("bla bla").show();
wait();
simply add wait();
and them in the OnClickListener start the class again with notify() something like this
@Override
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), "test", Toast.LENGTH_LONG).show();
**notify**();
dialog.cancel();
}
the same workaround goes 4 toasts and other async calls in android
My personal opinion is to use what makes sense in the context. Personally I almost never use for
for array traversal. I use it for other types of iteration, but foreach
is just too easy... The time difference is going to be minimal in most cases.
The big thing to watch for is:
for ($i = 0; $i < count($array); $i++) {
That's an expensive loop, since it calls count on every single iteration. So long as you're not doing that, I don't think it really matters...
As for the reference making a difference, PHP uses copy-on-write, so if you don't write to the array, there will be relatively little overhead while looping. However, if you start modifying the array within the array, that's where you'll start seeing differences between them (since one will need to copy the entire array, and the reference can just modify inline)...
As for the iterators, foreach
is equivalent to:
$it->rewind();
while ($it->valid()) {
$key = $it->key(); // If using the $key => $value syntax
$value = $it->current();
// Contents of loop in here
$it->next();
}
As far as there being faster ways to iterate, it really depends on the problem. But I really need to ask, why? I understand wanting to make things more efficient, but I think you're wasting your time for a micro-optimization. Remember, Premature Optimization Is The Root Of All Evil
...
Edit: Based upon the comment, I decided to do a quick benchmark run...
$a = array();
for ($i = 0; $i < 10000; $i++) {
$a[] = $i;
}
$start = microtime(true);
foreach ($a as $k => $v) {
$a[$k] = $v + 1;
}
echo "Completed in ", microtime(true) - $start, " Seconds\n";
$start = microtime(true);
foreach ($a as $k => &$v) {
$v = $v + 1;
}
echo "Completed in ", microtime(true) - $start, " Seconds\n";
$start = microtime(true);
foreach ($a as $k => $v) {}
echo "Completed in ", microtime(true) - $start, " Seconds\n";
$start = microtime(true);
foreach ($a as $k => &$v) {}
echo "Completed in ", microtime(true) - $start, " Seconds\n";
And the results:
Completed in 0.0073502063751221 Seconds
Completed in 0.0019769668579102 Seconds
Completed in 0.0011849403381348 Seconds
Completed in 0.00111985206604 Seconds
So if you're modifying the array in the loop, it's several times faster to use references...
And the overhead for just the reference is actually less than copying the array (this is on 5.3.2)... So it appears (on 5.3.2 at least) as if references are significantly faster...
You can delete using cURL
or visually using one of the many tools that open source enthusiasts have created for Elasticsearch.
Using cURL
curl -XDELETE localhost:9200/index/type/documentID
e.g.
curl -XDELETE localhost:9200/shop/product/1
You will then receive a reply as to whether this was successful or not. You can delete an entire index or types with an index also, you can delete a type by leaving out the document ID like so -
curl -XDELETE localhost:9200/shop/product
If you wish to delete an index -
curl -XDELETE localhost:9200/shop
If you wish to delete more than one index that follows a certain naming convention (note the *
, a wildcard), -
curl -XDELETE localhost:9200/.mar*
Visually
There are various tools as mentioned above, I wont list them here but I will link you to one which enables you to get started straight away, located here. This tool is called KOPF, to connect to your host please click on the logo on top left hand corner and enter the URL of your cluster.
Once connected you will be able to administer your entire cluster, delete, optimise and tune your cluster.
Always (always, always, I'm not kidding) use htmlspecialchars()
:
echo htmlspecialchars($_POST['contact_list']);
Comparison sorts (i.e. ones based on comparing elements) cannot possibly be faster than n log n
. It doesn't matter what the underlying data structure is. See Wikipedia.
Other kinds of sort that take advantage of there being lots of identical elements in the list (such as the counting sort), or some expected distribution of elements in the list, are faster, though I can't think of any that work particularly well on a linked list.
Jonathan's answer didn't seem to work for me. I'm using React v0.14.0 and React Router v1.0.0-rc3. This did:
<IndexRoute component={Home}/>
.
So in Matthew's Case, I believe he'd want:
<IndexRoute component={SearchDashboard}/>
.
Source: https://github.com/rackt/react-router/blob/master/docs/guides/advanced/ComponentLifecycle.md
We can add for this:
@Transactional(readOnly = true)
public class Banking_CustomerService implements CustomerService {
public Customer getDetail(String customername) {
// do something
}
// these settings have precedence for this method
@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public void updateCustomer(Customer customer) {
// do something
}
}
Try this:
window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat="+elemA+"&lon="+elemB+"&setLatLon=Set";
To put a variable in a string enclose the variable in quotes and addition signs like this:
var myname = "BOB";
var mystring = "Hi there "+myname+"!";
Just remember that one rule!
Type Conversions T() where T is the desired datatype of the result are quite simple in GoLang.
In my program, I scan an integer i from the user input, perform a type conversion on it and store it in the variable f. The output prints the float64
equivalent of the int
input. float32
datatype is also available in GoLang
Code:
package main
import "fmt"
func main() {
var i int
fmt.Println("Enter an Integer input: ")
fmt.Scanf("%d", &i)
f := float64(i)
fmt.Printf("The float64 representation of %d is %f\n", i, f)
}
Solution:
>>> Enter an Integer input:
>>> 232332
>>> The float64 representation of 232332 is 232332.000000
If you want to remove the glow from buttons in Bootstrap (which is not necessarily bad UX in my opinion), you'll need the following code:
.btn:focus, .btn:active:focus, .btn.active:focus{
outline-color: transparent;
outline-style: none;
}
I can see that your using AppServ, mod_rewrite is disabled by default on that WAMP package (just googled it)
Solution:
Find: C:/AppServ/Apache/conf/httpd.conf
file.
and un-comment this line
#LoadModule rewrite_module modules/mod_rewrite.so
Restart apache... Simplez
Place your cursor after Apples, under Macro Tab, select Start Recording. Type the comma(,) character, space( ) character, and press End key, under Macro tab, select Stop Recording.
Ctrl+Shift+P for single playback.
I had the same problem with a file that I've created on my mac. If I try to run it in a shell with ./filename I got the file not found error message. I think that something was wrong with the file.
what I've done:
open a ssh session to the server
cat filename
copy the output to the clipboard
rm filename
touch filename
vi filename
i for insert mode
paste the content from the clipboard
ESC to end insert mode
:wq!
This worked for me.
This should be more efficient both for the application and also for the developer.
Add the following class to your web project:
/// <summary>
/// This holds all of the session variables for the site.
/// </summary>
public class SessionCentralized
{
protected internal static void Save<T>(string sessionName, T value)
{
HttpContext.Current.Session[sessionName] = value;
}
protected internal static T Get<T>(string sessionName)
{
return (T)HttpContext.Current.Session[sessionName];
}
public static int? WhatEverSessionVariableYouWantToHold
{
get
{
return Get<int?>(nameof(WhatEverSessionVariableYouWantToHold));
}
set
{
Save(nameof(WhatEverSessionVariableYouWantToHold), value);
}
}
}
Here is the implementation:
SessionCentralized.WhatEverSessionVariableYouWantToHold = id;
This is universal solution for conditions wiht more same results.
<?php
$your_name1_finded="somethnig searched"; //$your_name1_finded must be finded in previous select
$result = db_query("SELECT your_name1 FROM your_table WHERE your_name=your_condition ORDER BY your_name1, your_name2"); //Get all our ids
$i=0;
while($row = db_fetch_assoc($result)) { //Loop through our rows
$i++;
$current_row[$i]=$row['your_name1'];// field with results
if($row['your_name1'] == $your_name1_finded) {//If we haven't hit our current row yet
$yid=$i;
}
}
//buttons
if ($current_row[$yid-1]) $out_button.= "<a class='button' href='/$your_url/".$current_row[$yid-1]."'>BUTTON_PREVIOUS</a>";
if ($current_row[$yid+1]) $out_button.= "<a class='button' href='/$your_url/".$current_row[$yid+1]."'>BUTTON_NEXT</a>";
echo $out_button;//display buttons
?>
I'm surprised no one had mentioned a simple function that takes a string and a list.
function in_list(needle, hay)
{
var i, len;
for (i = 0, len = hay.length; i < len; i++)
{
if (hay[i] == needle) { return true; }
}
return false;
}
var alist = ["test"];
console.log(in_list("test", alist));
after writing the jquery code perform this validation in your route or in controller.
$.ajax({
url: "/id/edit",
data:
name:name,
method:'get',
success:function(data){
console.log(data);}
});
Route::get('/', function(){
if(Request::ajax()){
return 'it's ajax request';}
});
If you want an 2d array of integers, which elements are allocated sequentially in memory, you must declare it like
int (*intPtr)[n] = new int[x][n]
where instead of x you can write any dimension, but n must be the same in two places. Example
int (*intPtr)[8] = new int[75][8];
intPtr[5][5] = 6;
cout<<intPtr[0][45]<<endl;
must print 6.
"Dino TW" has provided the link to the comment Hibernate Mapping Exception : Repeated column in mapping for entity which has the vital information.
The link hints to provide "inverse=true" in the set mapping, I tried it and it actually works. It is such a rare situation wherein a Set and Composite key come together. Make inverse=true, we leave the insert & update of the table with Composite key to be taken care by itself.
Below can be the required mapping,
<class name="com.example.CompanyEntity" table="COMPANY">
<id name="id" column="COMPANY_ID"/>
<set name="names" inverse="true" table="COMPANY_NAME" cascade="all-delete-orphan" fetch="join" batch-size="1" lazy="false">
<key column="COMPANY_ID" not-null="true"/>
<one-to-many entity-name="vendorName"/>
</set>
</class>
I don't think you can give a path to curl, but you can CD to the location, download and CD back.
cd target/path && { curl -O URL ; cd -; }
Or using subshell.
(cd target/path && curl -O URL)
Both ways will only download if path exists. -O
keeps remote file name. After download it will return to original location.
If you need to set filename explicitly, you can use small -o
option:
curl -o target/path/filename URL
<head>
<style> t {color:#??????;letter-spacing:35px;} </style>
</head>
<t>.</t>
Make sure the color code matches the background the px is variable to desired length for the tab.
Then add your text after the < t >.< /t >
The period is used as a space holder and it is easier to type, but the '& #160;' can be used in place of the period also making it so the color coding is irrelative.
<head>
<style> t {letter-spacing:35px;} </style>
</head>
<t> </t>
This is useful mostly for displaying paragraphs of text though may come in useful in other portions of scripts.
If you prefer significant digits to fixed digits then, the signif command might be useful:
> signif(1.12345, digits = 3)
[1] 1.12
> signif(12.12345, digits = 3)
[1] 12.1
> signif(12345.12345, digits = 3)
[1] 12300
EDIT 2018/05/15: This can be achieved with a meta tag; please add that tag to your index.html and disregard this post.
This is not a complete answer to the question (for the technical answer please refer to @Zze's answer above), but there's an important step that needs to be added:
COMPATIBILITY MODE
Even with the appropriate polyfills in place, there are still issues with running Angular 2+ apps using the polyfills on IE11. If you are running the site off an intranet host (ie. if you are testing it at http://localhost or another mapped local domain name), you must go into Compatibility View settings and uncheck "Display intranet sites in Compatibility View", since IE11's Compatibility View breaks a couple of the conventions included in the ES5 polyfills for Angular.
I believe you can do the following to get the extension of a file name.
var path = require('path')
path.extname('index.html')
// returns
'.html'
If you're only looking for one:
import re
match = re.search(r'href=[\'"]?([^\'" >]+)', s)
if match:
print(match.group(1))
If you have a long string, and want every instance of the pattern in it:
import re
urls = re.findall(r'href=[\'"]?([^\'" >]+)', s)
print(', '.join(urls))
Where s
is the string that you're looking for matches in.
Quick explanation of the regexp bits:
r'...'
is a "raw" string. It stops you having to worry about escaping characters quite as much as you normally would. (\
especially -- in a raw string a\
is just a\
. In a regular string you'd have to do\\
every time, and that gets old in regexps.)"
href=[\'"]?
" says to match "href=", possibly followed by a'
or"
. "Possibly" because it's hard to say how horrible the HTML you're looking at is, and the quotes aren't strictly required.Enclosing the next bit in "
()
" says to make it a "group", which means to split it out and return it separately to us. It's just a way to say "this is the part of the pattern I'm interested in.""
[^\'" >]+
" says to match any characters that aren't'
,"
,>
, or a space. Essentially this is a list of characters that are an end to the URL. It lets us avoid trying to write a regexp that reliably matches a full URL, which can be a bit complicated.
The suggestion in another answer to use BeautifulSoup isn't bad, but it does introduce a higher level of external requirements. Plus it doesn't help you in your stated goal of learning regexps, which I'd assume this specific html-parsing project is just a part of.
It's pretty easy to do:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html_to_parse)
for tag in soup.findAll('a', href=True):
print(tag['href'])
Once you've installed BeautifulSoup, anyway.
I found a better solutions in following link. Only use "object-fit" https://medium.com/@chrisnager/center-and-crop-images-with-a-single-line-of-css-ad140d5b4a87
This is my way, using location from props. I don't know but history.isActive got undefined for me
export default class Navbar extends React.Component {
render(){
const { location } = this.props;
const homeClass = location.pathname === "/" ? "active" : "";
const aboutClass = location.pathname.match(/^\/about/) ? "active" : "";
const contactClass = location.pathname.match(/^\/contact/) ? "active" : "";
return (
<div>
<ul className="nav navbar-nav navbar-right">
<li className={homeClass}><Link to="/">Home</Link></li>
<li className={aboutClass}><Link to="about" activeClassName="active">About</Link></li>
<li className={contactClass}><Link to="contact" activeClassName="active">Contact</Link></li>
</ul>
</div>
);}}
In newer version of windows the Certuil has [CertificateStoreName] where we can give the store name. In earlier version windows this was not possible.
Installing *.pfx certificate: certutil -f -p "" -enterprise -importpfx root ""
Installing *.cer certificate: certutil -addstore -enterprise -f -v root ""
For more details below command can be executed in windows cmd. C:>certutil -importpfx -? Usage: CertUtil [Options] -importPFX [CertificateStoreName] PFXFile [Modifiers]
In my point,
border:none
is working but not valid w3c standard
so better we can use border:0;
The problem for me was that my stream was not set to the origin before download.
Response.Clear();
Response.ContentType = "Application/msword";
Response.AddHeader("Content-Disposition", "attachment; filename=myfile.docx");
//ADDED THIS LINE
myMemoryStream.Seek(0,SeekOrigin.Begin);
myMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.Close();
I bet this is what was intended as a result.
$ date -u --date=@1404372514
Thu Jul 3 07:28:34 UTC 2014
With Firefox, I:
swagger.json
definition file there, andBe careful of your slash directions!!
It seems you can drill down in folder structure but not up, annoyingly.
asp.net mvc ActionLink new tab with angular parameter
<a target="_blank" class="btn" data-ng-href="@Url.Action("RunReport", "Performance")?hotelCode={{hotel.code}}">Select Room</a>
You can use RelativeSource
to find the parent element, like this -
Binding="{Binding Path=DataContext.CurveSpeedMustBeSpecified,
RelativeSource={RelativeSource AncestorType={x:Type local:YourParentElementType}}}"
See this SO question for more details about RelativeSource
.
Not quite an answer, but a long comment with nice formatting of code to the other (correct) answers. If you try the following, you will see that what you are getting are views of the original array, not copies, and that was not the case for the accepted answer in the question you link. Be aware of the possible side effects!
>>> x = np.arange(9.0)
>>> a,b,c = np.split(x, 3)
>>> a
array([ 0., 1., 2.])
>>> a[1] = 8
>>> a
array([ 0., 8., 2.])
>>> x
array([ 0., 8., 2., 3., 4., 5., 6., 7., 8.])
>>> def chunks(l, n):
... """ Yield successive n-sized chunks from l.
... """
... for i in xrange(0, len(l), n):
... yield l[i:i+n]
...
>>> l = range(9)
>>> a,b,c = chunks(l, 3)
>>> a
[0, 1, 2]
>>> a[1] = 8
>>> a
[0, 8, 2]
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8]
As @PavelAnossov answered, the canonical answer, use the word_tokenize
function in nltk:
from nltk import word_tokenize
sent = "This is my text, this is a nice way to input text."
word_tokenize(sent)
If your sentence is truly simple enough:
Using the string.punctuation
set, remove punctuation then split using the whitespace delimiter:
import string
x = "This is my text, this is a nice way to input text."
y = "".join([i for i in x if not in string.punctuation]).split(" ")
print y
After many hours troubleshooting this stuff... Here are some quick highlights that helped us from the X-UA-Compatible
docs: http://msdn.microsoft.com/en-us/library/cc288325(VS.85).aspx#ctl00_contentContainer_ctl16
Using <meta http-equiv="X-UA-Compatible" content=" _______ " />
The Standard User Agent modes (the non-emulate ones) ignore <!DOCTYPE>
directives in your page and render based on the standards supported by that version of IE (e.g., IE=8
will better obey table border spacing and some pseudo selectors than IE=7
).
Whereas, the Emulate modes tell IE to follow any <!DOCTYPE>
directives in your page, rendering standards mode based the version you choose and quirks mode based on IE=5
Possible values for the content
attribute are:
content="IE=5"
content="IE=7"
content="IE=EmulateIE7"
content="IE=8"
content="IE=EmulateIE8"
content="IE=9"
content="IE=EmulateIE9"
content="IE=edge"
True is only valid if you're using the .NET SqlClient library. It isn't valid when using OLEDB. Where SSPI is bvaid in both either you are using .net SqlClient library or OLEDB.
By using ToDictionary
:
var dictionary = list.ToDictionary(s => s);
If it is possible that any string could be repeated, either do a Distinct
call first on the list (to remove duplicates), or use ToLookup
which allows for multiple values per key.
The examples above are a bit out of date. One new example is here:
import pyhs2 as hive
import getpass
DEFAULT_DB = 'default'
DEFAULT_SERVER = '10.37.40.1'
DEFAULT_PORT = 10000
DEFAULT_DOMAIN = 'PAM01-PRD01.IBM.COM'
u = raw_input('Enter PAM username: ')
s = getpass.getpass()
connection = hive.connect(host=DEFAULT_SERVER, port= DEFAULT_PORT, authMechanism='LDAP', user=u + '@' + DEFAULT_DOMAIN, password=s)
statement = "select * from user_yuti.Temp_CredCard where pir_post_dt = '2014-05-01' limit 100"
cur = connection.cursor()
cur.execute(statement)
df = cur.fetchall()
In addition to the standard python program, a few libraries need to be installed to allow Python to build the connection to the Hadoop databae.
1.Pyhs2, Python Hive Server 2 Client Driver
2.Sasl, Cyrus-SASL bindings for Python
3.Thrift, Python bindings for the Apache Thrift RPC system
4.PyHive, Python interface to Hive
Remember to change the permission of the executable
chmod +x test_hive2.py ./test_hive2.py
Wish it helps you. Reference: https://sites.google.com/site/tingyusz/home/blogs/hiveinpython
I apologize for reviving this thread, but there was a strategy not discussed here which may be applicable.
Using reflection it is possible to do something akin to forward declaration. For instance lets say you have a section of code that looks like this:
# We want to call a function called 'foo', but it hasn't been defined yet.
function_name = 'foo'
# Calling at this point would produce an error
# Here is the definition
def foo():
bar()
# Note that at this point the function is defined
# Time for some reflection...
globals()[function_name]()
So in this way we have determined what function we want to call before it is actually defined, effectively a forward declaration. In python the statement globals()[function_name]()
is the same as foo()
if function_name = 'foo'
for the reasons discussed above, since python must lookup each function before calling it. If one were to use the timeit
module to see how these two statements compare, they have the exact same computational cost.
Of course the example here is very useless, but if one were to have a complex structure which needed to execute a function, but must be declared before (or structurally it makes little sense to have it afterwards), one can just store a string and try to call the function later.
Use this function, it will test for the existence of the correct method.
function disabledEventPropagation(event)
{
if (event.stopPropagation){
event.stopPropagation();
}
else if(window.event){
window.event.cancelBubble=true;
}
}
git revert -m
allows to un-merge still keeping the history of both merge and un-do operation. Might be good for documenting probably.
I was using one to one mapping , but child was not getting deleted JPA was giving foreign key violation
After using orphanRemoval = true , issue got resolved
If you are using windows machine you need to do cd android
then ./gradlew clean
then run react-native run-android
The Concat
method will return an object which implements IEnumerable<T>
by returning an object (call it Cat) whose enumerator will attempt to use the two passed-in enumerable items (call them A and B) in sequence. If the passed-in enumerables represent sequences which will not change during the lifetime of Cat, and which can be read from without side-effects, then Cat may be used directly. Otherwise, it may be a good idea to call ToList()
on Cat
and use the resulting List<T>
(which will represent a snapshot of the contents of A and B).
Some enumerables take a snapshot when enumeration begins, and will return data from that snapshot if the collection is modified during enumeration. If B is such an enumerable, then any change to B which occurs before Cat has reached the end of A will show up in Cat's enumeration, but changes which occur after that will not. Such semantics may likely be confusing; taking a snapshot of Cat can avoid such issues.
Another problem you are likely to face after setting up all your URLconf patterns is that the variable {{ MEDIA_URL }}
won't work in your templates. To fix this,in your settings.py, make sure you add
django.core.context_processors.media
in your TEMPLATE_CONTEXT_PROCESSORS
.
For Python 2.7 and Pandas 0.24.2 and using Psycopg2
Psycopg2 Connection Module
def dbConnect (db_parm, username_parm, host_parm, pw_parm):
# Parse in connection information
credentials = {'host': host_parm, 'database': db_parm, 'user': username_parm, 'password': pw_parm}
conn = psycopg2.connect(**credentials)
conn.autocommit = True # auto-commit each entry to the database
conn.cursor_factory = RealDictCursor
cur = conn.cursor()
print ("Connected Successfully to DB: " + str(db_parm) + "@" + str(host_parm))
return conn, cur
Connect to the database
conn, cur = dbConnect(databaseName, dbUser, dbHost, dbPwd)
Assuming dataframe to be present already as df
output = io.BytesIO() # For Python3 use StringIO
df.to_csv(output, sep='\t', header=True, index=False)
output.seek(0) # Required for rewinding the String object
copy_query = "COPY mem_info FROM STDOUT csv DELIMITER '\t' NULL '' ESCAPE '\\' HEADER " # Replace your table name in place of mem_info
cur.copy_expert(copy_query, output)
conn.commit()
Use tr:first-child
to take the first tr
:
.category_table tr:first-child td {
vertical-align: top;
}
If you have nested tables, and you don't want to apply styles to the inner rows, add some child selectors so only the top-level td
s in the first top-level tr
get the styles:
.category_table > tbody > tr:first-child > td {
vertical-align: top;
}
This is a standard problem.
Note that MySQL allows you to omit columns from the GROUP BY clause, which Standard SQL does not, but you do not get deterministic results in general when you use the MySQL facility.
SELECT *
FROM Messages AS M
JOIN (SELECT To_ID, From_ID, MAX(TimeStamp) AS Most_Recent
FROM Messages
WHERE To_ID = 12345678
GROUP BY From_ID
) AS R
ON R.To_ID = M.To_ID AND R.From_ID = M.From_ID AND R.Most_Recent = M.TimeStamp
WHERE M.To_ID = 12345678
I've added a filter on the To_ID
to match what you're likely to have. The query will work without it, but will return a lot more data in general. The condition should not need to be stated in both the nested query and the outer query (the optimizer should push the condition down automatically), but it can do no harm to repeat the condition as shown.
In your .button
CSS, try display:inline-block
. See this JSFiddle
<div class="centered">
<p style="text-align: justify;">Cras justo odio, dapibus ac facilisis in, egestas eget quam. Nullam id dolor id nibh ultricies vehicula ut id elit. Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vitae elit libero, a pharetra augue. Praesent commodo cursus magna, vel scelerisque</p>nisl consectetur et.</div>
I was able to achieve the result by wrapping the content in a div tag and applying the attribute text-align: center. Immediately after the div tag I wrapped the content in a paragraph tag and applied attribute, text-align: justify. To make the last line centered, I excluded it from the paragraph tag, which then falls back to attribute applied in the div tag. You just have to strategic about how many words you want on the last line. I've included a demo from fiddle. Hope this helps.
#include<stdio.h>
main()
{
int i,j,k;
for(i=2;i<=100;i++)
{
k=0;
for(j=2;j<=i;j++)
{
if(i%j==0)
k++;
}
if(k==1)
printf("%d\t",i);
}
}
ImageButton \ Button etc.
CommandArgument='<%# Container.DataItemIndex%>'
code-behind
protected void gvProductsList_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = e.CommandArgument;
}
The best way to do this (that I've seen) is
var str = new Array(len + 1).join( character );
That creates an array with the given length, and then joins it with the given string to repeat. The .join()
function honors the array length regardless of whether the elements have values assigned, and undefined values are rendered as empty strings.
You have to add 1 to the desired length because the separator string goes between the array elements.
The answer by @akrun certainly does the trick. For future googlers who want to understand why, here is an explanation...
The new variable needs to be created first.
The variable "valueBin" needs to be already in the df in order for the conditional assignment to work. Essentially, the syntax of the code is correct. Just add one line in front of the code chuck to create this name --
df$newVariableName <- NA
Then you continue with whatever conditional assignment rules you have, like
df$newVariableName[which(df$oldVariableName<=250)] <- "<=250"
I blame whoever wrote that package's error message... The debugging was made especially confusing by that error message. It is irrelevant information that you have two arrays in the df with different lengths. No. Simply create the new column first. For more details, consult this post https://www.r-bloggers.com/translating-weird-r-errors/
I think this is along the lines of what you're looking for. It appears that you want to see the orderid, the subtotal for each item in the order and the total amount for the order.
select o1.orderID, o1.subtotal, sum(o2.UnitPrice * o2.Quantity) as order_total from
(
select o.orderID, o.price * o.qty as subtotal
from product p inner join orderitem o on p.ProductID= o.productID
where o.orderID = @OrderId
)as o1
inner join orderitem o2 on o1.OrderID = o2.OrderID
group by o1.orderID, o1.subtotal
The problem is in new PHP Version in macOS Sierra
Please add
stream_context_set_option($ctx, 'ssl', 'verify_peer', false);
You can use the "Except" extension method (see http://msdn.microsoft.com/en-us/library/bb337804.aspx)
In your code
var difference = people.Except(exclusions);
You error clearly says, you are trying to use locale something was not there.
>>> locale.setlocale(locale.LC_ALL, 'de_DE')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/locale.py", line 581, in setlocale
return _setlocale(category, locale)
locale.Error: unsupported locale setting
locale.Error: unsupported locale setting
To check available setting, use locale -a
deb@deb-Latitude-E7470:/ambot$ locale -a
C
C.UTF-8
en_AG
en_AG.utf8
en_AU.utf8
en_BW.utf8
en_CA.utf8
en_DK.utf8
en_GB.utf8
en_HK.utf8
en_IE.utf8
en_IN
en_IN.utf8
en_NG
en_NG.utf8
en_NZ.utf8
en_PH.utf8
en_SG.utf8
en_US.utf8
en_ZA.utf8
en_ZM
en_ZM.utf8
en_ZW.utf8
POSIX
so you can use one among,
>>> locale.setlocale(locale.LC_ALL, 'en_AG.utf8')
'en_AG.utf8'
>>>
for de_DE
This file can either be adjusted manually or updated using the tool, update-locale.
update-locale LANG=de_DE.UTF-8
system("pause");
is wrong because it's part of Windows API and so it won't work in other operation systems.
You should try to use just objects from C++ standard library. A better solution will be to write:
cin.get();
return 0;
But it will also cause problems if you have other cin
s in your code. Because after each cin
, you'll tap an Enter
or \n
which is a white space character. cin
ignores this character and leaves it in the buffer zone but cin.get()
, gets this remained character. So the control of the program reaches the line return 0
and the console gets closed before letting you see the results.
To solve this, we write the code as follows:
cin.ignore();
cin.get();
return 0;
self.tableView.tableHeaderView = segmentedControl;
If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.
To add this to SQL Developer as an extension do the following:
<items>
<item type="editor" node="TableNode" vertical="true">
<title><![CDATA[FK References]]></title>
<query>
<sql>
<![CDATA[select a.owner,
a.table_name,
a.constraint_name,
a.status
from all_constraints a
where a.constraint_type = 'R'
and exists(
select 1
from all_constraints
where constraint_name=a.r_constraint_name
and constraint_type in ('P', 'U')
and table_name = :OBJECT_NAME
and owner = :OBJECT_OWNER)
order by table_name, constraint_name]]>
</sql>
</query>
</item>
</items>
Add the extension to SQL Developer:
Navigate to any table and you should now see an additional tab next to SQL one, labelled FK References, which displays the new FK information.
Reference
If you want to do it (what I think you are trying right now) then replace this line
<input type="submit" <a href="#" onclick="history.back();">"Back"</a>
with this
<button type="button" onclick="history.back();">Back</button>
If you don't want to rely on JavaScript then you could get the HTTP_REFERER
variable an then provide it in a link like this:
<a href="<?php echo $_SERVER['HTTP_REFERER'] ?>">Back</a>
You can have a pair of extension methods to make this task easier:
public static string ToDelimitedString<T>(this IEnumerable<T> lst, string separator = ", ")
{
return lst.ToDelimitedString(p => p, separator);
}
public static string ToDelimitedString<S, T>(this IEnumerable<S> lst, Func<S, T> selector,
string separator = ", ")
{
return string.Join(separator, lst.Select(selector));
}
So now just:
new int[] { 1, 2, 3, 4, 5 }.ToDelimitedString();
The weird thing that I was experiencing was that I could make changes to the components in Visual Studio 2019 while the app was running and see my changes but, when I restarted the app, I got the Cannot Get / error. Instead of running IIS Express, I chose to run the app using Angular JS and the build window showed me that there was an error in app.component.ts. It turned out to be an extra } at the end of the file. Not sure how it got there but, when I removed it, the app works fine.
You can't use forward declaration with the typedef struct.
The struct itself is an anonymous type, so you don't have an actual name to forward declare.
typedef struct{
int one;
int two;
}myStruct;
A forward declaration like this wont work:
struct myStruct; //forward declaration fails
void blah(myStruct* pStruct);
//error C2371: 'myStruct' : redefinition; different basic types
Sure you just need to setup a local web server. Check out XAMPP: http://www.apachefriends.org/en/xampp.html
That will get you up and running in about 10 minutes.
There is now a way to run php locally without installing a server: https://stackoverflow.com/a/21872484/672229
Yes but the files need to be processed. For example you can install test servers like mamp / lamp / wamp depending on your plateform.
Basically you need apache / php running.
How about placing a touchable component around/beside the TextInput
?
var INPUTREF = 'MyTextInput';
class TestKb extends Component {
constructor(props) {
super(props);
}
render() {
return (
<View style={{ flex: 1, flexDirection: 'column', backgroundColor: 'blue' }}>
<View>
<TextInput ref={'MyTextInput'}
style={{
height: 40,
borderWidth: 1,
backgroundColor: 'grey'
}} ></TextInput>
</View>
<TouchableWithoutFeedback onPress={() => this.refs[INPUTREF].blur()}>
<View
style={{
flex: 1,
flexDirection: 'column',
backgroundColor: 'green'
}}
/>
</TouchableWithoutFeedback>
</View>
)
}
}