As hinted at by this post Error in chrome: Content-Type is not allowed by Access-Control-Allow-Headers just add the additional header to your web.config like so...
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
</customHeaders>
</httpProtocol>
If you include a file input box you can access the file as a base64 encoded string by using the FileReader object. If it's a text file a simple base64 decode will work to get the text.
Assuming the following HTML:
<input type="file" id="myfile" />
You can access using the following JQuery JS:
var file = $('#myfile').get(0).files[0];
var reader = new FileReader();
reader.onload = function (e) {
//get the file result, split by comma to remove the prefix, then base64 decode the contents
var decodedText = atob(e.target.result.split(',')[1]);
//show the file contents
alert(decoded);
};
reader.readAsDataURL(file);
You can write queries like this in SQL Server:
--each [0-9] matches a single digit, this would match 5xx
SELECT * FROM YourTable WHERE SomeField LIKE '5[0-9][0-9]'
ImmutableMap does not accept null
values whereas Collections.unmodifiableMap()
does. In addition it will never change after construction, while UnmodifiableMap
may. From the JavaDoc:
An immutable, hash-based Map with reliable user-specified iteration order. Does not permit null keys or values.
Unlike Collections.unmodifiableMap(java.util.Map), which is a view of a separate map which can still change, an instance of ImmutableMap contains its own data and will never change. ImmutableMap is convenient for public static final maps ("constant maps") and also lets you easily make a "defensive copy" of a map provided to your class by a caller.
If you are using the default R console CTRL + L
RStudio - CTRL + L
The only thing that worked for me: Go to Tools -> Options -> Text editor -> C# -> Intellisense
And turn off
Turns out I was too eager to try everything that's new in VS :) It was broken in only one solutions though.
A simpler answer.
function ($quantity) use ($tax, &$total) { .. };
$tax
inside the closure has no external effect, unless it is a pointer, like an object is.&$total
. This way, modifying the value of $total
DOES HAVE an external effect, the original variable's value changes.As @Mytskine pointed out probably the best in-depth explanation is the RFC for closures. (Upvote him for this.)
If you have a bunch of chars and want to concat them into a string, why not do
System.out.println("" + char1 + char2 + char3);
?
If anyone was wondering , how you could do this for your entire application without having to make all your activities extend a common base class in Kotlin , see the example below :
class InteractiveStoryApplication: Application() {
override fun onCreate() {
super.onCreate()
registerActivityLifecycleCallbacks(object: ActivityLifecycleCallbacks {
override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) {
activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
}
override fun onActivityPaused(activity: Activity?) {
}
override fun onActivityResumed(activity: Activity?) {
}
override fun onActivityDestroyed(activity: Activity?) {
}
override fun onActivitySaveInstanceState(activity: Activity?, outState: Bundle?) {
}
override fun onActivityStarted(activity: Activity?) {
}
override fun onActivityStopped(activity: Activity?) {
}
})
}
}
and then you have to add your common base class in AndroidManifest like so:
<application android:allowBackup="true"
android:name=".InteractiveStoryApplication"
try
hive --outputformat==csv2 -e "select * from YOUR_TABLE";
This worked for me
my hive version is "Hive 3.1.0.3.1.0.0-78"
The scanner can also use delimiters other than whitespace.
Easy example from Scanner API:
String input = "1 fish 2 fish red fish blue fish";
// \\s* means 0 or more repetitions of any whitespace character
// fish is the pattern to find
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt()); // prints: 1
System.out.println(s.nextInt()); // prints: 2
System.out.println(s.next()); // prints: red
System.out.println(s.next()); // prints: blue
// don't forget to close the scanner!!
s.close();
The point is to understand the regular expressions (regex
) inside the Scanner::useDelimiter
. Find an useDelimiter
tutorial here.
To start with regular expressions here you can find a nice tutorial.
abc… Letters
123… Digits
\d Any Digit
\D Any Non-digit character
. Any Character
\. Period
[abc] Only a, b, or c
[^abc] Not a, b, nor c
[a-z] Characters a to z
[0-9] Numbers 0 to 9
\w Any Alphanumeric character
\W Any Non-alphanumeric character
{m} m Repetitions
{m,n} m to n Repetitions
* Zero or more repetitions
+ One or more repetitions
? Optional character
\s Any Whitespace
\S Any Non-whitespace character
^…$ Starts and ends
(…) Capture Group
(a(bc)) Capture Sub-group
(.*) Capture all
(ab|cd) Matches ab or cd
Another easy way with jQuery:
$('.Numeric').bind('keydown',function(e){
if (e.which < 48 || e.which > 57)
return false;
return true;
})
Now just set your each inputs class to Numeric, like:
<input type="text" id="inp2" name="inp2" class='Numeric' />
You can use tojson
to convert each record to JSON in a MongoDB shell script.
Run this script in RoboMongo:
var cursor = db.getCollection('foo').find({}, {});
while(cursor.hasNext()) {
print(tojson(cursor.next()))
}
This prints all results as a JSON-like array.
The result is not really JSON! Some types, such as dates and object IDs, are printed as JavaScript function calls, e.g., ISODate("2016-03-03T12:15:49.996Z")
.
Might not be very efficient for large result sets, but you can limit the query. Alternatively, you can use mongoexport
.
Here is how the standard keyboard behaves for each of these input types.
See this answer for more details.
From the HTML point of view everything's been said, but to correct the PHP-side approach a little and taking thirtydot's and icktoofay's advice into account:
<?php echo '<input type="text" name="idtest" value="' . htmlspecialchars($idtest) . '">'; ?>
Try this query
SELECT v.VehicleId, v.Name, ll.LocationList
FROM Vehicles v
LEFT JOIN
(SELECT
DISTINCT
VehicleId,
REPLACE(
REPLACE(
REPLACE(
(
SELECT City as c
FROM Locations x
WHERE x.VehicleID = l.VehicleID FOR XML PATH('')
),
'</c><c>',', '
),
'<c>',''
),
'</c>', ''
) AS LocationList
FROM Locations l
) ll ON ll.VehicleId = v.VehicleId
I had the same problem, but I had my activity declared in the Manifest file, with the correct name.
My problem was that I didn't have to imported a third party libraries in a "libs" folder, and I needed reference them in my proyect (Right-click, properties, Java Build Path, Libraries, Add Jar...).
This method is easier and safer
var lOrders = new List<string>();
bool insertOrderNew = lOrders.Find(r => r == "1234") == null ? true : false
Use this one:
box-shadow: 0px 0px 0px 1px red;
Based on the fact that the request isn't sent on the default port 80/443 this Ajax call is automatically considered a cross-origin resource (CORS) request, which in other words means that the request automatically issues an OPTIONS request which checks for CORS headers on the server's/servlet's side.
This happens even if you set
crossOrigin: false;
or even if you ommit it.
The reason is simply that localhost != localhost:57124
. Try sending it only to localhost
without the port - it will fail, because the requested target won't be reachable, however notice that if the domain names are equal the request is sent without the OPTIONS request before POST.
Using the ASP.NET Core Tag Helper feature:
<a asp-controller="Home" asp-action="SetLanguage" asp-route-yourparam1="@item.Value">@item.Text</a>
I got same problem if i understand your question correctly, I want to know the last inserted id after every insert performance in SQLite operation. i tried the following statement:
select * from table_name order by id desc limit 1
The id is the first column and primary key of the table_name, the mentioned statement show me the record with the largest id.
But the premise is u never deleted any row so the numbers of id equal to the numbers of rows.
I had a similar problem application-level add-in in VSTO, the exception HRESULT: 0x800A03EC when adding new sheet.
The error code 0x800A03EC (or -2146827284) means NAME_NOT_FOUND; in other words, you've asked for something, and Excel can't find it.
Dominic Zukiewicz @ Excel error HRESULT: 0x800A03EC while trying to get range with cell's name
Then I finally realized ThisWorkbook triggered the exception. ActiveWorkbook went OK.
Excel.Worksheet newSheetException = Globals.ThisAddIn.Application.ThisWorkbook.Worksheets.Add(Type.Missing, sheet, Type.Missing, Type.Missing);
Excel.Worksheet newSheetNoException = Globals.ThisAddIn.Application.ActiveWorkbook.Worksheets.Add(Type.Missing, sheet, Type.Missing, Type.Missing);
def f(x) -> str:
return x+4
print(f(45))
# will give the result :
49
# or with other words '-> str' has NO effect to return type:
print(f(45).__class__)
<class 'int'>
use the String.Trim()
function.
string foo = " hello ";
string bar = foo.Trim();
Console.WriteLine(bar); // writes "hello"
The whole reason for having kubernetes is so it manages the containers for you so you don't have to care so much about the lifecyle of the containers in the pod.
Since you have a deployment
setup that uses replica set
. You can delete the pod using kubectl delete pod test-1495806908-xn5jn
and kubernetes will manage the creation of a new pod with the 2 containers without any downtime. Trying to manually restart single containers in pods negates the whole benefits of kubernetes.
Sometimes the dependencies don't update even with Maven->Update Project->Force Update option checked using m2eclipse plugin.
In case it doesn't work for anyone else, this method worked for me:
mvn eclipse:eclipse
This will update your .classpath file with the new dependencies while preserving your .project settings and other eclipse config files.
If you want to clear your old settings for whatever reason, you can run:
mvn eclipse:clean
mvn eclipse:eclipse
mvn eclipse:clean will erase your old settings, then mvn eclipse:eclipse will create new .project, .classpath and other eclipse config files.
Create a User-Defined TableType
in your database:
CREATE TYPE [dbo].[MyTableType] AS TABLE(
[Id] int NOT NULL,
[Name] [nvarchar](128) NULL
)
and define a parameter in your Stored Procedure
:
CREATE PROCEDURE [dbo].[InsertTable]
@myTableType MyTableType readonly
AS
BEGIN
insert into [dbo].Records select * from @myTableType
END
and send your DataTable
directly to sql server:
using (var command = new SqlCommand("InsertTable") {CommandType = CommandType.StoredProcedure})
{
var dt = new DataTable(); //create your own data table
command.Parameters.Add(new SqlParameter("@myTableType", dt));
SqlHelper.Exec(command);
}
To edit the values inside stored-procedure, you can declare a local variable with the same type and insert input table into it:
DECLARE @modifiableTableType MyTableType
INSERT INTO @modifiableTableType SELECT * FROM @myTableType
Then, you can edit @modifiableTableType
:
UPDATE @modifiableTableType SET [Name] = 'new value'
You might just want to use the new TUN.Logging PowerShell module, this can also send a log mail. Just use the Start-Log and/or Start-MailLog cmdlets to start logging and then just use Write-HostLog, Write-WarningLog, Write-VerboseLog, Write-ErrorLog etc. to write to console and log file/mail. Then call Send-Log and/or Stop-Log at the end and voila, you got your logging. Just install it from the PowerShell Gallery via
Install-Module -Name TUN.Logging
Or just follow the link: https://www.powershellgallery.com/packages/TUN.Logging
Documentation of the module can be found here: https://github.com/echalone/TUN/blob/master/PowerShell/Modules/TUN.Logging/TUN.Logging.md
either
bin\Iris.exe
(no leading slash - because that means start right from the root)
or \Program\bin\Iris.exe
(full path)
For a specific folder I used:
git checkout -- FolderToClean/*
With pivot_data as
(
select
action, -- grouping column
view_edit -- spreading column
from tbl
)
select action, [view], [edit]
from pivot_data
pivot ( max(view_edit) for view_edit in ([view], [edit]) ) as p;
The accepted answer helped me but I got tripped up while doing concatenation of varchars involving case statements. I know the OP's question does not involve case statements but I thought this would be helpful to post here for others like me who ended up here while struggling to build long dynamic SQL statements involving case statements.
When using case statements with string concatenation the rules mentioned in the accepted answer apply to each section of the case statement independently.
declare @l_sql varchar(max) = ''
set @l_sql = @l_sql +
case when 1=1 then
--without this correction the result is truncated
--CONVERT(VARCHAR(MAX), '')
+REPLICATE('1', 8000)
+REPLICATE('1', 8000)
end
print len(@l_sql)
multipart/form-data
is used when you want to upload files to the server. Please check this article for details.
InputStream is;
InputStreamReader r = new InputStreamReader(is);
BufferedReader br = new BufferedReader(r);
@Chaibi Alaa, To make the user able to add only once, and move the marker; You can set the marker on first click and then just change the position on subsequent clicks.
var marker;
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
function placeMarker(location) {
if (marker == null)
{
marker = new google.maps.Marker({
position: location,
map: map
});
}
else
{
marker.setPosition(location);
}
}
I have tried with all the methods shown in this thread and none worked for me, try this one. It worked for me.
((MainActivity) getContext().getApplicationContext()).Method();
Have a look at the add
filter.
Edit: You can chain filters, so you could do "shop/"|add:shop_name|add:"/base.html"
. But that won't work because it is up to the template tag to evaluate filters in arguments, and extends doesn't.
I guess you can't do this within templates.
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
E.g. thenReturn() may be missing.
For mocking of void methods try out below:
//Kotlin Syntax
Mockito.`when`(voidMethodCall())
.then {
Unit //Do Nothing
}
You can disable and re-enable the foreign key constraints before and after deleting:
alter table MyOtherTable nocheck constraint all
delete from MyTable
alter table MyOtherTable check constraint all
lowercase-with-hyphens
is the style I most often see on GitHub.*
lowercase_with_underscores
is probably the second most popular style I see.
The former is my preference because it saves keystrokes.
* Anecdotal; I haven't collected any data.
Since the original question was about jQuery.get
, it is worth mentioning here that (as mentioned here) one could use async: false
in a $.get()
but ideally avoid it since asynchronous XMLHTTPRequest
is deprecated (and the browser may give a warning):
$.get({
url: url,// mandatory
data: data,
success: success,
dataType: dataType,
async:false // to make it synchronous
});
Perhaps the following, then your calculator can use arbitrary number base (e.g. hex, binary, base 7! etc): (untested)
def convert(str):
try:
base = 10 # default
if ':' in str:
sstr = str.split(':')
base, str = int(sstr[0]), sstr[1]
val = int(str, base)
except ValueError:
val = None
return val
val = convert(raw_input("Enter value:"))
# 10 : Decimal
# 16:a : Hex, 10
# 2:1010 : Binary, 10
The ID of the two repos are both localSnap
; that's probably not what you want and it might confuse Maven.
If that's not it: There might be more repository
elements in your POM. Search the output of mvn help:effective-pom
for repository
to make sure the number and place of them is what you expect.
It can be done without printing magic strings and using TextFinder. Here's some info on it.
Basically you need a .jar file from http://yourserver.com/cli available in shell scripts, then you can use the following command to mark a build unstable:
java -jar jenkins-cli.jar set-build-result unstable
To mark build unstable on error, you can use:
failing_cmd cmd_args || java -jar jenkins-cli.jar set-build-result unstable
The problem is that jenkins-cli.jar has to be available from shell script. You can either put it in easy-to-access path, or download in via job's shell script:
wget ${JENKINS_URL}jnlpJars/jenkins-cli.jar
There is a solution that requires no non-standard modules and is 100% transportable
import thread
def input_thread(a_list):
raw_input()
a_list.append(True)
def do_stuff():
a_list = []
thread.start_new_thread(input_thread, (a_list,))
while not a_list:
stuff()
Quick guide to setup a cron job
Create a new text file, example: mycronjobs.txt
For each daily job (00:00, 03:45), save the schedule lines in mycronjobs.txt
00 00 * * * ruby path/to/your/script.rb
45 03 * * * path/to/your/script2.sh
Send the jobs to cron (everytime you run this, cron deletes what has been stored and updates with the new information in mycronjobs.txt)
crontab mycronjobs.txt
Extra Useful Information
See current cron jobs
crontab -l
Remove all cron jobs
crontab -r
Add this code on values anim
<scale
android:duration="@android:integer/config_longAnimTime"
android:fromXScale="0.2"
android:fromYScale="0.2"
android:toXScale="1.0"
android:toYScale="1.0"
android:pivotX="50%"
android:pivotY="50%"/>
<alpha
android:fromAlpha="0.1"
android:toAlpha="1.0"
android:duration="@android:integer/config_longAnimTime"
android:interpolator="@android:anim/accelerate_decelerate_interpolator"/>
call on styles.xml
<style name="DialogScale">
<item name="android:windowEnterAnimation">@anim/scale_in</item>
<item name="android:windowExitAnimation">@anim/scale_out</item>
</style>
On java code: set Onclick
public void onClick(View v) {
fab_onclick(R.style.DialogScale, "Scale" ,(Activity) context,getWindow().getDecorView().getRootView());
// Dialogs.fab_onclick(R.style.DialogScale, "Scale");
}
setup on method:
alertDialog.getWindow().getAttributes().windowAnimations = type;
If you are using lodash and don't want to modify either array, you can use the function _.xor(). It compares the two arrays as sets and returns the set that contains their difference. If the length of this difference is zero, the two arrays are essentially equal:
var a = [1, 2, 3];
var b = [3, 2, 1];
var c = new Array(1, 2, 3);
_.xor(a, b).length === 0
true
_.xor(b, c).length === 0
true
To add to svick's answer, the -m
option simply adds a message to your stash, and is entirely optional. Thus, the command
git stash push [paths you wish to stash]
is perfectly valid. So for instance, if I want to only stash changes in the src/
directory, I can just run
git stash push src/
Update your google play services or just create the new emulator. When you install the new emulator this problem will automatically be solved. Happy coding :)
to expand on Idriss's answer, here's my static method that works like a champ:
using System.Web.Mail;
public static void SendEmail(String Subject, String sMessage, String EmailAddress, String STMPServer, int SMTPPort, String UserName = "", String Password = null, Boolean IsSecure = true, Boolean IsHTML = true, String FromAddress = "[email protected]") {
string SMTP_SERVER = "http://schemas.microsoft.com/cdo/configuration/smtpserver";
string SMTP_SERVER_PORT = "http://schemas.microsoft.com/cdo/configuration/smtpserverport";
string SEND_USING = "http://schemas.microsoft.com/cdo/configuration/sendusing";
string SMTP_USE_SSL = "http://schemas.microsoft.com/cdo/configuration/smtpusessl";
string SMTP_AUTHENTICATE = "http://schemas.microsoft.com/cdo/configuration/smtpauthenticate";
string SEND_USERNAME = "http://schemas.microsoft.com/cdo/configuration/sendusername";
string SEND_PASSWORD = "http://schemas.microsoft.com/cdo/configuration/sendpassword";
MailMessage mail = new MailMessage();
mail.Fields[SMTP_SERVER] = STMPServer;
mail.Fields[SMTP_SERVER_PORT] = SMTPPort;
mail.Fields[SEND_USING] = 2;
mail.Fields[SMTP_USE_SSL] = IsSecure;
if(!String.IsNullOrEmpty(UserName) && !String.IsNullOrEmpty(Password))
{
mail.Fields[SMTP_AUTHENTICATE] = 1;
mail.Fields[SEND_USERNAME] = UserName;
mail.Fields[SEND_PASSWORD] = Password;
}
else
{
mail.Fields[SMTP_AUTHENTICATE] = 0;
}
mail.From = FromAddress;
mail.To = EmailAddress;
mail.Subject = Subject;
if (IsHTML)
{
mail.BodyFormat = MailFormat.Html;
}
else
{
mail.BodyFormat = MailFormat.Text;
}
mail.Body = sMessage;
SmtpMail.Send(mail);
}
I cross verified all the credentials
Added new server key and deleted old one
Downloaded google-services.json again
Nothing solved the issue
Then I just clean the project and then rebuild the project.After that it's working fine
Delete lines from all files that match the match
grep -rl 'text_to_search' . | xargs sed -i '/text_to_search/d'
SELECT DATEDIFF(NOW(),pickup_date) AS noofday
FROM cir_order
WHERE DATEDIFF(NOW(),pickup_date)>2;
or
SELECT *
FROM cir_order
WHERE cir_order.`cir_date` >= DATE_ADD( CURDATE(), INTERVAL -10 DAY )
std::map
will sort its elements by keys
. It doesn't care about the values
when sorting.
You can use std::vector<std::pair<K,V>>
then sort it using std::sort
followed by std::stable_sort
:
std::vector<std::pair<K,V>> items;
//fill items
//sort by value using std::sort
std::sort(items.begin(), items.end(), value_comparer);
//sort by key using std::stable_sort
std::stable_sort(items.begin(), items.end(), key_comparer);
The first sort should use std::sort
since it is nlog(n)
, and then use std::stable_sort
which is n(log(n))^2
in the worst case.
Note that while std::sort
is chosen for performance reason, std::stable_sort
is needed for correct ordering, as you want the order-by-value to be preserved.
@gsf noted in the comment, you could use only std::sort
if you choose a comparer which compares values
first, and IF they're equal, sort the keys
.
auto cmp = [](std::pair<K,V> const & a, std::pair<K,V> const & b)
{
return a.second != b.second? a.second < b.second : a.first < b.first;
};
std::sort(items.begin(), items.end(), cmp);
That should be efficient.
But wait, there is a better approach: store std::pair<V,K>
instead of std::pair<K,V>
and then you don't need any comparer at all — the standard comparer for std::pair
would be enough, as it compares first
(which is V
) first then second
which is K
:
std::vector<std::pair<V,K>> items;
//...
std::sort(items.begin(), items.end());
That should work great.
If you are using the Office 365 SMTP gateway then "SMTP Error: data not accepted." is the response you will get if the mailbox is full (even if you are just sending from it).
Try deleting some messages out of the mailbox.
If you can't know the progress you should not fake it by abusing a progress bar, instead just display some sort of busy icon like en.wikipedia.org/wiki/Throbber#Spinning_wheel Show it when starting the task and hide it when it's finished. That would make for a more "honest" GUI.
$_SERVER['PHP_SELF']
for the page name and $_GET['id']
for a specific parameter.
try print_r($_GET);
to print out all the parameters.
for your request echo $_SERVER['PHP_SELF']."?id=".$_GET['id'];
return all the parameters echo $_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING'];
Never mind, I found the answer.
This will do the trick.
Dim colIndex As Long
colIndex = Application.Match(colName, Range(Cells(rowIndex, 1), Cells(rowIndex, 100)), 0)
Since you have an object, not a jQuery wrapper, you need to use a different variant of $.each()
$.each(json, function (key, data) {
console.log(key)
$.each(data, function (index, data) {
console.log('index', data)
})
})
Demo: Fiddle
Right click properties, Application tab, then see the assembly name and default namespace
All of the List
classes maintain the order of insertion. They use different implementations based on performance and other characteristics (e.g. ArrayList
for speed of access of a specific index, LinkedList
for simply maintaining order). Since there is no key, duplicates are allowed.
The Set
classes do not maintain insertion order. They may optionally impose a specific order (as with SortedSet
), but typically have an implementation-defined order based on some hash function (as with HashSet
). Since Set
s are accessed by key, duplicates are not allowed.
I was also getting "Request return with error:parsererror." in the javascript console. In my case it wasn´t a matter of Json, but I had to pass to the view text area a valid encoding.
String encodedString = getEncodedString(text, encoding);
view.setTextAreaContent(encodedString);
Try this
rails destroy model Rating
It will remove model, migration, tests and fixtures
Just pick the columns you want directly....
df[['A','E','I','C']]
GROUP BY can be selected from Total row in query design view in MS Access.
If Total row not shown in design view (as in my case). You can go to SQL View and add GROUP By fname etc. Then Total row will automatically show in design view.
You have to select as Expression in this row for calculated fields.
To get caller/called class name use below code, it works fine for me.
String callerClassName = new Exception().getStackTrace()[1].getClassName();
String calleeClassName = new Exception().getStackTrace()[0].getClassName();
use Class="NO-CACHE"
sample html:
<div>
<img class="NO-CACHE" src="images/img1.jpg" />
<img class="NO-CACHE" src="images/imgLogo.jpg" />
</div>
jQuery:
$(document).ready(function ()
{
$('.NO-CACHE').attr('src',function () { return $(this).attr('src') + "?a=" + Math.random() });
});
javascript:
var nods = document.getElementsByClassName('NO-CACHE');
for (var i = 0; i < nods.length; i++)
{
nods[i].attributes['src'].value += "?a=" + Math.random();
}
Result: src="images/img1.jpg" => src="images/img1.jpg?a=0.08749723793963926"
The hex editor plugin mentioned by ellak still works, but it seems that you need the TextFX Characters plugin as well.
I initially installed only the hex plugin and Notepad++ would no longer pop up; instead it started eating memory (killed it at 1.2 GB). I removed it again and for other reasons installed the TextFX plugin (based on Find multiple lines in Notepad++)
Out of curiosity I installed the hex plugin again and now it works.
Note that this is on a fresh install of Windows 7 64 bit.
You do it by stacking case labels:
switch(myvar)
{
case 2:
case 5:
...
break;
case 7:
case 12:
...
break;
...
}
Look at Java sources: valueOf
is using parseInt
:
/**
* Parses the specified string as a signed decimal integer value.
*
* @param string
* the string representation of an integer value.
* @return an {@code Integer} instance containing the integer value
* represented by {@code string}.
* @throws NumberFormatException
* if {@code string} cannot be parsed as an integer value.
* @see #parseInt(String)
*/
public static Integer valueOf(String string) throws NumberFormatException {
return valueOf(parseInt(string));
}
parseInt
returns int
/**
* Parses the specified string as a signed decimal integer value. The ASCII
* character \u002d ('-') is recognized as the minus sign.
*
* @param string
* the string representation of an integer value.
* @return the primitive integer value represented by {@code string}.
* @throws NumberFormatException
* if {@code string} cannot be parsed as an integer value.
*/
public static int parseInt(String string) throws NumberFormatException {
return parseInt(string, 10);
}
You can use CSS3 transitions with rotate()
to spin the image on hover.
img {_x000D_
border-radius: 50%;_x000D_
-webkit-transition: -webkit-transform .8s ease-in-out;_x000D_
transition: transform .8s ease-in-out;_x000D_
}_x000D_
img:hover {_x000D_
-webkit-transform: rotate(360deg);_x000D_
transform: rotate(360deg);_x000D_
}
_x000D_
<img src="https://i.stack.imgur.com/BLkKe.jpg" width="100" height="100"/>
_x000D_
Here is a fiddle DEMO
More info and references :
You can pass a regex to the spec command which will only run it
blocks matching the name you supply.
spec path/to/my_spec.rb -e "should be the correct answer"
2019 Update: Rspec2 switched from the 'spec' command to the 'rspec' command.
I'm using a 3rd party program that executes Oracle SQL and I encountered this error. Prior to a SELECT
statement, I had some commented notes that included special characters. Removing the comments resolved the issue.
REST is very abstract. It helps to have some good, simple, real-world examples.
Take for example all major social media apps -- Tumblr, Instagram, Facebook, and Twitter. They all have a forever-scrolling view where the farther you scroll down, the more content you see, further and further back in time. However, we've all experienced that moment where you lose where you were scrolled to, and the app resets you back to the top. Like if you quit the app, then when you reopen it, you're back at the top again.
The reason why, is because the server did not store your session state. Sadly, your scroll position was just stored in RAM on the client.
Fortunately you don't have to log back in when you reconnect, but that's only because your client-side also stored login certificate has not expired. Delete and reinstall the app, and you're going to have to log back in, because the server did not associate your IP address with your session.
You don't have a login session on the server, because they abide by REST.
Now the above examples don't involve a web browser at all, but on the back end, the apps are communicating via HTTPS with their host servers. My point is that REST does not have to involve cookies and browsers etc. There are various means of storing client-side session state.
But lets talk about web browsers for a second, because that brings up another major advantage of REST that nobody here is talking about.
If the server tried to store session state, how is it supposed to identify each individual client?
It could not use their IP address, because many people could be using that same address on a shared router. So how, then?
It can't use MAC address for many reasons, not the least of which because you can be logged into multiple different Facebook accounts simultaneously on different browsers plus the app. One browser can easily pretend to be another one, and MAC addresses are just as easy to spoof.
If the server has to store some client-side state to identify you, it has to store it in RAM longer than just the time it takes to process your requests, or else it has to cache that data. Servers have limited amounts of RAM and cache, not to mention processor speed. Server-side state adds to all three, exponentially. Plus if the server is going to store any state about your sessions then it has to store it separately for each browser and app you're currently logged in with, and also for each different device you use.
So... I hope that you see now why REST is so important for scalability. I hope you can start to see why server-side session state is to server scalability what welded-on anvils are to car acceleration.
Where people get confused is by thinking that "state" refers to, like, information stored in a database. No, it refers to any information that needs to be in the RAM of the server when you're using it.
Create a dummy tag that is not going to rendered on the page but it will work as holder for ng-repeat:
<dummyTag ng-repeat="featureItem in item.features">{{featureItem.feature}}</br> </dummyTag>
You are using the object that contains the null value reference. So it's giving a null exception. In the example the string value is null and when checking its length, the exception occurred.
Example:
string value = null;
if (value.Length == 0) // <-- Causes exception
{
Console.WriteLine(value); // <-- Never reached
}
The exception error is:
Unhandled Exception:
System.NullReferenceException: Object reference not set to an instance of an object. at Program.Main()
As of now, you can only store string values in localStorage. You'll need to serialize the array object and then store it in localStorage.
For example:
localStorage.setItem('session', a.join('|'));
or
localStorage.setItem('session', JSON.stringify(a));
For people like me, linq addicts, and based on svick's answer, here a linq approach:
using System.Linq;
//...
//make it linq iterable.
var obj_linq = Response.Cast<KeyValuePair<string, JToken>>();
Now you can make linq expressions like:
JToken x = obj_linq
.Where( d => d.Key == "my_key")
.Select(v => v)
.FirstOrDefault()
.Value;
string y = ((JValue)x).Value;
Or just:
var y = obj_linq
.Where(d => d.Key == "my_key")
.Select(v => ((JValue)v.Value).Value)
.FirstOrDefault();
Or this one to iterate over all data:
obj_linq.ToList().ForEach( x => { do stuff } );
You can use both with relatively few issues. Twitter Bootstrap uses jQuery 1.7.1 (as of this writing), and I can't think of any reasons why you cannot integrate additional Jquery UI components into your HTML templates.
I've been using a combination of HTML5 Boilerplate & Twitter Bootstrap built at Initializr.com. This combines two awesome starter templates into one great starter project. Check out the details at http://html5boilerplate.com/ and http://www.initializr.com/ Or to get started right away, go to http://www.initializr.com/, click the "Bootstrap 2" button, and click "Download It". This will give you all the js and css you need to get started.
And don't be scared off by HTML5 and CSS3. Initializr and HTML5 Boilerplate include polyfills and IE specific code that will allow all features to work in IE 6, 7 8, and 9.
The use of LESS in Twitter Bootstrap is also optional. They use LESS to compile all the CSS that is used by Bootstrap, but if you just want to override or add your own styles, they provide an empty css file for that purpose.
There is also a blank js file (script.js) for you to add custom code. This is where you would add your handlers or selectors for additional jQueryUI components.
$x = $y ?? 'dev'
is short hand for x = y if y is set, otherwise x = 'dev'
There is also
$x = $y =="SOMETHING" ? 10 : 20
meaning if y equals 'SOMETHING' then x = 10, otherwise x = 20
What is the truth?
Microsoft's documentation describing the behaviour of their browser is correct.
Is there any solution to hide the addressbar?
No. If you could hide it, then you could use HTML/CSS to make something that looked like a common address bar. You could then put a different address in it. You could then trick people into thinking they were on a different site and entering their password for it.
It is impossible to conceal the user's location from them because it is essential for security that they know what their location is.
You can send data from one actvity to another with an Intent
Intent sendStuff = new Intent(this, TargetActivity.class);
sendStuff.putExtra(key, stringvalue);
startActivity(sendStuff);
You then can retrieve this information in the second activity by getting the intent and extracting the string extra. Do this in your onCreate()
method.
Intent startingIntent = getIntent();
String whatYouSent = startingIntent.getStringExtra(key, value);
Then all you have to do is call setText on your TextView
and use that string.
Check to make sure that the file is complete. This error message can occur if you only partially downloaded a file or if it has major issues. Check the MD5sum.
RIGHT('00' + CONVERT(VARCHAR, MyNumber), 2)
Be warned that this will cripple numbers > 99. You might want to factor in that possibility.
Look at this blog here. It describes a way to do this, by defining an EntitySorter<T>
.
It allows you to pass in an IEntitySorter<T>
into your service methods and use it like this:
public static Person[] GetAllPersons(IEntitySorter<Person> sorter)
{
using (var db = ContextFactory.CreateContext())
{
IOrderedQueryable<Person> sortedList = sorter.Sort(db.Persons);
return sortedList.ToArray();
}
}
And you can create an EntitiySorter
like this:
IEntitySorter<Person> sorter = EntitySorter<Person>
.OrderBy(p => p.Name)
.ThenByDescending(p => p.Id);
Or like this:
var sorter = EntitySorter<Person>
.OrderByDescending("Address.City")
.ThenBy("Id");
You basically have 3 options to prevent the PowerShell Console window from closing, that I describe in more detail on my blog post.
PowerShell -NoExit "C:\SomeFolder\SomeScript.ps1"
Read-Host -Prompt "Press Enter to exit"
Global Fix: Change your registry key to always leave the PowerShell Console window open after the script finishes running. Here's the 2 registry keys that would need to be changed:
? Open With ? Windows PowerShell
When you right-click a .ps1 file and choose Open With
Registry Key: HKEY_CLASSES_ROOT\Applications\powershell.exe\shell\open\command
Default Value:
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "%1"
Desired Value:
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "& \"%1\""
? Run with PowerShell
When you right-click a .ps1 file and choose Run with PowerShell (shows up depending on which Windows OS and Updates you have installed).
Registry Key: HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\0\Command
Default Value:
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & '%1'"
Desired Value:
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoExit "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & \"%1\""
You can download a .reg file from my blog to modify the registry keys for you if you don't want to do it manually.
It sounds like you likely want to use option #2. You could even wrap your whole script in a try block, and only prompt for input if an error occurred, like so:
try
{
# Do your script's stuff
}
catch
{
Write-Error $_.Exception.ToString()
Read-Host -Prompt "The above error occurred. Press Enter to exit."
}
It's possible to set the center aligned view as an anchor for other views. In the example below "@+id/stat_2" centered horizontally in parent and it serves as an anchor for other views in this layout.
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/stat_1"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:gravity="center"
android:maxLines="1"
android:text="10"
android:textColor="#777"
android:textSize="22sp"
app:layout_constraintTop_toTopOf="@+id/stat_2"
app:layout_constraintEnd_toStartOf="@+id/divider_1" />
<TextView
android:id="@+id/stat_detail_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Streak"
android:textColor="#777"
android:textSize="12sp"
app:layout_constraintTop_toBottomOf="@+id/stat_1"
app:layout_constraintStart_toStartOf="@+id/stat_1"
app:layout_constraintEnd_toEndOf="@+id/stat_1" />
<View
android:id="@+id/divider_1"
android:layout_width="1dp"
android:layout_height="0dp"
android:layout_marginEnd="16dp"
android:background="#ccc"
app:layout_constraintTop_toTopOf="@+id/stat_2"
app:layout_constraintEnd_toStartOf="@+id/stat_2"
app:layout_constraintBottom_toBottomOf="@+id/stat_detail_2" />
<TextView
android:id="@+id/stat_2"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:gravity="center"
android:maxLines="1"
android:text="243"
android:textColor="#777"
android:textSize="22sp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toBottomOf="parent" />
<TextView
android:id="@+id/stat_detail_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="1"
android:text="Calories Burned"
android:textColor="#777"
android:textSize="12sp"
app:layout_constraintTop_toBottomOf="@+id/stat_2"
app:layout_constraintStart_toStartOf="@+id/stat_2"
app:layout_constraintEnd_toEndOf="@+id/stat_2" />
<View
android:id="@+id/divider_2"
android:layout_width="1dp"
android:layout_height="0dp"
android:layout_marginStart="16dp"
android:background="#ccc"
app:layout_constraintBottom_toBottomOf="@+id/stat_detail_2"
app:layout_constraintStart_toEndOf="@+id/stat_2"
app:layout_constraintTop_toTopOf="@+id/stat_2" />
<TextView
android:id="@+id/stat_3"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:gravity="center"
android:maxLines="1"
android:text="3200"
android:textColor="#777"
android:textSize="22sp"
app:layout_constraintTop_toTopOf="@+id/stat_2"
app:layout_constraintStart_toEndOf="@+id/divider_2" />
<TextView
android:id="@+id/stat_detail_3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="1"
android:text="Steps"
android:textColor="#777"
android:textSize="12sp"
app:layout_constraintTop_toBottomOf="@+id/stat_3"
app:layout_constraintStart_toStartOf="@+id/stat_3"
app:layout_constraintEnd_toEndOf="@+id/stat_3" />
</android.support.constraint.ConstraintLayout>
Here's how it works on smallest smartphone (3.7 480x800 Nexus One) vs largest smartphone (5.5 1440x2560 Pixel XL)
yes you can ;-)
the simplest way is using this ->http://www.androidfanatic.com/community-forums.html?func=view&catid=9&id=2248
The old link is dead it was for a Debian install script There is an app for that in the android market but you will need root
When I want to access the application file version (what is set in Assembly Information -> File version), say to set a label's text to it on form load to display the version, I have just used
versionlabel.Text = "Version " + Application.ProductVersion;
This approach requires a reference to System.Windows.Forms
.
You can achieve it like that:
ng-style="{ 'width' : (myObject.value == 'ok') ? '100%' : '0%' }"
If you want the units h
, min
and sec
for a duration you can use this:
public static String convertSeconds(int seconds) {
int h = seconds/ 3600;
int m = (seconds % 3600) / 60;
int s = seconds % 60;
String sh = (h > 0 ? String.valueOf(h) + " " + "h" : "");
String sm = (m < 10 && m > 0 && h > 0 ? "0" : "") + (m > 0 ? (h > 0 && s == 0 ? String.valueOf(m) : String.valueOf(m) + " " + "min") : "");
String ss = (s == 0 && (h > 0 || m > 0) ? "" : (s < 10 && (h > 0 || m > 0) ? "0" : "") + String.valueOf(s) + " " + "sec");
return sh + (h > 0 ? " " : "") + sm + (m > 0 ? " " : "") + ss;
}
int seconds = 3661;
String duration = convertSeconds(seconds);
That's a lot of conditional operators. The method will return those strings:
0 -> 0 sec
5 -> 5 sec
60 -> 1 min
65 -> 1 min 05 sec
3600 -> 1 h
3601 -> 1 h 01 sec
3660 -> 1 h 01
3661 -> 1 h 01 min 01 sec
108000 -> 30 h
Use
System.Drawing.Color.FromArgb(myHashCode);
Here's an online tool that will take JSON, including nested objects or nested arrays of objects and generate a Java source with Jackson annotations.
I normally create a static method on form/dialog, that I can call. This returns the success (OK-button) or failure, along with the values that needs to be filled in.
public class ResultFromFrmMain {
public DialogResult Result { get; set; }
public string Field1 { get; set; }
}
And on the form:
public static ResultFromFrmMain Execute() {
using (var f = new frmMain()) {
var result = new ResultFromFrmMain();
result.Result = f.ShowDialog();
if (result.Result == DialogResult.OK) {
// fill other values
}
return result;
}
}
To call your form;
public void MyEventToCallForm() {
var result = frmMain.Execute();
if (result.Result == DialogResult.OK) {
myTextBox.Text = result.Field1; // or something like that
}
}
Have a look at nlohmann's JSON Repository on GitHub. I have found that it is the most convenient way to work with JSON.
It is designed to behave just like an STL container, which makes its usage very intuitive.
I am not 100% sure where all of the other suggestions are trying to go, but the issue is basically related to the extension that you have on the file. If you save the file as a Excel 97/2003 workbook it will not allow you to see all million rows. Create a new sheet and save it as a workbook and you will see all million. Note: the extension will be .xlsx
Many answers here describe dangerous methods where they instantiate a file input stream but do not get a reference to the input stream in order to close the stream later. This results in dangling input streams and memory leaks. The correct way of loading the properties should be similar to following:
Properties prop = new Properties();
try(InputStream fis = new FileInputStream("myProp.properties")) {
prop.load(fis);
}
catch(Exception e) {
System.out.println("Unable to find the specified properties file");
e.printStackTrace();
return;
}
Note the instantiating of the file input stream in try-with-resources
block. Since a FileInputStream
is autocloseable, it will be automatically closed after the try-with-resources
block is exited. If you want to use a simple try
block, you must explicitly close it using fis.close();
in the finally
block.
Neither of the answers resolved the issue for me. Even after I had installed a new version of Tortoise SVN + Ccleaner.
Seems that there is a folder in AppData\Roaming\Subversion
that contains all configuration of Tortoise SVN. You need to delete it all and restart Tortoise SVN.
Hope this helps someone as the ultimate solution.
I just want to add to Stephen's answer if you want to sort the array from high to low, another way other than in the comments above is just to add this to the line:
reverse = True
and the result will be as follows:
data.sort(key=lambda tup: tup[1], reverse=True)
In the case of a vector and list, the main differences that stick out to me are the following:
vector
A vector stores its elements in contiguous memory. Therefore, random access is possible inside a vector which means that accessing an element of a vector is very fast because we can simply multiply the base address with the item index to access that element. In fact, it takes only O(1) or constant time for this purpose.
Since a vector basically wraps an array, every time you insert an element into the vector (dynamic array), it has to resize itself by finding a new contiguous block of memory to accommodate the new elements which is time-costly.
It does not consume extra memory to store any pointers to other elements within it.
list
A list stores its elements in non-contiguous memory. Therefore, random access is not possible inside a list which means that to access its elements we have to use the pointers and traverse the list which is slower relative to vector. This takes O(n) or linear time which is slower than O(1).
Since a list uses non-contiguous memory, the time taken to insert an element inside a list is a lot more efficient than in the case of its vector counterpart because reallocation of memory is avoided.
It consumes extra memory to store pointers to the element before and after a particular element.
So, keeping these differences in mind, we usually consider memory, frequent random access and insertion to decide the winner of vector vs list in a given scenario.
to refresh the form you need to type - me.refresh in the button event on click
Forever takes command line options for output:
-l LOGFILE Logs the forever output to LOGFILE
-o OUTFILE Logs stdout from child script to OUTFILE
-e ERRFILE Logs stderr from child script to ERRFILE
For example:
forever start -o out.log -e err.log my-script.js
See here for more info
In your codethis
refers to the select element not to the selected option
to refer the selected option you can do this -
$(this).find('option:selected').attr("name");
Try this, perhaps it works ;)
.factory('authInterceptor', function($location, $q, $window) {
return {
request: function(config) {
config.headers = config.headers || {};
config.headers.Authorization = 'xxxx-xxxx';
return config;
}
};
})
.config(function($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
})
And make sure your back end works too, try this. I'm using RESTful CodeIgniter.
class App extends REST_Controller {
var $authorization = null;
public function __construct()
{
parent::__construct();
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
if ( "OPTIONS" === $_SERVER['REQUEST_METHOD'] ) {
die();
}
if(!$this->input->get_request_header('Authorization')){
$this->response(null, 400);
}
$this->authorization = $this->input->get_request_header('Authorization');
}
}
If you have a lot of variables in your Rdata
file and don't want them to clutter your global environment, create a new environment and load all of the data to this new environment.
load(file.path("C:/Users/isfar.RData"), isfar_env <- new.env() )
# Access individual variables in the RData file using '$' operator
isfar_env$var_name
# List all of the variable names in RData:
ls(isfar_env)
If you checkout
a commit sha directly, it puts you into a "detached head" state, which basically just means that the current sha that your working copy has checked out, doesn't have a branch pointing at it.
If you haven't made any commits yet, you can leave detached head state by simply checking out whichever branch you were on before checking out the commit sha:
git checkout <branch>
If you did make commits while you were in the detached head state, you can save your work by simply attaching a branch before or while you leave detached head state:
# Checkout a new branch at current detached head state:
git checkout -b newBranch
You can read more about detached head state at the official Linux Kernel Git docs for checkout.
The other thing you can do is use HSTS by returning the "Strict-Transport-Security" header to the browser. The browser has to support this (and at present, it's primarily Chrome and Firefox that do), but it means that once set, the browser won't make requests to the site over HTTP and will instead translate them to HTTPS requests before issuing them. Try this in combination with a redirect from HTTP:
protected void Application_BeginRequest(Object sender, EventArgs e)
{
switch (Request.Url.Scheme)
{
case "https":
Response.AddHeader("Strict-Transport-Security", "max-age=300");
break;
case "http":
var path = "https://" + Request.Url.Host + Request.Url.PathAndQuery;
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location", path);
break;
}
}
Browsers that aren't HSTS aware will just ignore the header but will still get caught by the switch statement and sent over to HTTPS.
The right answer (using Python 2.7 and later, since check_output()
was introduced then) is:
py2output = subprocess.check_output(['python','py2.py','-i', 'test.txt'])
To demonstrate, here are my two programs:
py2.py:
import sys
print sys.argv
py3.py:
import subprocess
py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'])
print('py2 said:', py2output)
Running it:
$ python3 py3.py
py2 said: b"['py2.py', '-i', 'test.txt']\n"
Here's what's wrong with each of your versions:
py2output = subprocess.check_output([str('python py2.py '),'-i', 'test.txt'])
First, str('python py2.py')
is exactly the same thing as 'python py2.py'
—you're taking a str
, and calling str
to convert it to an str
. This makes the code harder to read, longer, and even slower, without adding any benefit.
More seriously, python py2.py
can't be a single argument, unless you're actually trying to run a program named, say, /usr/bin/python\ py2.py
. Which you're not; you're trying to run, say, /usr/bin/python
with first argument py2.py
. So, you need to make them separate elements in the list.
Your second version fixes that, but you're missing the '
before test.txt'
. This should give you a SyntaxError
, probably saying EOL while scanning string literal
.
Meanwhile, I'm not sure how you found documentation but couldn't find any examples with arguments. The very first example is:
>>> subprocess.check_output(["echo", "Hello World!"])
b'Hello World!\n'
That calls the "echo"
command with an additional argument, "Hello World!"
.
Also:
-i is a positional argument for argparse, test.txt is what the -i is
I'm pretty sure -i
is not a positional argument, but an optional argument. Otherwise, the second half of the sentence makes no sense.
In drawable I use this xml code to define the border and background:
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="4dp" android:color="#D8FDFB" />
<padding android:left="7dp" android:top="7dp"
android:right="7dp" android:bottom="7dp" />
<corners android:radius="4dp" />
<solid android:color="#f0600000"/>
</shape>
execute the command
declare @sql varchar (100)
set @sql ='select * from #td1'
if (@IsMonday+@IsTuesday !='')
begin
set @sql= @sql+' where PickupDay in ('''+@IsMonday+''','''+@IsTuesday+''' )'
end
exec( @sql)
Adding a bit to mitigate the confusion here. Even though Darren Davies' (accepted) answer is more straight forward, I think Andrei's answer is a better approach for MVC applications.
The answer from Andrei means that you can use HttpContext
just as you would use System.Web.HttpContext.Current
. For example, if you want to do this:
System.Web.HttpContext.Current.User.Identity.Name
you should instead do this:
HttpContext.User.Identity.Name
Both achieve the same result, but (again) in terms of MVC, the latter is more recommended.
Another good and also straight forward information regarding this matter can be found here: Difference between HttpContext.Current and Controller.Context in MVC ASP.NET.
This seems to be a recent regression or some strange behavior in typescript. If you have the code:
const result = []
Usually it would be treated as if you wrote:
const result:any[] = []
however, if you have both noImplicitAny
FALSE, AND strictNullChecks
TRUE in your tsconfig, it is treated as:
const result:never[] = []
This behavior defies all logic, IMHO. Turning on null checks changes the entry types of an array?? And then turning on noImplicitAny
actually restores the use of any
without any warnings??
When you truly have an array of any
, you shouldn't need to indicate it with extra code.
Datatable JS plugin is also one good alternate to accomedate search feature for html table
var table = $('#example').DataTable();
// #myInput is a <input type="text"> element
$('#myInput').on( 'keyup', function () {
table.search( this.value ).draw();
} );
https://datatables.net/examples/basic_init/zero_configuration.html
If you're still having issues with the simple approach, creating an empty bucket then Redirect all requests to another host name
under Static web hosting in properties via the console. Ensure that you have set 2 A records in route53, one for final-destination.com
and one for redirect-to.final-destination.com
. The settings for each of these will be identical, but the name will be different so it matches the names that you set for your buckets / URLs.
Here is how I have achieved this:
TextFormCell.h
#import <UIKit/UIKit.h>
#define CellTextFieldWidth 90.0
#define MarginBetweenControls 20.0
@interface TextFormCell : UITableViewCell {
UITextField *textField;
}
@property (nonatomic, retain) UITextField *textField;
@end
TextFormCell.m
#import "TextFormCell.h"
@implementation TextFormCell
@synthesize textField;
- (id)initWithReuseIdentifier:(NSString *)reuseIdentifier {
if (self = [super initWithReuseIdentifier:reuseIdentifier]) {
// Adding the text field
textField = [[UITextField alloc] initWithFrame:CGRectZero];
textField.clearsOnBeginEditing = NO;
textField.textAlignment = UITextAlignmentRight;
textField.returnKeyType = UIReturnKeyDone;
[self.contentView addSubview:textField];
}
return self;
}
- (void)dealloc {
[textField release];
[super dealloc];
}
#pragma mark -
#pragma mark Laying out subviews
- (void)layoutSubviews {
CGRect rect = CGRectMake(self.contentView.bounds.size.width - 5.0,
12.0,
-CellTextFieldWidth,
25.0);
[textField setFrame:rect];
CGRect rect2 = CGRectMake(MarginBetweenControls,
12.0,
self.contentView.bounds.size.width - CellTextFieldWidth - MarginBetweenControls,
25.0);
UILabel *theTextLabel = (UILabel *)[self textLabel];
[theTextLabel setFrame:rect2];
}
It may seems a bit verbose, but it works!
Don't forget to set the delegate!
You will have to write a wrapper for C in C++ if you want to do this. C++ is backwards compatible, but C is not forwards compatible.
If you look for POSIX compliant solution:
cd DirsRoot && find . -type f -print -o -name . -o -prune
-maxdepth is not POSIX compliant option.
You can collect or set the content of a selected tag.
As a Pseudo idea, its similar to having many boxes within a room and imply the idea 'everything within that box'
You could try the subplot_tool()
plt.subplot_tool()
I can highly recommend Squirrel SQL.
Also see this similar question:
I guess what you need is np.set_printoptions(suppress=True)
, for details see here:
http://pythonquirks.blogspot.fr/2009/10/controlling-printing-in-numpy.html
For SciPy.org numpy documentation, which includes all function parameters (suppress isn't detailed in the above link), see here: https://docs.scipy.org/doc/numpy/reference/generated/numpy.set_printoptions.html
Turns out the Samsung file explorer uses a custom action. This is why I could see the Samsung file explorer when looking for a file from the samsung apps, but not from mine.
The action is "com.sec.android.app.myfiles.PICK_DATA"
I created a custom Activity Picker which displays activities filtering both intents.
You could use a shortcut library to handle the browser specific stuff.
shortcut.add("Ctrl+S",function() {
alert("Hi there!");
});
The .css()
method makes it super simple to find and set CSS properties and combined with other methods like .animate(), you can make some cool effects on your site.
In its simplest form, the .css()
method can set a single CSS property for a particular set of matched elements. You just pass the property and value as strings and the element’s CSS properties are changed.
$('.example').css('background-color', 'red');
This would set the ‘background-color’ property to ‘red’ for any element that had the class of ‘example’.
But you aren’t limited to just changing one property at a time. Sure, you could add a bunch of identical jQuery objects, each changing just one property at a time, but this is making several, unnecessary calls to the DOM and is a lot of repeated code.
Instead, you can pass the .css()
method a Javascript object that contains the properties and values as key/value pairs. This way, each property will then be set on the jQuery object all at once.
$('.example').css({
'background-color': 'red',
'border' : '1px solid red',
'color' : 'white',
'font-size': '32px',
'text-align' : 'center',
'display' : 'inline-block'
});
This will change all of these CSS properties on the ‘.example’ elements.
If you use a Custom format, rather than one of the pre-selected Date formats, the export to CSV will keep your selected format. Otherwise it defaults back to the US format
Scraping it to JSON with Node.js would be fun :)
https://github.com/f1lt3r/bitcoin-scraper
[
[
1419033600, // Timestamp (1 for each minute of entire history)
318.58, // Open
318.58, // High
318.58, // Low
318.58, // Close
0.01719605, // Volume (BTC)
5.478317609, // Volume (Currency)
318.58 // Weighted Price (USD)
]
]
If the value contains non-numeric characters, you can convert the value to an integer as follows:
SELECT CASE WHEN <column>~E'^\\d+$' THEN CAST (<column> AS INTEGER) ELSE 0 END FROM table;
The CASE operator checks the < column>, if it matches the integer pattern, it converts the rate into an integer, otherwise it returns 0
As the error says your router link should match the existing routes configured
It should be just routerLink="/about
"
Just to add some info to the other answers - using &
is a good way if you need an isolated scope.
The main downside of marko's solution is that it forces you to create an isolated scope on an element, but you can only have one of those on an element (otherwise you'll run into an angular error: Multiple directives [directive1, directive2] asking for isolated scope)
This means you :
Since the original question uses a directive with restrict:'A'
both situations might arise quite often in bigger applications, and using an isolated scope here is not a good practice and also unnecessary. In fact rekna had a good intuition in this case, and almost had it working, the only thing he was doing wrong was calling the $parsed function wrong (see what it returns here: https://docs.angularjs.org/api/ng/service/$parse ).
<div my-method='theMethodToBeCalled(id)'></div>
and the code
app.directive("myMethod",function($parse) {
restrict:'A',
link:function(scope,element,attrs) {
// here you can parse any attribute (so this could as well be,
// myDirectiveCallback or multiple ones if you need them )
var expressionHandler = $parse(attrs.myMethod);
$(element).on('theEvent',function( e, rowid ) {
calculatedId = // some function called to determine id based on rowid
// HERE: call the parsed function correctly (with scope AND params object)
expressionHandler(scope, {id:calculatedId});
}
}
}
app.controller("myController",function($scope) {
$scope.theMethodToBeCalled = function(id) { alert(id); };
}
I have faced same error on Amazon EC2 instance. The issue got fixed after restarting the instance.
from pyspark.sql.types import IntegerType
data_df = data_df.withColumn("Plays", data_df["Plays"].cast(IntegerType()))
data_df = data_df.withColumn("drafts", data_df["drafts"].cast(IntegerType()))
You can run loop for each column but this is the simplest way to convert string column into integer.
Okay you must try this guys it works for me:
Adding to the answer from Ignacio Vazquez-Abrams. This will allow for the + sign to precede the integer, and it will allow any number of zeros as decimal points. For example, this will allow +45.00000000 to be considered an integer.
However, $1 must be formatted to contain a decimal point. 45 is not considered an integer here, but 45.0 is.
if [[ $1 =~ ^-?[0-9]+.?[0]+$ ]]; then
echo "yes, this is an integer"
elif [[ $1 =~ ^\+?[0-9]+.?[0]+$ ]]; then
echo "yes, this is an integer"
else
echo "no, this is not an integer"
fi
My alternative solution with subtraction :)
void convert( unsigned int addr )
{
unsigned int num[OCTET],
next_addr[OCTET];
int bits = 8;
unsigned int shift_bits;
int i;
next_addr[0] = addr;
shift_bits -= bits;
num[0] = next_addr[0] >> shift_bits;
for ( i = 0; i < OCTET-1; i ++ )
{
next_addr[i + 1] = next_addr[i] - ( num[i] << shift_bits ); // next subaddr
shift_bits -= bits; // next shift
num[i + 1] = next_addr[i + 1] >> shift_bits; // octet
}
printf( "%d.%d.%d.%d\n", num[0], num[1], num[2], num[3] );
}
I created Lodash to provide more consistent cross-environment iteration support for arrays, strings, objects, and arguments
objects1. It has since become a superset of Underscore.js, providing more consistent API behavior, more features (like AMD support, deep clone, and deep merge), more thorough documentation and unit tests (tests which run in Node.js, RingoJS, Rhino, Narwhal, PhantomJS, and browsers), better overall performance and optimizations for large arrays/object iteration, and more flexibility with custom builds and template pre-compilation utilities.
Because Lodash is updated more frequently than Underscore.js, a lodash underscore
build is provided to ensure compatibility with the latest stable version of Underscore.js.
At one point I was even given push access to Underscore.js, in part because Lodash is responsible for raising more than 30 issues; landing bug fixes, new features, and performance gains in Underscore.js v1.4.x+.
In addition, there are at least three Backbone.js boilerplates that include Lodash by default and Lodash is now mentioned in Backbone.js’s official documentation.
Check out Kit Cambridge's post, Say "Hello" to Lo-Dash, for a deeper breakdown on the differences between Lodash and Underscore.js.
Footnotes:
arguments
objects. In newer browsers, Underscore.js methods ignore holes in arrays, "Objects" methods iterate arguments
objects, strings are treated as array-like, and methods correctly iterate functions (ignoring their "prototype" property) and objects (iterating shadowed properties like "toString" and "valueOf"), while in older browsers they will not. Also, Underscore.js methods, like _.clone
, preserve holes in arrays, while others like _.flatten
don't.For me save_queries
option was turned off so,
$this->db->save_queries = TRUE; //Turn ON save_queries for temporary use.
$str = $this->db->last_query();
echo $str;
Ref: Can't get result from $this->db->last_query(); codeigniter
Since it sounds like your JAVA_HOME variable is not set correctly, follow the instructions for setting that.
Setting JAVA_HOME environment variable on MAC OSX 10.9
I would imagine once you set this, it will stop complaining.
You can make this lot faster by overriding ViewGroup onLayout method. This is my universal solution:
package your.app.package;
import android.content.Context;
import android.view.ViewGroup;
public class GridLayout extends ViewGroup {
public GridLayout(Context context) {
super(context);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int columns = 2;//edit this if you need different grid
final int rows = 2;
int children = getChildCount();
if (children != columns * rows)
throw new IllegalStateException("GridLayout must have " + columns * rows + " children");
int width = getWidth();
int height = getHeight();
int viewWidth = width / columns;
int viewHeight = height / rows;
int rowIndex = 0;
int columnIndex = 0;
for (int i = 0; i < children; i++) {
getChildAt(i).layout(viewWidth * columnIndex, viewHeight * rowIndex, viewWidth * columnIndex + viewWidth, viewHeight * rowIndex + viewHeight);
columnIndex++;
if (columnIndex == columns) {
columnIndex = 0;
rowIndex++;
}
}
}
}
EDIT: Don't forget match_parent for children!
android:layout_width="match_parent"
android:layout_height="match_parent"
LIKE does matching like wildcards char [*, ?] at the shell
LIKE '%suffix' - give me everything that ends with suffix. You couldn't do that with =
Depends on the case actually.
you can add this two lines:
HTMLCollection.prototype.forEach = Array.prototype.forEach;
NodeList.prototype.forEach = Array.prototype.forEach;
HTMLCollection is return by getElementsByClassName and getElementsByTagName
NodeList is return by querySelectorAll
Like this you can do a forEach:
var selections = document.getElementsByClassName('myClass');
/* alternative :
var selections = document.querySelectorAll('.myClass');
*/
selections.forEach(function(element, i){
//do your stuffs
});
Morgan :- Morgan is a middleware which will help us to identify the clients who are accessing our application. Basically a logger.
To Use Morgan, We need to follow below steps :-
npm install --save morgan
This will add morgan to json.package file
var morgan = require('morgan');
3> // create a write stream (in append mode)
var accessLogStream = fs.createWriteStream(
path.join(__dirname, 'access.log'), {flags: 'a'}
);
// setup the logger
app.use(morgan('combined', {stream: accessLogStream}));
Note: Make sure you do not plumb above blindly make sure you have every conditions where you need .
Above will automatically create a access.log file to your root once user will access your app.
Thanks for the earlier reply.
I figured out the solutions using selenium 2.0 classes.
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class WebTableExample
{
public static void main(String[] args)
{
WebDriver driver = new InternetExplorerDriver();
driver.get("http://localhost/test/test.html");
WebElement table_element = driver.findElement(By.id("testTable"));
List<WebElement> tr_collection=table_element.findElements(By.xpath("id('testTable')/tbody/tr"));
System.out.println("NUMBER OF ROWS IN THIS TABLE = "+tr_collection.size());
int row_num,col_num;
row_num=1;
for(WebElement trElement : tr_collection)
{
List<WebElement> td_collection=trElement.findElements(By.xpath("td"));
System.out.println("NUMBER OF COLUMNS="+td_collection.size());
col_num=1;
for(WebElement tdElement : td_collection)
{
System.out.println("row # "+row_num+", col # "+col_num+ "text="+tdElement.getText());
col_num++;
}
row_num++;
}
}
}
One possible cause of this linker error can also be inline
functions that are declared but not defined in a header file that is then included somewhere else. Inline functions have to be defined in every translation unit they are used in.
Assuming you're talking about round the value for printing, then Andrew Coleson and AraK's answer are correct:
printf("%.2f", 37.777779);
But note that if you're aiming to round the number to exactly 37.78 for internal use (eg to compare against another value), then this isn't a good idea, due to the way floating point numbers work: you usually don't want to do equality comparisons for floating point, instead use a target value +/- a sigma value. Or encode the number as a string with a known precision, and compare that.
See the link in Greg Hewgill's answer to a related question, which also covers why you shouldn't use floating point for financial calculations.
This is the Simple method, Use ParseExact
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime result;
String dateString = "Sun 08 Jun 2013 8:30 AM -06:00";
String format = "ddd dd MMM yyyy h:mm tt zzz";
result = DateTime.ParseExact(dateString, format, provider);
This should work for you.
Here's the calling order:
app.config()
app.run()
app.controller()
Here's a simple demo where you can watch each one executing (and experiment if you'd like).
From Angular's module docs:
Run blocks - get executed after the injector is created and are used to kickstart the application. Only instances and constants can be injected into run blocks. This is to prevent further system configuration during application run time.
Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the services have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests.
One situation where run blocks are used is during authentications.
login to your server via
ssh -X root@yourIP
edit /etc/ssh/sshd_config file, and add this line to it.
X11UseLocalhost no
Restart sshd. for CentOS (check your distribution)
/sbin/service sshd restart
check your DISPLAY
echo $DISPLAY
you should see this
yourIP:10.0
Enjoy
firefox
$count = 0;
$output ='';
$ischeckedvalueArray = array();
for ($i=0; $i < sizeof($array); $i++) {
$eachArrayValue = $array[$i];
if(! in_array($eachArrayValue, $ischeckedvalueArray)) {
for( $j=$i; $j < sizeof($array); $j++) {
if ($array[$j] === $eachArrayValue) {
$count++;
}
}
$ischeckedvalueArray[] = $eachArrayValue;
$output .= $eachArrayValue. " Repated ". $count."<br/>";
$count = 0;
}
}
echo $output;
Maybe this will help someone.
I've deleted my models.py
and expected makemigrations
to create DeleteModel
statements.
Remember to delete *.pyc
files!
If you want to loop over a range and do something for every number that is NOT a perfect square, you could do something like this:
def non_squares(upper):
next_square = 0
diff = 1
for i in range(0, upper):
if i == next_square:
next_square += diff
diff += 2
continue
yield i
If you want to do something for every number that IS a perfect square, the generator is even easier:
(n * n for n in range(upper))
A short way to LabelEncoder()
multiple columns with a dict()
:
from sklearn.preprocessing import LabelEncoder
le_dict = {col: LabelEncoder() for col in columns }
for col in columns:
le_dict[col].fit_transform(df[col])
and you can use this le_dict
to labelEncode any other column:
le_dict[col].transform(df_another[col])
I had this same problem and stumbled upon the following simple solution. Just add a bit of padding to the image and it resizes itself to fit within the div.
<div class="col-sm-3">
<img src="xxx.png" class="img-responsive" style="padding-top: 5px">
</div>
Just remove /Observable
from 'rxjs/Observable';
If you then get Cannot find module 'rxjs-compat/Observable'
just put below line to thr terminal and press enter.
npm install --save rxjs-compat
Apache is an HTTP web server which serve as HTTP.
Apache Tomcat is a java servlet container. It features same as web server but is customized to execute java servlet and JSP pages.
n=int(input())
for i in range(n):
n=input()
n=int(n)
arr1=list(map(int,input().split()))
the for loop shall run 'n' number of times . the second 'n' is the length of the array. the last statement maps the integers to a list and takes input in space separated form . you can also return the array at the end of for loop.
Indeed you cannot save changes inside a foreach
loop in C# using Entity Framework.
context.SaveChanges()
method acts like a commit on a regular database system (RDMS).
Just make all changes (which Entity Framework will cache) and then save all of them at once calling SaveChanges()
after the loop (outside of it), like a database commit command.
This works if you can save all changes at once.
Using scriptlets in JSPs is not a good practice.
Instead, you can use:
Please refer to:
Use the imp module, or the more direct __import__()
function.
While all of the above links have merit, and have benefited me greatly in the past, as a linguist "exposed" to various Lucene search engines for the last 15 years, I have to say that elastic-search development is very fast in Python. That being said, some of the code felt non-intuitive to me. So, I reached out to one component of the ELK stack, Kibana, from an open source perspective, and found that I could generate the somewhat cryptic code of elasticsearch very easily in Kibana. Also, I could pull Chrome Sense es queries into Kibana as well. If you use Kibana to evaluate es, it will further speed up your evaluation. What took hours to run on other platforms was up and running in JSON in Sense on top of elasticsearch (RESTful interface) in a few minutes at worst (largest data sets); in seconds at best. The documentation for elasticsearch, while 700+ pages, didn't answer questions I had that normally would be resolved in SOLR or other Lucene documentation, which obviously took more time to analyze. Also, you may want to take a look at Aggregates in elastic-search, which have taken Faceting to a new level.
Bigger picture: if you're doing data science, text analytics, or computational linguistics, elasticsearch has some ranking algorithms that seem to innovate well in the information retrieval area. If you're using any TF/IDF algorithms, Text Frequency/Inverse Document Frequency, elasticsearch extends this 1960's algorithm to a new level, even using BM25, Best Match 25, and other Relevancy Ranking algorithms. So, if you are scoring or ranking words, phrases or sentences, elasticsearch does this scoring on the fly, without the large overhead of other data analytics approaches that take hours--another elasticsearch time savings. With es, combining some of the strengths of bucketing from aggregations with the real-time JSON data relevancy scoring and ranking, you could find a winning combination, depending on either your agile (stories) or architectural(use cases) approach.
Note: did see a similar discussion on aggregations above, but not on aggregations and relevancy scoring--my apology for any overlap. Disclosure: I don't work for elastic and won't be able to benefit in the near future from their excellent work due to a different architecural path, unless I do some charity work with elasticsearch, which wouldn't be a bad idea
You can download a library from http://json.org (Json-lib or org.json) and use it to parse/generate the JSON
The simplest technique is to use NSString *uuid = [[NSProcessInfo processInfo] globallyUniqueString]
. See the NSProcessInfo class reference.
function getSelectedText(elementId) {
var elt = document.getElementById(elementId);
if (elt.selectedIndex == -1)
return null;
return elt.options[elt.selectedIndex].text;
}
var text = getSelectedText('test');
I used this to update a excel 12 xlsx file
System.Data.OleDb.OleDbConnection MyConnection;
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.ACE.OLEDB.12.0;Data Source='D:\\Programming\\Spreadsheet-Current.xlsx';Extended Properties='Excel 12.0;HDR=YES;';");
MyConnection.Open();
myCommand.Connection = MyConnection;
string sql = "Update [ArticlesV2$] set [ID]='Test' where [ActualPageId]=114";//
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
MyConnection.Close();
For the Java programming language, there is no difference between the two. Java has two types of comments: traditional comments (/* ... */
) and end-of-line comments (// ...
). See the Java Language Specification. So, for the Java programming language, both /* ... */
and /** ... */
are instances of traditional comments, and they are both treated exactly the same by the Java compiler, i.e., they are ignored (or more correctly: they are treated as white space).
However, as a Java programmer, you do not only use a Java compiler. You use a an entire tool chain, which includes e.g. the compiler, an IDE, a build system, etc. And some of these tools interpret things differently than the Java compiler. In particular, /** ... */
comments are interpreted by the Javadoc tool, which is included in the Java platform and generates documentation. The Javadoc tool will scan the Java source file and interpret the parts between /** ... */
as documentation.
This is similar to tags like FIXME
and TODO
: if you include a comment like // TODO: fix this
or // FIXME: do that
, most IDEs will highlight such comments so that you don't forget about them. But for Java, they are just comments.
If you don't want to assign identifier to the hidden field; you can use name or class with selector like:
$('input[name=hiddenfieldname]').val();
or with assigned class:
$('input.hiddenfieldclass').val();
In String type we have several method valueOf
static String valueOf(boolean b)
static String valueOf(char c)
static String valueOf(char[] data)
static String valueOf(char[] data, int offset, int count)
static String valueOf(double d)
static String valueOf(float f)
static String valueOf(int i)
static String valueOf(long l)
static String valueOf(Object obj)
As we can see those method are capable to resolve all kind of numbers
every implementation of specific method like you have presented: So for integers we have
Integer.toString(int i)
for double
Double.toString(double d)
and so on
In my opinion this is not some historical thing, but it is more useful for a developer to use the method valueOf
from the String class than from the proper type, as it leads to fewer changes for us to make.
Sample 1:
public String doStuff(int num) {
// Do something with num...
return String.valueOf(num);
}
Sample2:
public String doStuff(int num) {
// Do something with num...
return Integer.toString(num);
}
As we see in sample 2 we have to do two changes, in contrary to sample one.
In my conclusion, using the valueOf
method from String class is more flexible and that's why it is available there.
It looks like you don't have any records that match your query, so you'd want to return an empty array (or null or something) if the number of rows == 0.
Compact solution (provided you don't need other environment variables):
call('sqsub -np {} /homedir/anotherdir/executable'.format(var1).split(),
env=dict(LD_LIBRARY_PATH=my_path))
Using the env command line tool:
call('env LD_LIBRARY_PATH=my_path sqsub -np {} /homedir/anotherdir/executable'.format(var1).split())
There's also a C standard built-in library to get command line arguments: getopt
You can check it on Wikipedia or in Argument-parsing helpers for C/Unix.
In jQuery you can trigger a click like this:
$('#foo').trigger('click');
More here:
http://api.jquery.com/trigger/
If you want to do the same using prototype, it looks like this:
$('foo').simulate('click');
I was having an issue with an SVG that was disappearing on Chrome for Android when the orientation was changed in certain circumstances. The below code doesn't reproduce it, but is the setup we had.
body {_x000D_
font-family: tahoma, sans-serif;_x000D_
font-size: 12px;_x000D_
margin: 10px;_x000D_
}_x000D_
article {_x000D_
display: flex;_x000D_
}_x000D_
aside {_x000D_
flex: 0 1 10px;_x000D_
margin-right: 10px;_x000D_
min-width: 10px;_x000D_
position: relative;_x000D_
}_x000D_
svg {_x000D_
bottom: 0;_x000D_
left: 0;_x000D_
position: absolute;_x000D_
right: 0;_x000D_
top: 0;_x000D_
}_x000D_
.backgroundStop1 {_x000D_
stop-color: #5bb79e;_x000D_
}_x000D_
.backgroundStop2 {_x000D_
stop-color: #ddcb3f;_x000D_
}_x000D_
.backgroundStop3 {_x000D_
stop-color: #cf6b19;_x000D_
}
_x000D_
<article>_x000D_
<aside>_x000D_
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" height="100%" width="100%">_x000D_
<defs>_x000D_
<linearGradient id="IndicatorColourPattern" x1="0" x2="0" y1="0" y2="1">_x000D_
<stop class="backgroundStop1" offset="0%"></stop>_x000D_
<stop class="backgroundStop2" offset="50%"></stop>_x000D_
<stop class="backgroundStop3" offset="100%"></stop>_x000D_
</linearGradient>_x000D_
</defs>_x000D_
<rect x="0" y="0" rx="5" ry="5" width="100%" height="100%" fill="url(#IndicatorColourPattern)"></rect>_x000D_
</svg>_x000D_
</aside>_x000D_
<section>_x000D_
<p>Donec et eros nibh. Nullam porta, elit ut sagittis pulvinar, lacus augue lobortis mauris, sed sollicitudin elit orci non massa. Proin condimentum in nibh sed vestibulum. Donec accumsan fringilla est, porttitor vestibulum dolor ornare id. Sed elementum_x000D_
urna sollicitudin commodo ultricies. Curabitur tristique orci et ligula interdum, eu condimentum metus eleifend. Nam libero augue, pharetra at maximus in, pellentesque imperdiet orci.</p>_x000D_
<p>Fusce commodo ullamcorper ullamcorper. Etiam eget pellentesque quam, id sodales erat. Vestibulum risus magna, efficitur sed nisl et, rutrum consectetur odio. Sed at lorem non ligula consequat tempus vel nec risus.</p>_x000D_
</section>_x000D_
</article>
_x000D_
Day and half later after poking and prodding and not happy with the hacky solutions offered here, I discovered that the issue was caused by the fact it seemed to keep the element in memory while drawing a new one. The solution was to make the ID of the linearGradient on the SVG unique, even though it was only ever used once per page.
This can be achieved many different ways, but for our angular app we used lodash uniqueId function to add a variable to the scope:
Angular Directive (JS):
scope.indicatorColourPatternId = _.uniqueId('IndicatorColourPattern');
HTML Updates:
Line 5: <linearGradient ng-attr-id="{{indicatorColourPatternId}}" x1="0" x2="0" y1="0" y2="1">
Line 11: <rect x="0" y="0" rx="5" ry="5" width="100%" height="100%" ng-attr-fill="url(#{{indicatorColourPatternId}})"/>
I hope this answer saves someone else a days worth of face-smashing their keyboard.
Double stars (**
) are exponentiation. So "2 times 2" and "2 to the power 2" are the same. Change the numbers and you'll see a difference.
i've been with this issue using elementary OS loki. For like one day and i solved it restarting the adb using this command:
./adb kill-server
and
./adb start-server
You need to be in the Sdk folder >Platform Tools
Now, restart your phone this will restart all the process in your phone.
And that's how i fixed it.
const { promisify } = require("util")
const directory = path.join(__dirname, "/tmpl")
const pathnames = promisify(fs.readdir)(directory)
try {
async function emitData(directory) {
let filenames = await pathnames
var ob = {}
const data = filenames.map(async function(filename, i) {
if (filename.includes(".")) {
var storedFile = promisify(fs.readFile)(directory + `\\${filename}`, {
encoding: "utf8",
})
ob[filename.replace(".js", "")] = await storedFile
socket.emit("init", { data: ob })
}
return ob
})
}
emitData(directory)
} catch (err) {
console.log(err)
}
Who wants to try with generators?
As per PEP-20 by Tim Peters, "Explicit is better than implicit" and "Readability counts". If all you need from the os
module is under os.path
, import os.path
would be more explicit and let others know what you really care about.
Likewise, PEP-20 also says "Simple is better than complex", so if you also need stuff that resides under the more-general os
umbrella, import os
would be preferred.
Never use =='NA' to test for missing values. Use is.na()
instead. This should do it:
new_DF <- DF[rowSums(is.na(DF)) > 0,]
or in case you want to check a particular column, you can also use
new_DF <- DF[is.na(DF$Var),]
In case you have NA character values, first run
Df[Df=='NA'] <- NA
to replace them with missing values.
If you submit the form via Javascript (i.e. formElement.submit()
or anything equivalent), then none of the submit buttons are considered successful and none of their values are included in the submitted data. (Note that if you submit the form by using submitElement.click()
then the submit that you had a reference to is considered active; this doesn't really fall under the remit of your question since here the submit button is unambiguous but I thought I'd include it for people who read the first part and wonder how to make a submit button successful via JS form submission. Of course, the form's onsubmit handlers will still fire this way whereas they wouldn't via form.submit()
so that's another kettle of fish...)
If the form is submitted by hitting Enter while in a non-textarea field, then it's actually down to the user agent to decide what it wants here. The specs don't say anything about submitting a form using the enter key while in a text entry field (if you tab to a button and activate it using space or whatever, then there's no problem as that specific submit button is unambiguously used). All it says is that a form must be submitted when a submit button is activated, it's not even a requirement that hitting enter in e.g. a text input will submit the form.
I believe that Internet Explorer chooses the submit button that appears first in the source; I have a feeling that Firefox and Opera choose the button with the lowest tabindex, falling back to the first defined if nothing else is defined. There's also some complications regarding whether the submits have a non-default value attribute IIRC.
The point to take away is that there is no defined standard for what happens here and it's entirely at the whim of the browser - so as far as possible in whatever you're doing, try to avoid relying on any particular behaviour. If you really must know, you can probably find out the behaviour of the various browser versions but when I investigated this a while back there were some quite convoluted conditions (which of course are subject to change with new browser versions) and I'd advise you to avoid it if possible!
For datetimepickers use this this work for me
$('#lastdate1').data({date: '2016-07-05'});
$('#lastdate1').datetimepicker('update');
$('#lastdate1').datetimepicker().children('input').val('2016-07-05');
Use 'this' keyword to access variable. This worked for me
var uemail = localStorage.getItem("useremail");
if (typeof this.uemail === "undefined")
{
alert('undefined');
}
else
{
alert('defined');
}
You would need to do something like this. I am typing this off the top of my head, so this may not be 100% correct.
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace); CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession); CGImageRef image = CGBitmapContextCreateImage(context); UIImage* myCroppedImg = [UIImage imageWithCGImage:image]; CGContextRelease(context);
Kotlin Style way to do this more simple (example):
isVisible = false
Complete example:
if (some_data_array.details == null){
holder.view.some_data_array.isVisible = false}
Removing the space between @ and taglib did the trick for me: <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
Revers CountDown timer with hours minutes and seconds
public void reverseTimer(int Seconds, final TextView tv) {
new CountDownTimer(Seconds * 1000 + 1000, 1000) {
public void onTick(long millisUntilFinished) {
int seconds = (int) (millisUntilFinished / 1000);
int hours = seconds / (60 * 60);
int tempMint = (seconds - (hours * 60 * 60));
int minutes = tempMint / 60;
seconds = tempMint - (minutes * 60);
tv.setText("TIME : " + String.format("%02d", hours)
+ ":" + String.format("%02d", minutes)
+ ":" + String.format("%02d", seconds));
}
public void onFinish() {
tv.setText("Completed");
}
}.start();
}
None of the above worked for me. My app was working fine in previous than Lollipop. But when I tested it on Lollipop the above error came up. It refused to install. I didn't have any previous versions installed so all the above solutions are invalid in my case. But thanks to this SO solution now it is running fine. Just like most developers I followed Google's misleading tutorial and I added the permissions by copy and paste like this:
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission android:name="com.google.android.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
This would work with older versions < Lollipop. So now I changed to:
<uses-permission android:name="com.mycompany.myappname.c2dm.permission.RECEIVE" />
<permission android:name="com.mycompany.myappname.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
when the given element is a object:
handleNewObj = e => {
const data = e[Object.keys(e)[0]];
this.setState({
anykeyofyourstate: {
...this.state.anykeyofyourstate,
[Object.keys(e)[0]]: data
}
});
};
hope it helps someone
You can use Contains()
for that. It will feel a little backwards when you're really trying to produce an IN
clause, but this should do it:
var userProfiles = _dataContext.UserProfile
.Where(t => idList.Contains(t.Id));
I'm also assuming that each UserProfile
record is going to have an int
Id
field. If that's not the case you'll have to adjust accordingly.
The first thing you need to do is to set the level of verification. Such levels is not so much:
Although the method setHostnameVerifier() is obsolete for new library apache, but for version in Android SDK is normal.
And so we take ALLOW_ALL_HOSTNAME_VERIFIER
and set it in the method factory SSLSocketFactory.setHostnameVerifier()
.
Next, You need set our factory for the protocol to https. To do this, simply call the SchemeRegistry.register()
method.
Then you need to create a DefaultHttpClient
with SingleClientConnManager
.
Also in the code below you can see that on default will also use our flag (ALLOW_ALL_HOSTNAME_VERIFIER
) by the method HttpsURLConnection.setDefaultHostnameVerifier()
Below code works for me:
HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
DefaultHttpClient client = new DefaultHttpClient();
SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
registry.register(new Scheme("https", socketFactory, 443));
SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());
// Set verifier
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
// Example send http request
final String url = "https://encrypted.google.com/";
HttpPost httpPost = new HttpPost(url);
HttpResponse response = httpClient.execute(httpPost);
Just create a button element with jQuery, and add the event handler when you create it :
var div = $('<div />', {'data-role' : 'fieldcontain'}),
btn = $('<input />', {
type : 'button',
value : 'Dynamic Button',
id : 'btn_a',
on : {
click: function() {
alert ( this.value );
}
}
});
div.append(btn).appendTo( $('#pg_menu_content').empty() );
You can access it by the class' private attributes:
cls_name = self.__class__.__name__
EDIT:
As said by Ned Batcheler
, this wouldn't work in the class body, but it would in a method.
Here is the plunker
New plunker with cleaner code & where both the query and search list items are case insensitive
Main idea is create a filter function to achieve this purpose.
From official doc
function: A predicate function can be used to write arbitrary filters. The function is called for each element of array. The final result is an array of those elements that the predicate returned true for.
<input ng-model="query">
<tr ng-repeat="smartphone in smartphones | filter: search ">
$scope.search = function(item) {
if (!$scope.query || (item.brand.toLowerCase().indexOf($scope.query) != -1) || (item.model.toLowerCase().indexOf($scope.query.toLowerCase()) != -1) ){
return true;
}
return false;
};
Update
Some people might have a concern on performance in real world, which is correct.
In real world, we probably would do this kinda filter from controller.
Here is the detail post showing how to do it.
in short, we add ng-change
to input for monitoring new search change
and then trigger filter function.
There are many options to consume a SOAP web service with Stub or Java classes created based on WSDL. But if anyone wants to do this without any Java class created, this article is very helpful. Code Snippet from the article:
public String someMethod() throws MalformedURLException, IOException {
//Code to make a webservice HTTP request
String responseString = "";
String outputString = "";
String wsURL = "<Endpoint of the webservice to be consumed>";
URL url = new URL(wsURL);
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection)connection;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
String xmlInput = "entire SOAP Request";
byte[] buffer = new byte[xmlInput.length()];
buffer = xmlInput.getBytes();
bout.write(buffer);
byte[] b = bout.toByteArray();
String SOAPAction = "<SOAP action of the webservice to be consumed>";
// Set the appropriate HTTP parameters.
httpConn.setRequestProperty("Content-Length",
String.valueOf(b.length));
httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
httpConn.setRequestProperty("SOAPAction", SOAPAction);
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
OutputStream out = httpConn.getOutputStream();
//Write the content of the request to the outputstream of the HTTP Connection.
out.write(b);
out.close();
//Ready with sending the request.
//Read the response.
InputStreamReader isr = null;
if (httpConn.getResponseCode() == 200) {
isr = new InputStreamReader(httpConn.getInputStream());
} else {
isr = new InputStreamReader(httpConn.getErrorStream());
}
BufferedReader in = new BufferedReader(isr);
//Write the SOAP message response to a String.
while ((responseString = in.readLine()) != null) {
outputString = outputString + responseString;
}
//Parse the String output to a org.w3c.dom.Document and be able to reach every node with the org.w3c.dom API.
Document document = parseXmlFile(outputString); // Write a separate method to parse the xml input.
NodeList nodeLst = document.getElementsByTagName("<TagName of the element to be retrieved>");
String elementValue = nodeLst.item(0).getTextContent();
System.out.println(elementValue);
//Write the SOAP message formatted to the console.
String formattedSOAPResponse = formatXML(outputString); // Write a separate method to format the XML input.
System.out.println(formattedSOAPResponse);
return elementValue;
}
For those who're looking for a similar kind of solution with file upload while consuming a SOAP API, please refer to this post: How to attach a file (pdf, jpg, etc) in a SOAP POST request?
There is a Win32 port of wget that works decently.
PowerShell's Invoke-WebRequest -Method Head
would work as well.
You can use:
overflow:hidden;
to hide the text outside the zone.
Note that it may cut the last letter (so a part of the last letter will still be displayed). A nicer way is to display an ellipsis at the end. You can do it by using text-overflow
:
overflow: hidden;
white-space: nowrap; /* Don't forget this one */
text-overflow: ellipsis;
What works for me is if ( !myobject )
You are experiencing this issue for two reasons.
When performing a join in JPQL you must ensure that an underlying association between the entities attempting to be joined exists. In your example, you are missing an association between the User and Area entities. In order to create this association we must add an Area field within the User class and establish the appropriate JPA Mapping. I have attached the source for User below. (Please note I moved the mappings to the fields)
User.java
@Entity
@Table(name="user")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="iduser")
private Long idUser;
@Column(name="user_name")
private String userName;
@OneToOne()
@JoinColumn(name="idarea")
private Area area;
public Long getIdUser() {
return idUser;
}
public void setIdUser(Long idUser) {
this.idUser = idUser;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Area getArea() {
return area;
}
public void setArea(Area area) {
this.area = area;
}
}
Once this relationship is established you can reference the area object in your @Query declaration. The query specified in your @Query annotation must follow proper syntax, which means you should omit the on clause. See the following:
@Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")
While looking over your question I also made the relationship between the User and Area entities bidirectional. Here is the source for the Area entity to establish the bidirectional relationship.
Area.java
@Entity
@Table(name = "area")
public class Area {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="idarea")
private Long idArea;
@Column(name="area_name")
private String areaName;
@OneToOne(fetch=FetchType.LAZY, mappedBy="area")
private User user;
public Long getIdArea() {
return idArea;
}
public void setIdArea(Long idArea) {
this.idArea = idArea;
}
public String getAreaName() {
return areaName;
}
public void setAreaName(String areaName) {
this.areaName = areaName;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
Actually strings have very few resemblances to value types. For starters, not all value types are immutable, you can change the value of an Int32 all you want and it it would still be the same address on the stack.
Strings are immutable for a very good reason, it has nothing to do with it being a reference type, but has a lot to do with memory management. It's just more efficient to create a new object when string size changes than to shift things around on the managed heap. I think you're mixing together value/reference types and immutable objects concepts.
As far as "==": Like you said "==" is an operator overload, and again it was implemented for a very good reason to make framework more useful when working with strings.