I was just searching for a solution for this :)
it appears that you can't have OkControlID assign to a control if you want to that control fires an event, just removing this property I got everything working again.
my code (working):
<asp:Panel ID="pnlResetPanelsView" CssClass="modalPopup" runat="server" Style="display:none;">
<h2>
Warning</h2>
<p>
Do you really want to reset the panels to the default view?</p>
<div style="text-align: center;">
<asp:Button ID="btnResetPanelsViewOK" Width="60" runat="server" Text="Yes"
CssClass="buttonSuperOfficeLayout" OnClick="btnResetPanelsViewOK_Click" />
<asp:Button ID="btnResetPanelsViewCancel" Width="60" runat="server" Text="No" CssClass="buttonSuperOfficeLayout" />
</div>
</asp:Panel>
<ajax:ModalPopupExtender ID="mpeResetPanelsView" runat="server" TargetControlID="btnResetView"
PopupControlID="pnlResetPanelsView" BackgroundCssClass="modalBackground" DropShadow="true"
CancelControlID="btnResetPanelsViewCancel" />
echo "Enter the Programs you want to run:"
> ${PROGRAM_LIST}
while read PROGRAM_ENTRY
do
if [ ! -s ${PROGRAM_ENTRY} ]
then
echo ${PROGRAM_ENTRY} >> ${PROGRAM_LIST}
else
break
fi
done
This will do it in Delphi. Note the use of the BitBlt function, which is a Windows API call, not something specific to Delphi.
Edit: Added example usage
function TForm1.GetScreenShot(OnlyActiveWindow: boolean) : TBitmap;
var
w,h : integer;
DC : HDC;
hWin : Cardinal;
r : TRect;
begin
//take a screenshot and return it as a TBitmap.
//if they specify "OnlyActiveWindow", then restrict the screenshot to the
//currently focused window (same as alt-prtscrn)
//Otherwise, get a normal screenshot (same as prtscrn)
Result := TBitmap.Create;
if OnlyActiveWindow then begin
hWin := GetForegroundWindow;
dc := GetWindowDC(hWin);
GetWindowRect(hWin,r);
w := r.Right - r.Left;
h := r.Bottom - r.Top;
end //if active window only
else begin
hWin := GetDesktopWindow;
dc := GetDC(hWin);
w := GetDeviceCaps(DC,HORZRES);
h := GetDeviceCaps(DC,VERTRES);
end; //else entire desktop
try
Result.Width := w;
Result.Height := h;
BitBlt(Result.Canvas.Handle,0,0,Result.Width,Result.Height,DC,0,0,SRCCOPY);
finally
ReleaseDC(hWin, DC) ;
end; //try-finally
end;
procedure TForm1.btnSaveScreenshotClick(Sender: TObject);
var
bmp : TBitmap;
savdlg : TSaveDialog;
begin
//take a screenshot, prompt for where to save it
savdlg := TSaveDialog.Create(Self);
bmp := GetScreenshot(False);
try
if savdlg.Execute then begin
bmp.SaveToFile(savdlg.FileName);
end;
finally
FreeAndNil(bmp);
FreeAndNil(savdlg);
end; //try-finally
end;
Good question - I think the only way to achieve this is to filter the items in the select.
You can do this through a jquery plugin. Check the following link, it describes how to achieve something similar to what you need. Thanks
jQuery disable SELECT options based on Radio selected (Need support for all browsers)
Maybe can be shorter an more elegant. But I did it.
public String getHumanTimeFormatFromMilliseconds(String millisecondS){
String message = "";
long milliseconds = Long.valueOf(millisecondS);
if (milliseconds >= 1000){
int seconds = (int) (milliseconds / 1000) % 60;
int minutes = (int) ((milliseconds / (1000 * 60)) % 60);
int hours = (int) ((milliseconds / (1000 * 60 * 60)) % 24);
int days = (int) (milliseconds / (1000 * 60 * 60 * 24));
if((days == 0) && (hours != 0)){
message = String.format("%d hours %d minutes %d seconds ago", hours, minutes, seconds);
}else if((hours == 0) && (minutes != 0)){
message = String.format("%d minutes %d seconds ago", minutes, seconds);
}else if((days == 0) && (hours == 0) && (minutes == 0)){
message = String.format("%d seconds ago", seconds);
}else{
message = String.format("%d days %d hours %d minutes %d seconds ago", days, hours, minutes, seconds);
}
} else{
message = "Less than a second ago.";
}
return message;
}
Try running the Powershell GUI as Administrator
For version 14. On mac, it is ?(alt) + ? + ?
You can modify the id
without having to use getElementById
Example:
<div id = 'One' onclick = "One.id = 'Two'; return false;">One</div>
You can see it here: http://jsbin.com/elikaj/1/
Tested with Mozilla Firefox 22 and Google Chrome 60.0
This is old post but I will share one my solution because noone mention here one problem before.
New email address can contain UTF-8 characters or special domain names like .live
, .news
etc.
Also I find that some email address can be on Cyrilic and on all cases standard regex or filter_var()
will fail.
That's why I made an solution for it:
function valid_email($email)
{
if(is_array($email) || is_numeric($email) || is_bool($email) || is_float($email) || is_file($email) || is_dir($email) || is_int($email))
return false;
else
{
$email=trim(strtolower($email));
if(filter_var($email, FILTER_VALIDATE_EMAIL)!==false) return $email;
else
{
$pattern = '/^(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){255,})(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){65,}@)(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22))(?:\\.(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22)))*@(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-+[a-z0-9]+)*\\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-+[a-z0-9]+)*)|(?:\\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\\]))$/iD';
return (preg_match($pattern, $email) === 1) ? $email : false;
}
}
}
This function work perfectly for all cases and email formats.
The reason of this warning is i was presenting a view controller over a small view that is not full size view. Given below is the image of my project. where on click on four option above. User navigate to different childviewcontroller's view.(it works like tabViewcontroller). But the childviewcontroller contains view of small size. So if we present a view from childviewcontroller it gives this warning.
And to avoid this, you can present a view on childviewcontroller's parent
[self.parentViewController presentViewController:viewController animated:YES completion:nil];
This is concerning "Build Solution" option only.
I got totally fed up with Visual Studio's inability to really clean solutions and wrote this little tool that will do it for you.
Close your solution in VS first and drag its folder from Windows Explorer into this app or into its icon. Depending on the setting at the bottom of its window, it can also remove additional stuff, that will help if you try to manually upload your solution to GitHub or share it with someone else:
In a nutshell, it will place all "Debug" folders, Intellisense, and other caches that can be rebuilt by VS into Recycle Bin for you.
Using COUNT instead of SUM removes the requirement for an ELSE statement:
SELECT jobId, jobName,
COUNT(CASE WHEN Priority=1 THEN 1 END) AS Priority1,
COUNT(CASE WHEN Priority=2 THEN 1 END) AS Priority2,
COUNT(CASE WHEN Priority=3 THEN 1 END) AS Priority3,
COUNT(CASE WHEN Priority=4 THEN 1 END) AS Priority4,
COUNT(CASE WHEN Priority=5 THEN 1 END) AS Priority5
FROM TableName
GROUP BY jobId, jobName
function pyramid(n) {
for(i=1 ;i<=n;i++) {
let str = ' '.repeat(n-i);
let str2 = '*'.repeat(i*2-1);
console.log(str + str2 + str);
}
}
pyramid(5)
var arr = new Array();
$('li').each(function() {
arr.push(this.innerHTML);
})
That should work, you may need a space after the commas.
Also, the function you call afterwards must support an array of objects, and not just a singleton object.
i had a similar problem - firefox returned the correct value of obj.clientHeight but ie did not- it returned 0. I changed it to obj.offsetHeight and it worked. Seems there is some state that ie has for clientheight - that makes it iffy...
The content
property states:
Authors may include newlines in the generated content by writing the "\A" escape sequence in one of the strings after the 'content' property. This inserted line break is still subject to the 'white-space' property. See "Strings" and "Characters and case" for more information on the "\A" escape sequence.
So you can use:
#headerAgentInfoDetailsPhone:after {
content:"Office: XXXXX \A Mobile: YYYYY ";
white-space: pre; /* or pre-wrap */
}
When escaping arbitrary strings, however, it's advisable to use \00000a
instead of \A
, because any number or [a-f]
character followed by the new line may give unpredictable results:
function addTextToStyle(id, text) {
return `#${id}::after { content: "${text.replace(/"/g, '\\"').replace(/\n/g, '\\00000a')} }"`;
}
Just pass it as an argument of findAll
:
>>> from BeautifulSoup import BeautifulSoup
>>> soup = BeautifulSoup("""
... <html>
... <head><title>My Title!</title></head>
... <body><table>
... <tr><td>First!</td>
... <td valign="top">Second!</td></tr>
... </table></body><html>
... """)
>>>
>>> soup.findAll('td')
[<td>First!</td>, <td valign="top">Second!</td>]
>>>
>>> soup.findAll('td', valign='top')
[<td valign="top">Second!</td>]
In python, not
is a boolean operator which gets the opposite of a value:
>>> myval = 0
>>> nyvalue = not myval
>>> nyvalue
True
>>> myval = 1
>>> nyvalue = not myval
>>> nyvalue
False
And True == 1
and False == 0
(if you need to convert it to an integer, you can use int()
)
Try this:
declare @var char(3)
set @var='[%]'
select Address from Accomodation where Address like '%'+@var+'%'
You must use [] cancels the effect of wildcard, so you read % as a normal character, idem about character _
In current version of Jekyll, it defaults to http://127.0.0.1:4000/.
This is good, if you are connected to a network but do not want anyone else to access your application.
However it may happen that you want to see how your application runs on a mobile or from some other laptop/computer.
In that case, you can use
jekyll serve --host 0.0.0.0
This binds your application to the host & next use following to connect to it from some other host
http://host's IP adress/4000
Anyone who is just starting with Haskell and trying to print an Int, use:
module Lib
( someFunc
) where
someFunc :: IO ()
x = 123
someFunc = putStrLn (show x)
Short answers:
Q1: Yes.
Q2: Doesn't matter which you use.
Long answer:
A select ... for update
will (as it implies) select certain rows but also lock them as if they have already been updated by the current transaction (or as if the identity update had been performed). This allows you to update them again in the current transaction and then commit, without another transaction being able to modify these rows in any way.
Another way of looking at it, it is as if the following two statements are executed atomically:
select * from my_table where my_condition;
update my_table set my_column = my_column where my_condition;
Since the rows affected by my_condition
are locked, no other transaction can modify them in any way, and hence, transaction isolation level makes no difference here.
Note also that transaction isolation level is independent of locking: setting a different isolation level doesn't allow you to get around locking and update rows in a different transaction that are locked by your transaction.
What transaction isolation levels do guarantee (at different levels) is the consistency of data while transactions are in progress.
np.unique
when I run it on np.random.random(100).reshape(10,10)
returns all the unique individual elements, but you want the unique rows, so first you need to put them into tuples:
array = #your numpy array of lists
new_array = [tuple(row) for row in array]
uniques = np.unique(new_array)
That is the only way I see you changing the types to do what you want, and I am not sure if the list iteration to change to tuples is okay with your "not looping through"
It will kill not only all plot windows, but all processes that are called python3, except the current script you run. It works for python3. So, if you are running any other python3 script it will be terminated. As I only run one script at once, it does the job for me.
import os
import subprocess
subprocess.call(["bash","-c",'pyIDs=($(pgrep python3));for x in "${pyIDs[@]}"; do if [ "$x" -ne '+str(os.getpid())+' ];then kill -9 "$x"; fi done'])
I like checking the orientation notification because you can add this feature in any class, no needs to be a view or a view controller. Even in your app delegate.
SWIFT 5:
//ask the system to start notifying when interface change
UIDevice.current.beginGeneratingDeviceOrientationNotifications()
//add the observer
NotificationCenter.default.addObserver(
self,
selector: #selector(orientationChanged(notification:)),
name: UIDevice.orientationDidChangeNotification,
object: nil)
than caching the notification
@objc func orientationChanged(notification : NSNotification) {
//your code there
}
var answer = accountTable.Aggregate(new { Min = int.MinValue, Max = int.MaxValue },
(a, b) => new { Min = Math.Min(a.Min, b.Field<int>("AccountLevel")),
Max = Math.Max(a.Max, b.Field<int>("AccountLevel")) });
int min = answer.Min;
int max = answer.Max;
1 iteration, linq style :)
When you perform
>>> [(i) for i in my_list if i=="two"]
i
is iterated through the list my_list
. As the list comprehension finishes evaluation, i
is assigned to the last item in iteration, which is "three"
.
BIG WARNING: Make ONE HUNDRED PERCENT sure that your extension is not already tied to some mime type.
We used the extension '.icz' for our custom files for, basically, ever, and Safari just never would let you open them saying "Safari cannot open this file." no matter what we did or tried with the UT stuff above.
Eventually I realized that there are some UT* C functions you can use to explore various things, and while .icz gives the right answer (our app):
In app did load at top, just do this...
NSString * UTI = (NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension,
(CFStringRef)@"icz",
NULL);
CFURLRef ur =UTTypeCopyDeclaringBundleURL(UTI);
and put break after that line and see what UTI and ur are -- in our case, it was our identifier as we wanted), and the bundle url (ur) was pointing to our app's folder.
But the MIME type that Dropbox gives us back for our link, which you can check by doing e.g.
$ curl -D headers THEURLGOESHERE > /dev/null
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 27393 100 27393 0 0 24983 0 0:00:01 0:00:01 --:--:-- 28926
$ cat headers
HTTP/1.1 200 OK
accept-ranges: bytes
cache-control: max-age=0
content-disposition: attachment; filename="123.icz"
Content-Type: text/calendar
Date: Fri, 24 May 2013 17:41:28 GMT
etag: 872926d
pragma: public
Server: nginx
x-dropbox-request-id: 13bd327248d90fde
X-RequestId: bf9adc56934eff0bfb68a01d526eba1f
x-server-response-time: 379
Content-Length: 27393
Connection: keep-alive
The Content-Type is what we want. Dropbox claims this is a text/calendar entry. Great. But in my case, I've ALREADY TRIED PUTTING text/calendar into my app's mime types, and it still doesn't work. Instead, when I try to get the UTI and bundle url for the text/calendar mimetype,
NSString * UTI = (NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType,
(CFStringRef)@"text/calendar",
NULL);
CFURLRef ur =UTTypeCopyDeclaringBundleURL(UTI);
I see "com.apple.ical.ics" as the UTI and ".../MobileCoreTypes.bundle/" as the bundle URL. Not our app, but Apple. So I try putting com.apple.ical.ics into the LSItemContentTypes alongside my own, and into UTConformsTo in the export, but no go.
So basically, if Apple thinks they want to at some point handle some form of file type (that could be created 10 years after your app is live, mind you), you will have to change extension cause they'll simply not let you handle the file type.
The FolderBrowserDialog class is the best option.
All you need to do is put a type tag and make the type button.
<button id="btnId" type="button">Hide/Show</button>
_x000D_
That solves the issue
You should just grab the window by the title bar and snap it to the left side of your screen (close browser) then reopen the browser ans snap it to the top... problem is over.
I'd prefer to use splice method:
var chunks = function(array, size) {
var results = [];
while (array.length) {
results.push(array.splice(0, size));
}
return results;
};
The glow effect is most-likely controlled by box-shadow. In addition to adding what Pavel said, you can add the box-shadow property for the different browser engines.
textarea {
border: none;
overflow: auto;
outline: none;
-webkit-box-shadow: none;
-moz-box-shadow: none;
box-shadow: none;
resize: none; /*remove the resize handle on the bottom right*/
}
You may also try adding !important to prioritize this CSS.
Generally you compile most .c files in the following way:
gcc foo.c -o foo. It might vary depending on what #includes you used or if you have any external .h files. Generally, when you have a C file, it looks somewhat like the following:
#include <stdio.h>
/* any other includes, prototypes, struct delcarations... */
int main(){
*/ code */
}
When I get an 'undefined reference to main', it usually means that I have a .c file that does not have int main()
in the file. If you first learned java, this is an understandable manner of confusion since in Java, your code usually looks like the following:
//any import statements you have
public class Foo{
int main(){}
}
I would advise looking to see if you have int main()
at the top.
Dim inputString As String = "ra"
Enumerable.Range(0, arr.Length).Where(Function(x) arr(x).ToLower().Contains(inputString.ToLower()))
Hope this piece of code give you an idea of changing jPanels inside a JFrame.
public class PanelTest extends JFrame {
Container contentPane;
public PanelTest() {
super("Changing JPanel inside a JFrame");
contentPane=getContentPane();
}
public void createChangePanel() {
contentPane.removeAll();
JPanel newPanel=new JPanel();
contentPane.add(newPanel);
System.out.println("new panel created");//for debugging purposes
validate();
setVisible(true);
}
}
I was also getting the same error.
nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)
and when i typed the localhost in the browser, then i was getting
It works!
This is the default web page for this server.
The web server software is running but no content has been added, yet. instead of nginx welcome page, apache2 is running on the same port,
find the apache2 ports.conf file
sudo /etc/apache2/ports.conf
change the port other then 80
, i make it as 70
save the file
restart your system
it will works for you also, if you type the localhost in the browser, you will get nginx welcome page
If you want to find all occurences:
>>> re.findall('\(.*?\)',s)
[u"(date='2/xc2/xb2',time='/case/test.png')", u'(eee)']
>>> re.findall('\((.*?)\)',s)
[u"date='2/xc2/xb2',time='/case/test.png'", u'eee']
browser.close()
will close only the current chrome window.
browser.quit()
should close all of the open windows, then exit webdriver.
Toni
's answer is very useful, but I thought a quick start for total beginners to test coverage assessment (like I am).
As already mentioned, Visual Studio Professional and Community Editions do not have built-in test coverage support. However, it can be obtained quite easily. I will write step-by-step configuration for use with NUnit tests within Visual Studion 2015 Professional.
Install OpenCover NUGet component using NuGet interface
Get OpenCoverUI extension. This can be installed directly from Visual Studio by using Tools -> Extensions and Updates
Configure OpenCoverUI to use the appropriate executables, by accessing Tools -> Options -> OpenCover.UI Options -> General
NUnit Path: must point to the `nunit-console.exe file. This can be found only within NUnit 2.xx version, which can be downloaded from here.
OpenCover Path: this should point to the installed package, usually <solution path>\packages\OpenCover.4.6.519\tools\OpenCover.Console.exe
Install ReportGenerator NUGet package
Access OpenCover Test Explorer
from OpenCover menu. Try discovering tests from there. If it fails, check Output windows for more details.
Check OpenCover Results (within OpenCover menu) for more details. It will output details such as Code Coverage in a tree based view. You can also highlight code that is or is not covered (small icon in the top-left).
NOTE: as mentioned, OpenCoverUI does not support latest major version of NUnit (3.xx). However, if nothing specific to this version is used within tests, it will work with no problems, regardless of having installed NUnit 3.xx version.
This covers the quick start. As already mentioned in the comments, for more advanced configuration and automation check this article.
PS C:\Users\joshua> $file = New-Object System.IO.FileInfo('file.type')
PS C:\Users\joshua> $file.BaseName, $file.Extension
file
.type
Cconvert NSTimeInterval
milisecondedDate
value to nsstring
and after that convert into int
.
try this : here select is your select element
let select = document.getElementsByClassName('lstSelected')[0],
options = select.options,
len = options.length,
data='',
i=0;
while (i<len){
if (options[i].selected)
data+= "&" + select.name + '=' + options[i].value;
i++;
}
return data;
Data is in the form of query string i.e.name=value&name=anotherValue
This could work as well:
def get_first_element(MyModel):
my_query = MyModel.objects.all()
return my_query[:1]
if it's empty, then returns an empty list, otherwise it returns the first element inside a list.
Simply declare in styles.xml
<style name="AppTheme.Fullscreen" parent="AppTheme">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
</style>
Then use in menifest.xml
<activity
android:name=".activities.Splash"
android:theme="@style/AppTheme.Fullscreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Chill Pill :)
Using ImageMagick, this is very similar to hackerb9 code and result, but is a little simpler command line. It does assume that the top left pixel is the background color. I just flood fill the background with transparency, then select the alpha channel and blur it and remove half of the blurred area using -level 50x100%. Then turn back on all the channels and flatten it against the brown color. The -blur 0x1 -level 50x100% acts to antialias the boundaries of the alpha channel transparency. You can adjust the fuzz value, blur amount and the -level 50% value to change the degree of antialiasing.
convert logo: -fuzz 25% -fill none -draw "matte 0,0 floodfill" -channel alpha -blur 0x1 -level 50x100% +channel -background saddlebrown -flatten result.jpg
The following command worked for me. Docker file was placed in my-app-master folder.
docker build -f my-app-master/Dockerfile -t my-app-master .
Use padding in percentages too and remove from the width:
padding: 5%; width: 90%;
I often used the following code to import a module which sit under the same directory as the running script. It will first get the directory from which powershell is running
$currentPath=Split-Path ((Get-Variable MyInvocation -Scope 0).Value).MyCommand.Path
import-module "$currentPath\sqlps.ps1"
In TestNG, you use dependsOnMethods and/or dependsOnGroups:
@Test(groups = "a")
public void f1() {}
@Test(groups = "a")
public void f2() {}
@Test(dependsOnGroups = "a")
public void g() {}
In this case, g() will only run after f1() and f2() have completed and succeeded.
You will find a lot of examples in the documentation: http://testng.org/doc/documentation-main.html#test-groups
The answers so far have been correct, but here is some additional information:
One can safely rename a branch with '-m' (move), but one has to be careful with '-M', because it forces the rename, even if there is an existing branch with the same name already. Here is the excerpt from the 'git-branch' man page:
With a -m or -M option,
<oldbranch>
will be renamed to<newbranch>
. If<oldbranch>
had a corresponding reflog, it is renamed to match<newbranch>
, and a reflog entry is created to remember the branch renaming. If<newbranch>
exists, -M must be used to force the rename to happen.
Prefix the call with Module2 (ex. Module2.IDLE
). I'm assuming since you asked this that you have IDLE defined multiple times in the project, otherwise this shouldn't be necessary.
Try this:
Suppose HTML like this :
<form id="myform" name="myform" method="POST" action="process_edit_questionnaire.php?project=<?php echo $project_id; ?>">
<div id="question_block">
testing form
</div>
<a href="javascript: submit();">Submit</a>
</form>
<script type='text/javascript'>
function submit()
{
document.forms["myform"].submit();
}
</script>
you can check it out here : http://jsfiddle.net/Zm426/7/
Please try with this
$pattern = "/My name is '\(.*\)' and im fine/";
You can manually set xticks (and yticks) using pyplot.xticks:
import matplotlib.pyplot as plt
import numpy as np
x = np.array([0,1,2,3])
y = np.array([20,21,22,23])
my_xticks = ['John','Arnold','Mavis','Matt']
plt.xticks(x, my_xticks)
plt.plot(x, y)
plt.show()
Have you tried the import text function.
You can call bash directly within your Makefile instead of using the default shell:
bash -c "ls -al"
instead of:
ls -al
It is a server error, not a client error. If server errors weren't to be returned to the client, there wouldn't have been created an entire status code class for them (i.e. 5xx).
You can't hide the fact that you either made a programming error or some service you rely on is unavailable, and that certainly isn't the client's fault. Returning any other range of code in those cases than the 5xx series would make no sense.
RFC 7231 mentions in section 6.6. Server Error 5xx:
The 5xx (Server Error) class of status code indicates that the server is aware that it has erred or is incapable of performing the requested method.
This is exactly the case. There's nothing "internal" about the code "500 Internal Server Error" in the sense that it shouldn't be exposed to the client.
It is general practice in various messaging protocols to keep heartbeating each other (keep sending ping packets) the packet does not need to be very large. The probing mechanism will allow you to detect the disconnected client even before TCP figures it out in general (TCP timeout is far higher) Send a probe and wait for say 5 seconds for a reply, if you do not see reply for say 2-3 subsequent probes, your player is disconnected.
Also, related question
You should be careful about running test
for an unquoted variable, because it might produce unexpected results:
$ [ -f ]
$ echo $?
0
$ [ -f "" ]
$ echo $?
1
The recommendation is usually to have the tested variable surrounded by double quotation marks:
#!/bin/sh
FILE=$1
if [ ! -f "$FILE" ]
then
echo "File $FILE does not exist."
fi
1: No difference. It is kept around to allow old S-code to continue to function. This is documented a "Note" in ?Math
2: Yes: But you already know it:
`^`(x,y)
#[1] 1024
In R the mathematical operators are really functions that the parser takes care of rearranging arguments and function names for you to simulate ordinary mathematical infix notation. Also documented at ?Math
.
Edit: Let me add that knowing how R handles infix operators (i.e. two argument functions) is very important in understanding the use of the foundational infix "[[" and "["-functions as (functional) second arguments to lapply
and sapply
:
> sapply( list( list(1,2,3), list(4,3,6) ), "[[", 1)
[1] 1 4
> firsts <- function(lis) sapply(lis, "[[", 1)
> firsts( list( list(1,2,3), list(4,3,6) ) )
[1] 1 4
From a display perspective .container
gives you more control over the what the users are seeing, and makes it easier to see what the users will see as you only have 4 variations of display (5 in the case of bootstrap 5) because the sizes relate to the same as the grid sizes. e.g. .col-xs
, .col-sm
, .col
, and .col-lg
.
What this means, is that when you are doing user testing if you test on a displays with the 4 different sizes you see all the veriations in display.
When using .container-fluid
because the witdh is related to the viewport width the display is dynamic, so the varations are much greater and users with very large screens or uncommon screen widths may see results you weren't expecting.
Here's what's working for me
on windows
1) Add this to your %WINDIR%\System32\drivers\etc\hosts file: 127.0.0.1 localdev.YOURSITE.net (cause browser have issues with 'localhost' (for cross origin scripting)
Windows Vista and Windows 7 Vista and Windows 7 use User Account Control (UAC) so Notepad must be run as Administrator.
Click Start -> All Programs -> Accessories
Right click Notepad and select Run as administrator
Click Continue on the "Windows needs your permission" UAC window.
When Notepad opens Click File -> Open
In the filename field type C:\Windows\System32\Drivers\etc\hosts
Click Open
Add this to your %WINDIR%\System32\drivers\etc\hosts file: 127.0.0.1 localdev.YOURSITE.net
Save
Close and restart browsers
On Mac or Linux:
su
permission127.0.0.1 localdev.YOURSITE.net
When developing you use localdev.YOURSITE.net instead of localhost so if you are using run/debug configurations in your ide be sure to update it.
Use ".YOURSITE.net" as cookiedomain (with a dot in the beginning) when creating the cookiem then it should work with all subdomains.
2) create the certificate using that localdev.url
TIP: If you have issues generating certificates on windows, use a VirtualBox or Vmware machine instead.
3) import the certificate as outlined on http://www.charlesproxy.com/documentation/using-charles/ssl-certificates/
Came here to see how to append an item to a 2D array, but the title of the thread is a bit misleading because it is exploring an issue with the appending.
The easiest way I found to append to a 2D list is like this:
list=[[]]
list.append((var_1,var_2))
This will result in an entry with the 2 variables var_1, var_2. Hope this helps!
Addressing cases that some of the other answers don't handle well:
Many of the solutions on this page involve polling Console.KeyAvailable
or blocking on Console.ReadKey
. While it's true that the .NET Console
is not very cooperative here, you can use Task.Run
to move towards a more modern Async
mode of listening.
The main issue to be aware of is that, by default, your console thread isn't set up for Async
operation--meaning that, when you fall out of the bottom of your main
function, instead of awaiting Async
completions, your AppDoman and process will end. A proper way to address this would be to use Stephen Cleary's AsyncContext to establish full Async
support in your single-threaded console program. But for simpler cases, like waiting for a keypress, installing a full trampoline may be overkill.
The example below would be for a console program used in some kind of iterative batch file. In this case, when the program is done with its work, normally it should exit without requiring a keypress, and then we allow an optional key press to prevent the app from exiting. We can pause the cycle to examine things, possibly resuming, or use the pause as a known 'control point' at which to cleanly break out of the batch file.
static void Main(String[] args)
{
Console.WriteLine("Press any key to prevent exit...");
var tHold = Task.Run(() => Console.ReadKey(true));
// ... do your console app activity ...
if (tHold.IsCompleted)
{
#if false // For the 'hold' state, you can simply halt forever...
Console.WriteLine("Holding.");
Thread.Sleep(Timeout.Infinite);
#else // ...or allow continuing to exit
while (Console.KeyAvailable)
Console.ReadKey(true); // flush/consume any extras
Console.WriteLine("Holding. Press 'Esc' to exit.");
while (Console.ReadKey(true).Key != ConsoleKey.Escape)
;
#endif
}
}
By default, unlike an exception, a warning doesn't interrupt.
After import warnings
, it is possible to specify a Warnings class when generating a warning. If one is not specified, it is literally UserWarning
by default.
>>> warnings.warn('This is a default warning.')
<string>:1: UserWarning: This is a default warning.
To simply use a preexisting class instead, e.g. DeprecationWarning
:
>>> warnings.warn('This is a particular warning.', DeprecationWarning)
<string>:1: DeprecationWarning: This is a particular warning.
Creating a custom warning class is similar to creating a custom exception class:
>>> class MyCustomWarning(UserWarning):
... pass
...
... warnings.warn('This is my custom warning.', MyCustomWarning)
<string>:1: MyCustomWarning: This is my custom warning.
For testing, consider assertWarns
or assertWarnsRegex
.
As an alternative, especially for standalone applications, consider the logging
module. It can log messages having a level of debug, info, warning, error, etc. Log messages having a level of warning or higher are by default printed to stderr.
I ran into the same issue a while ago and did solve it by using reflection with some help from Jackson.
First populate a map with all the fields on an Object. Then add those map entries as parameters to the MockHttpServletRequestBuilder.
In this way you can use any Object and you are passing it as request parameters. I'm sure there are other solutions out there but this one worked for us:
@Test
public void testFormEdit() throws Exception {
getMockMvc()
.perform(
addFormParameters(post(servletPath + tableRootUrl + "/" + POST_FORM_EDIT_URL).servletPath(servletPath)
.param("entityID", entityId), validEntity)).andDo(print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON)).andExpect(content().string(equalTo(entityId)));
}
private MockHttpServletRequestBuilder addFormParameters(MockHttpServletRequestBuilder builder, Object object)
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
SimpleDateFormat dateFormat = new SimpleDateFormat(applicationSettings.getApplicationDateFormat());
Map<String, ?> propertyValues = getPropertyValues(object, dateFormat);
for (Entry<String, ?> entry : propertyValues.entrySet()) {
builder.param(entry.getKey(),
Util.prepareDisplayValue(entry.getValue(), applicationSettings.getApplicationDateFormat()));
}
return builder;
}
private Map<String, ?> getPropertyValues(Object object, DateFormat dateFormat) {
ObjectMapper mapper = new ObjectMapper();
mapper.setDateFormat(dateFormat);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.registerModule(new JodaModule());
TypeReference<HashMap<String, ?>> typeRef = new TypeReference<HashMap<String, ?>>() {};
Map<String, ?> returnValues = mapper.convertValue(object, typeRef);
return returnValues;
}
The way to do this is via the bracket notation.
var test = {_x000D_
"id": "109",_x000D_
"No. of interfaces": "4"_x000D_
}_x000D_
alert(test["No. of interfaces"]);
_x000D_
For more info read out here:
A char
variable is actually an 8-bit integral value. It will have values from 0
to 255
. These are ASCII codes. 0
stands for the C-null character, and 255
stands for an empty symbol.
So, when you write the following assignment:
char a = 'a';
It is the same thing as:
char a = 97;
So, you can compare two char
variables using the >
, <
, ==
, <=
, >=
operators:
char a = 'a';
char b = 'b';
if( a < b ) printf("%c is smaller than %c", a, b);
if( a > b ) printf("%c is smaller than %c", a, b);
if( a == b ) printf("%c is equal to %c", a, b);
Use NUMPAD 7 and NUMPAD 9. It will help you.
Similar to Julien's answer above, I had success with the following:
fig, ax = plt.subplots(figsize=(10,4))
for key, grp in df.groupby(['ticker']):
ax.plot(grp['Date'], grp['adj_close'], label=key)
ax.legend()
plt.show()
This solution might be more relevant if you want more control in matlab.
Solution inspired by: https://stackoverflow.com/a/52526454/10521959
Storing files in your database will lead to a huge database size. You may not like that, for development, testing, backups, etc.
Instead, you'd use FileStream (SQL-Server) or BFILE (Oracle).
There is no default-implementation of BFILE/FileStream in Postgres, but you can add it: https://github.com/darold/external_file
And further information (in french) can be obtained here:
http://blog.dalibo.com/2015/01/26/Extension_BFILE_pour_PostgreSQL.html
To answer the acual question:
Apart from bytea
, for really large files, you can use LOBS:
// http://stackoverflow.com/questions/14509747/inserting-large-object-into-postgresql-returns-53200-out-of-memory-error
// https://github.com/npgsql/Npgsql/wiki/User-Manual
public int InsertLargeObject()
{
int noid;
byte[] BinaryData = new byte[123];
// Npgsql.NpgsqlCommand cmd ;
// long lng = cmd.LastInsertedOID;
using (Npgsql.NpgsqlConnection connection = new Npgsql.NpgsqlConnection(GetConnectionString()))
{
using (Npgsql.NpgsqlTransaction transaction = connection.BeginTransaction())
{
try
{
NpgsqlTypes.LargeObjectManager manager = new NpgsqlTypes.LargeObjectManager(connection);
noid = manager.Create(NpgsqlTypes.LargeObjectManager.READWRITE);
NpgsqlTypes.LargeObject lo = manager.Open(noid, NpgsqlTypes.LargeObjectManager.READWRITE);
// lo.Write(BinaryData);
int i = 0;
do
{
int length = 1000;
if (i + length > BinaryData.Length)
length = BinaryData.Length - i;
byte[] chunk = new byte[length];
System.Array.Copy(BinaryData, i, chunk, 0, length);
lo.Write(chunk, 0, length);
i += length;
} while (i < BinaryData.Length);
lo.Close();
transaction.Commit();
} // End Try
catch
{
transaction.Rollback();
throw;
} // End Catch
return noid;
} // End Using transaction
} // End using connection
} // End Function InsertLargeObject
public System.Drawing.Image GetLargeDrawing(int idOfOID)
{
System.Drawing.Image img;
using (Npgsql.NpgsqlConnection connection = new Npgsql.NpgsqlConnection(GetConnectionString()))
{
lock (connection)
{
if (connection.State != System.Data.ConnectionState.Open)
connection.Open();
using (Npgsql.NpgsqlTransaction trans = connection.BeginTransaction())
{
NpgsqlTypes.LargeObjectManager lbm = new NpgsqlTypes.LargeObjectManager(connection);
NpgsqlTypes.LargeObject lo = lbm.Open(takeOID(idOfOID), NpgsqlTypes.LargeObjectManager.READWRITE); //take picture oid from metod takeOID
byte[] buffer = new byte[32768];
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
int read;
while ((read = lo.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
} // Whend
img = System.Drawing.Image.FromStream(ms);
} // End Using ms
lo.Close();
trans.Commit();
if (connection.State != System.Data.ConnectionState.Closed)
connection.Close();
} // End Using trans
} // End lock connection
} // End Using connection
return img;
} // End Function GetLargeDrawing
public void DeleteLargeObject(int noid)
{
using (Npgsql.NpgsqlConnection connection = new Npgsql.NpgsqlConnection(GetConnectionString()))
{
if (connection.State != System.Data.ConnectionState.Open)
connection.Open();
using (Npgsql.NpgsqlTransaction trans = connection.BeginTransaction())
{
NpgsqlTypes.LargeObjectManager lbm = new NpgsqlTypes.LargeObjectManager(connection);
lbm.Delete(noid);
trans.Commit();
if (connection.State != System.Data.ConnectionState.Closed)
connection.Close();
} // End Using trans
} // End Using connection
} // End Sub DeleteLargeObject
Any chance that you changed the name of your table view from "tableView" to "myTableView" at some point?
<a href="sms:/* phone number here */&body=/* body text here */">Link</a>
This works on my iPhone 5S!
BrenBarn is correct. The error means you tried to do something like None[5]
. In the backtrace, it says self.imageDef=self.values[2]
, which means that your self.values
is None
.
You should go through all the functions that update self.values
and make sure you account for all the corner cases.
List of Integer
.
List<Integer> list = new ArrayList<>();
int x = 5;
list.add(x);
This worked for me (on Windows 10):
Add the following lines into your scripts in the package.json file:
"dev": "npm run development",
"development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
"watch": "npm run development -- --watch",
"watch-poll": "npm run watch -- --watch-poll",
"hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
"prod": "npm run production",
"production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
Make your devDependencies looks something like this:
"devDependencies": {
"axios": "^0.18",
"bootstrap": "^4.0.0",
"popper.js": "^1.12",
"cross-env": "^5.1",
"jquery": "^3.2",
"laravel-mix": "^2.0",
"lodash": "^4.17.4",
"vue": "^2.5.7"
}
Remove node_modules
folder
npm install
npm run dev
So many questions here. I see at least two, maybe three:
*args
being used for?The first question is trivially answered in the Python Standard Library reference:
pop(key[, default])
If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised.
The second question is covered in the Python Language Reference:
If the form โ*identifierโ is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. If the form โ**identifierโ is present, it is initialized to a new dictionary receiving any excess keyword arguments, defaulting to a new empty dictionary.
In other words, the pop
function takes at least two arguments. The first two get assigned the names self
and key
; and the rest are stuffed into a tuple called args
.
What's happening on the next line when *args
is passed along in the call to self.data.pop
is the inverse of this - the tuple *args
is expanded to of positional parameters which get passed along. This is explained in the Python Language Reference:
If the syntax *expression appears in the function call, expression must evaluate to a sequence. Elements from this sequence are treated as if they were additional positional arguments
In short, a.pop()
wants to be flexible and accept any number of positional parameters, so that it can pass this unknown number of positional parameters on to self.data.pop()
.
This gives you flexibility; data
happens to be a dict
right now, and so self.data.pop()
takes either one or two parameters; but if you changed data
to be a type which took 19 parameters for a call to self.data.pop()
you wouldn't have to change class a
at all. You'd still have to change any code that called a.pop()
to pass the required 19 parameters though.
A .jar file is akin to a .exe file. In essence, they are both executable zip files (different zip algorithms).
In a jar file, you will see folders and class files. Each class file is similar to your .o file, and is a compiled java archive.
If you wanted to see the code in a jar file, download a java decompiler (located here: http://java.decompiler.free.fr/?q=jdgui) and a .jar extractor (7zip works fine).
You're misunderstanding the meaning of the merge here.
The --no-commit
prevents the MERGE COMMIT from occuring, and that only happens when you merge two divergent branch histories; in your example that's not the case since Git indicates that it was a "fast-forward" merge and then Git only applies the commits already present on the branch sequentially.
You can also let Square's Picasso library do the heavy lifting:
Picasso
.get()
.load("http://...")
.into(imageView);
As a bonus, you get caching, transformations, and more.
You can try something like this
IFNULL(NULLIF(X, '' ), 0)
Attribute X is assumed to be empty if it is an empty String, so after that you can declare as a zero instead of last value. In another case, it would remain its original value.
Anyway, just to give another way to do that.
Using Moshi:
When building your Retrofit Service add .asLenient() to your MoshiConverterFactory. You don't need a ScalarsConverter. It should look something like this:
return Retrofit.Builder()
.client(okHttpClient)
.baseUrl(ENDPOINT)
.addConverterFactory(MoshiConverterFactory.create().asLenient())
.build()
.create(UserService::class.java)
console.log( Object.keys( {'a':1,'b':2} ) );
The basic difference is the syntax. While SASS has a loose syntax with white space and no semicolons, the SCSS resembles more to CSS.
<RelativeLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="30dp">
<com.facebook.login.widget.LoginButton
xmlns:facebook="http://schemas.android.com/apk/res-auto"
android:id="@+id/login_button"
android:layout_width="300dp"
android:layout_height="100dp"
android:paddingTop="15dp"
android:paddingBottom="15dp" />
<LinearLayout
android:id="@+id/llfbSignup"
android:layout_width="300dp"
android:layout_height="50dp"
android:background="@drawable/facebook"
android:layout_gravity="center_horizontal"
android:orientation="horizontal">
<ImageView
android:layout_width="30dp"
android:layout_height="30dp"
android:src="@drawable/facbk"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp" />
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:background="@color/fullGray"
android:layout_marginLeft="10dp"/>
<com.yadav.bookedup.fonts.GoutamBold
android:layout_width="240dp"
android:layout_height="50dp"
android:text="Sign Up via Facebook"
android:gravity="center"
android:textColor="@color/white"
android:textSize="18dp"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"/>
</LinearLayout>
</RelativeLayout>
For anyone trying to do this in asp.net core. You can use claims.
public class CustomEmailProvider : IUserIdProvider
{
public virtual string GetUserId(HubConnectionContext connection)
{
return connection.User?.FindFirst(ClaimTypes.Email)?.Value;
}
}
Any identifier can be used, but it must be unique. If you use a name identifier for example, it means if there are multiple users with the same name as the recipient, the message would be delivered to them as well. I have chosen email because it is unique to every user.
Then register the service in the startup class.
services.AddSingleton<IUserIdProvider, CustomEmailProvider>();
Next. Add the claims during user registration.
var result = await _userManager.CreateAsync(user, Model.Password);
if (result.Succeeded)
{
await _userManager.AddClaimAsync(user, new Claim(ClaimTypes.Email, Model.Email));
}
To send message to the specific user.
public class ChatHub : Hub
{
public async Task SendMessage(string receiver, string message)
{
await Clients.User(receiver).SendAsync("ReceiveMessage", message);
}
}
Note: The message sender won't be notified the message is sent. If you want a notification on the sender's end. Change the SendMessage
method to this.
public async Task SendMessage(string sender, string receiver, string message)
{
await Clients.Users(sender, receiver).SendAsync("ReceiveMessage", message);
}
These steps are only necessary if you need to change the default identifier. Otherwise, skip to the last step where you can simply send messages by passing userIds or connectionIds to SendMessage
. For more
try below approach, very simple easy to implement
Below is the jsfiddle link
http://jsfiddle.net/v2t2k8ke/2/
HTML:
<table border='1' id='tbl_cnt'>
<thead><tr></tr></thead><tbody></tbody>
CSS:
#tbl_cnt{
border-collapse: collapse; width: 100%;word-break:break-all;
}
#tbl_cnt thead, #tbl_cnt tbody{
display: block;
}
#tbl_cnt thead tr{
background-color: #8C8787; text-align: center;width:100%;display:block;
}
#tbl_cnt tbody {
height: 100px;overflow-y: auto;overflow-x: hidden;
}
Jquery:
var data = [
{
"status":"moving","vehno":"tr544","loc":"bng","dri":"ttt"
}, {
"status":"stop","vehno":"tr54","loc":"che", "dri":"ttt"
},{ "status":"idle","vehno":"yy5499999999999994","loc":"bng","dri":"ttt"
},{
"status":"moving","vehno":"tr544","loc":"bng", "dri":"ttt"
}, {
"status":"stop","vehno":"tr54","loc":"che","dri":"ttt"
},{
"status":"idle","vehno":"yy544","loc":"bng","dri":"ttt"
}
];
var sth = '';
$.each(data[0], function (key, value) {
sth += '<td>' + key + '</td>';
});
var stb = '';
$.each(data, function (key, value) {
stb += '<tr>';
$.each(value, function (key, value) {
stb += '<td>' + value + '</td>';
});
stb += '</tr>';
});
$('#tbl_cnt thead tr').append(sth);
$('#tbl_cnt tbody').append(stb);
setTimeout(function () {
var col_cnt=0
$.each(data[0], function (key, value) {col_cnt++;});
$('#tbl_cnt thead tr').css('width', ($("#tbl_cnt tbody") [0].scrollWidth)+ 'px');
$('#tbl_cnt thead tr td,#tbl_cnt tbody tr td').css('width', ($('#tbl_cnt thead tr ').width()/Number(col_cnt)) + 'px');}, 100)
Using iconv looks like best solution but i my case I have Notice form this function: "Detected an illegal character in input string in" (without igonore). I use 2 functions to manipulate ASCII strings convert it to array of ASCII code and then serialize:
public static function ToAscii($string) {
$strlen = strlen($string);
$charCode = array();
for ($i = 0; $i < $strlen; $i++) {
$charCode[] = ord(substr($string, $i, 1));
}
$result = json_encode($charCode);
return $result;
}
public static function fromAscii($string) {
$charCode = json_decode($string);
$result = '';
foreach ($charCode as $code) {
$result .= chr($code);
};
return $result;
}
use this method:
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText(label, text);
clipboard.setPrimaryClip(clip);
at the place of setPrimaryClip we can also use the following methods:
void clearPrimaryClip()
Clears any current primary clip on the clipboard.
ClipData getPrimaryClip()
Returns the current primary clip on the clipboard.
ClipDescription getPrimaryClipDescription()
Returns a description of the current primary clip on the clipboard but not a copy of its data.
CharSequence getText()
This method is deprecated. Use getPrimaryClip() instead. This retrieves the primary clip and tries to coerce it to a string.
boolean hasPrimaryClip()
Returns true if there is currently a primary clip on the clipboard.
In VS2017. I had to edit my .sln file and had to update the VWDPort = "5010" setting. None of the other solutions posted here worked.
It's interesting that not a single answer mentioned parallel processing so far, where it might be REQUIRED that the imports are in the function, when the serialized function code is what is being pushed around to other cores, e.g. like in the case of ipyparallel.
There is a way to convert upper case to lower WITHOUT doing if tests, and it's pretty straight-forward. The isupper() function/macro's use of clocale.h should take care of problems relating to your location, but if not, you can always tweak the UtoL[] to your heart's content.
Given that C's characters are really just 8-bit ints (ignoring the wide character sets for the moment) you can create a 256 byte array holding an alternative set of characters, and in the conversion function use the chars in your string as subscripts into the conversion array.
Instead of a 1-for-1 mapping though, give the upper-case array members the BYTE int values for the lower-case characters. You may find islower() and isupper() useful here.
The code looks like this...
#include <clocale>
static char UtoL[256];
// ----------------------------------------------------------------------------
void InitUtoLMap() {
for (int i = 0; i < sizeof(UtoL); i++) {
if (isupper(i)) {
UtoL[i] = (char)(i + 32);
} else {
UtoL[i] = i;
}
}
}
// ----------------------------------------------------------------------------
char *LowerStr(char *szMyStr) {
char *p = szMyStr;
// do conversion in-place so as not to require a destination buffer
while (*p) { // szMyStr must be null-terminated
*p = UtoL[*p];
p++;
}
return szMyStr;
}
// ----------------------------------------------------------------------------
int main() {
time_t start;
char *Lowered, Upper[128];
InitUtoLMap();
strcpy(Upper, "Every GOOD boy does FINE!");
Lowered = LowerStr(Upper);
return 0;
}
This approach will, at the same time, allow you to remap any other characters you wish to change.
This approach has one huge advantage when running on modern processors, there is no need to do branch prediction as there are no if tests comprising branching. This saves the CPU's branch prediction logic for other loops, and tends to prevent pipeline stalls.
Some here may recognize this approach as the same one used to convert EBCDIC to ASCII.
#include <stdio.h>
#include "opencv.hpp"
int main(){
CvCapture *camera=cvCaptureFromFile("http://username:pass@cam_address/axis-cgi/mjpg/video.cgi?resolution=640x480&req_fps=30&.mjpg");
if (camera==NULL)
printf("camera is null\n");
else
printf("camera is not null");
cvNamedWindow("img");
while (cvWaitKey(10)!=atoi("q")){
double t1=(double)cvGetTickCount();
IplImage *img=cvQueryFrame(camera);
double t2=(double)cvGetTickCount();
printf("time: %gms fps: %.2g\n",(t2-t1)/(cvGetTickFrequency()*1000.), 1000./((t2-t1)/(cvGetTickFrequency()*1000.)));
cvShowImage("img",img);
}
cvReleaseCapture(&camera);
}
Or in php >= 7.3.0
you can use the function array_key_last()
As described in php.net โ Gets the last key of an array
From Linux Terminal:
adb shell getprop | grep "model\|version.sdk\|manufacturer\|hardware\|platform\|revision\|serialno\|product.name\|brand"
From Windows PowerShell:
adb shell
getprop | grep -e 'model' -e 'version.sdk' -e 'manufacturer' -e 'hardware' -e 'platform' -e 'revision' -e 'serialno' -e 'product.name' -e 'brand'
Sample output for Samsung:
[gsm.version.baseband]: [G900VVRU2BOE1]
[gsm.version.ril-impl]: [Samsung RIL v3.0]
[net.knoxscep.version]: [2.0.1]
[net.knoxsso.version]: [2.1.1]
[net.knoxvpn.version]: [2.2.0]
[persist.service.bdroid.version]: [4.1]
[ro.board.platform]: [msm8974]
[ro.boot.hardware]: [qcom]
[ro.boot.serialno]: [xxxxxx]
[ro.build.version.all_codenames]: [REL]
[ro.build.version.codename]: [REL]
[ro.build.version.incremental]: [G900VVRU2BOE1]
[ro.build.version.release]: [5.0]
[ro.build.version.sdk]: [21]
[ro.build.version.sdl]: [2101]
[ro.com.google.gmsversion]: [5.0_r2]
[ro.config.timaversion]: [3.0]
[ro.hardware]: [qcom]
[ro.opengles.version]: [196108]
[ro.product.brand]: [Verizon]
[ro.product.manufacturer]: [samsung]
[ro.product.model]: [SM-G900V]
[ro.product.name]: [kltevzw]
[ro.revision]: [14]
[ro.serialno]: [e5ce97c7]
I've used Sothink SWF decompiler a couple of times, the only problem is that as project gets more complex, the output of decompiler gets harder to compile back again. But it ensures that you can get your .as files most of the time, compilable fla is a question.
When clicking on the button for search you can find it without a loop.
Just add to the option an attribute with the value you need (like id
) and search for it specific.
$('#search_wrapper button').on('click', function(){
console.log($('option[value="'+
$('#autocomplete_input').val() +'"]').data('value'));
})
Nothing printed. The argument must be a pointer to a signed int, where the number of characters written so far is stored.
#include <stdio.h>
int main()
{
int val;
printf("blah %n blah\n", &val);
printf("val = %d\n", val);
return 0;
}
The previous code prints:
blah blah
val = 5
You can do it with this code:
ints = [8, 23, 45, 12, 78]
index = 0
for value in (ints):
index +=1
print index, value
Use this code if you need to reset the index value at the end of the loop:
ints = [8, 23, 45, 12, 78]
index = 0
for value in (ints):
index +=1
print index, value
if index >= len(ints)-1:
index = 0
You can use the asXML method
echo $xml->asXML();
You can also give it a filename
$xml->asXML('filename.xml');
To turn a 2D JavaScript array into an HTML table, you really need but a little bit of code :
function arrayToTable(tableData) {_x000D_
var table = $('<table></table>');_x000D_
$(tableData).each(function (i, rowData) {_x000D_
var row = $('<tr></tr>');_x000D_
$(rowData).each(function (j, cellData) {_x000D_
row.append($('<td>'+cellData+'</td>'));_x000D_
});_x000D_
table.append(row);_x000D_
});_x000D_
return table;_x000D_
}_x000D_
_x000D_
$('body').append(arrayToTable([_x000D_
["John","Slegers",34],_x000D_
["Tom","Stevens",25],_x000D_
["An","Davies",28],_x000D_
["Miet","Hansen",42],_x000D_
["Eli","Morris",18]_x000D_
]));
_x000D_
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
_x000D_
If you want to load your 2D array from a JSON file, you'll also need a little bit of Ajax code :
$.ajax({
type: "GET",
url: "data.json",
dataType: 'json',
success: function (data) {
$('body').append(arrayToTable(data));
}
});
Unless you have more style sheets than that, you've messed up your break points:
#1 (max-width: 700px)
#2 (min-width: 701px) and (max-width: 900px)
#3 (max-width: 901px)
The 3rd media query is probably meant to be min-width: 901px
. Right now, it overlaps #1 and #2, and only controls the page layout by itself when the screen is exactly 901px wide.
Edit for updated question:
(max-width: 640px)
(max-width: 800px)
(max-width: 1024px)
(max-width: 1280px)
Media queries aren't like catch or if/else statements. If any of the conditions match, then it will apply all of the styles from each media query it matched. If you only specify a min-width
for all of your media queries, it's possible that some or all of the media queries are matched. In your case, a device that's 640px wide matches all 4 of your media queries, so all for style sheets are loaded. What you are most likely looking for is this:
(max-width: 640px)
(min-width: 641px) and (max-width: 800px)
(min-width: 801px) and (max-width: 1024px)
(min-width: 1025px)
Now there's no overlap. The styles will only apply if the device's width falls between the widths specified.
Matter of style, but as Matt said, definitely consider marking constructors with default arguments which would allow implicit conversion as 'explicit' to avoid unintended automatic conversion. It's not a requirement (and may not be preferable if you're making a wrapper class which you want to implicitly convert to), but it can prevent errors.
I personally like defaults when appropriate, because I dislike repeated code. YMMV.
The only other difference is the default inheritance of classes and structs, which, unsurprisingly, is private and public respectively.
I'm using this tutorial and it works nicely for my application.
In my activity I put this code:
GPSTracker tracker = new GPSTracker(this);
if (!tracker.canGetLocation()) {
tracker.showSettingsAlert();
} else {
latitude = tracker.getLatitude();
longitude = tracker.getLongitude();
}
also check if your emulator runs with Google API
MS-Access doesn't support ROW_NUMBER(). Use TOP 1:
SELECT TOP 1 *
FROM [MyTable]
ORDER BY [MyIdentityCOlumn]
If you need the 15th row - MS-Access has no simple, built-in, way to do this. You can simulate the rownumber by using reverse nested ordering to get this:
SELECT TOP 1 *
FROM (
SELECT TOP 15 *
FROM [MyTable]
ORDER BY [MyIdentityColumn] ) t
ORDER BY [MyIdentityColumn] DESC
Use parse_url()
like this:
function url(){
if(isset($_SERVER['HTTPS'])){
$protocol = ($_SERVER['HTTPS'] && $_SERVER['HTTPS'] != "off") ? "https" : "http";
}
else{
$protocol = 'http';
}
return $protocol . "://" . parse_url($_SERVER['REQUEST_URI'], PHP_URL_HOST);
}
Here is another shorter option:
function url(){
$pu = parse_url($_SERVER['REQUEST_URI']);
return $pu["scheme"] . "://" . $pu["host"];
}
You should only need to do one of:
inline
(or inline-block
)float
left or rightYou should be able to adjust the height
, padding
, or margin
properties of the smaller heading to compensate for its positioning. I recommend setting both headings to have the same height
.
See this live jsFiddle for an example.
(code of the jsFiddle):
CSS
h2 {
font-size: 50px;
}
h3 {
font-size: 30px;
}
h2, h3 {
width: 50%;
height: 60px;
margin: 0;
padding: 0;
display: inline;
}?
HTML
<h2>Big Heading</h2>
<h3>Small(er) Heading</h3>
<hr />?
The difference is second parameter. Their second parameters, while both numbers, are expecting two different things:
When using substring the second parameter is the first index not to include:
var s = "string";
s.substring(1, 3); // would return 'tr'
var s = "another example";
s.substring(3, 7); // would return 'ther'
When using substr the second parameter is the number of characters to include in the substring:
var s = "string";
s.substr(1, 3); // would return 'tri'
var s = "another example";
s.substr(3, 7); // would return 'ther ex'
"12".match(/^(\d)+$/) # true
"1.2".match(/^(\d)+$/) # false
"dfs2".match(/^(\d)+$/) # false
"13422".match(/^(\d)+$/) # true
It is possible to set autofocus
on input elements
<input type="text" class="b_calle" id="b_calle" placeholder="Buscar por nombre de calle" autofocus="autofocus">
sudo mysql
enter your (LINUX) account password
grant create on *.* to user@localhost;
FLUSH PRIVILEGES;
This is not really related but if I was to asynchronously call a method e.g. matches(), I would use:
private final static ExecutorService service = Executors.newFixedThreadPool(10);
public static Future<Boolean> matches(final String x, final String y) {
return service.submit(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return x.matches(y);
}
});
}
Then to call the asynchronous method I would use:
String x = "somethingelse";
try {
System.out.println("Matches: "+matches(x, "something").get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
I have tested this and it works. Just thought it may help others if they just came for the "asynchronous method".
I post my final way of doing it based on the accepted answer:
@SuppressWarnings("serial")
@WebServlet("/")
@MultipartConfig
public final class DataCollectionServlet extends Controller {
private static final String UPLOAD_LOCATION_PROPERTY_KEY="upload.location";
private String uploadsDirName;
@Override
public void init() throws ServletException {
super.init();
uploadsDirName = property(UPLOAD_LOCATION_PROPERTY_KEY);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// ...
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Collection<Part> parts = req.getParts();
for (Part part : parts) {
File save = new File(uploadsDirName, getFilename(part) + "_"
+ System.currentTimeMillis());
final String absolutePath = save.getAbsolutePath();
log.debug(absolutePath);
part.write(absolutePath);
sc.getRequestDispatcher(DATA_COLLECTION_JSP).forward(req, resp);
}
}
// helpers
private static String getFilename(Part part) {
// courtesy of BalusC : http://stackoverflow.com/a/2424824/281545
for (String cd : part.getHeader("content-disposition").split(";")) {
if (cd.trim().startsWith("filename")) {
String filename = cd.substring(cd.indexOf('=') + 1).trim()
.replace("\"", "");
return filename.substring(filename.lastIndexOf('/') + 1)
.substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
}
}
return null;
}
}
where :
@SuppressWarnings("serial")
class Controller extends HttpServlet {
static final String DATA_COLLECTION_JSP="/WEB-INF/jsp/data_collection.jsp";
static ServletContext sc;
Logger log;
// private
// "/WEB-INF/app.properties" also works...
private static final String PROPERTIES_PATH = "WEB-INF/app.properties";
private Properties properties;
@Override
public void init() throws ServletException {
super.init();
// synchronize !
if (sc == null) sc = getServletContext();
log = LoggerFactory.getLogger(this.getClass());
try {
loadProperties();
} catch (IOException e) {
throw new RuntimeException("Can't load properties file", e);
}
}
private void loadProperties() throws IOException {
try(InputStream is= sc.getResourceAsStream(PROPERTIES_PATH)) {
if (is == null)
throw new RuntimeException("Can't locate properties file");
properties = new Properties();
properties.load(is);
}
}
String property(final String key) {
return properties.getProperty(key);
}
}
and the /WEB-INF/app.properties :
upload.location=C:/_/
HTH and if you find a bug let me know
Here is what I use.
Write-Host -NoNewLine 'Press any key to continue...';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');
You normally forward the request to a JSP for display. JSP is a view technology which provides a template to write plain vanilla HTML/CSS/JS in and provides ability to interact with backend Java code/variables with help of taglibs and EL. You can control the page flow with taglibs like JSTL. You can set any backend data as an attribute in any of the request, session or application scope and use EL (the ${}
things) in JSP to access/display them. You can put JSP files in /WEB-INF
folder to prevent users from directly accessing them without invoking the preprocessing servlet.
Kickoff example:
@WebServlet("/hello")
public class HelloWorldServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String message = "Hello World";
request.setAttribute("message", message); // This will be available as ${message}
request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response);
}
}
And /WEB-INF/hello.jsp
look like:
<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 2370960</title>
</head>
<body>
<p>Message: ${message}</p>
</body>
</html>
When opening http://localhost:8080/contextpath/hello this will show
Message: Hello World
in the browser.
This keeps the Java code free from HTML clutter and greatly improves maintainability. To learn and practice more with servlets, continue with below links.
Also browse the "Frequent" tab of all questions tagged [servlets] to find frequently asked questions.
If the new branch contains edits that are different from the current branch for that particular changed file, then it will not allow you to switch branches until the change is committed or stashed. If the changed file is the same on both branches (that is, the committed version of that file), then you can switch freely.
Example:
$ echo 'hello world' > file.txt
$ git add file.txt
$ git commit -m "adding file.txt"
$ git checkout -b experiment
$ echo 'goodbye world' >> file.txt
$ git add file.txt
$ git commit -m "added text"
# experiment now contains changes that master doesn't have
# any future changes to this file will keep you from changing branches
# until the changes are stashed or committed
$ echo "and we're back" >> file.txt # making additional changes
$ git checkout master
error: Your local changes to the following files would be overwritten by checkout:
file.txt
Please, commit your changes or stash them before you can switch branches.
Aborting
This goes for untracked files as well as tracked files. Here's an example for an untracked file.
Example:
$ git checkout -b experimental # creates new branch 'experimental'
$ echo 'hello world' > file.txt
$ git add file.txt
$ git commit -m "added file.txt"
$ git checkout master # master does not have file.txt
$ echo 'goodbye world' > file.txt
$ git checkout experimental
error: The following untracked working tree files would be overwritten by checkout:
file.txt
Please move or remove them before you can switch branches.
Aborting
A good example of why you WOULD want to move between branches while making changes would be if you were performing some experiments on master, wanted to commit them, but not to master just yet...
$ echo 'experimental change' >> file.txt # change to existing tracked file
# I want to save these, but not on master
$ git checkout -b experiment
M file.txt
Switched to branch 'experiment'
$ git add file.txt
$ git commit -m "possible modification for file.txt"
According to the documentation NUM_ROWS is the "Number of rows in the table", so I can see how this might be confusing. There, however, is a major difference between these two methods.
This query selects the number of rows in MY_TABLE from a system view. This is data that Oracle has previously collected and stored.
select num_rows from all_tables where table_name = 'MY_TABLE'
This query counts the current number of rows in MY_TABLE
select count(*) from my_table
By definition they are difference pieces of data. There are two additional pieces of information you need about NUM_ROWS.
In the documentation there's an asterisk by the column name, which leads to this note:
Columns marked with an asterisk (*) are populated only if you collect statistics on the table with the ANALYZE statement or the DBMS_STATS package.
This means that unless you have gathered statistics on the table then this column will not have any data.
Statistics gathered in 11g+ with the default estimate_percent
, or with a 100% estimate, will return an accurate number for that point in time. But statistics gathered before 11g, or with a custom estimate_percent
less than 100%, uses dynamic sampling and may be incorrect. If you gather 99.999% a single row may be missed, which in turn means that the answer you get is incorrect.
If your table is never updated then it is certainly possible to use ALL_TABLES.NUM_ROWS to find out the number of rows in a table. However, and it's a big however, if any process inserts or deletes rows from your table it will be at best a good approximation and depending on whether your database gathers statistics automatically could be horribly wrong.
Generally speaking, it is always better to actually count the number of rows in the table rather then relying on the system tables.
Just to enforce @phreakhead ยดs and user1051892 ยดs answers, <item android:bottom|android:left|android:right|android:top>
if negative, must to be greater than <stroke android:width>
. If not, itemยดs painting will be mixed with strokeยดs painting and you may think these values are not working.
The difference of Read(),ReadLine() and Readkey() method are given below:
Read():This is static method in Console class:
int i = Console.Read();//it always return int value.
Console.WriteLine(i);
paste above code and give input '1', and the output will be 49. That is Console.Read give int value but that value will be the ASCII value of that.
ReadLine():
string s= Console.ReadLine();//it always return string value.
Console.WriteLine(s);
It gives the string as it is given in the input stream.
ReadKey(): this method is used to hold the output screen.when any key is press. Read() and ReadLine() is used the enter key for exit.
Try this:
update table YourTable
set YourField = substring(YourField, 5, len(YourField)-3);
Hackbod's is one of the best answers on Stack Overflow. It throws light on a very obscure subject. It helped me a lot.
Another really helpful resource is this must-see video: Google I/O 2011: Memory management for Android Apps
UPDATE:
Process Stats, a service to discover how your app manages memory explained at the blog post Process Stats: Understanding How Your App Uses RAM by Dianne Hackborn:
In Kotlin you can use extensions as below:
fun String.toDoubleEx() : Double {
val decimalSymbol = DecimalFormatSymbols.getInstance().decimalSeparator
return if (decimalSymbol == ',') {
this.replace(decimalSymbol, '.').toDouble()
} else {
this.toDouble()
}
}
and you can use it everywhere in your code like this:
val myNumber1 = "5,2"
val myNumber2 = "6.7"
val myNum1 = myNumber1.toDoubleEx()
val myNum2 = myNumber2.toDoubleEx()
It is easy and universal!
The key thing to understand in Java is that Strings are immutable -- you can't change them. So it makes no sense to speak of 'removing a character from a string'. Instead, you make a NEW string with just the characters you want. The other posts in this question give you a variety of ways of doing that, but its important to understand that these don't change the original string in any way. Any references you have to the old string will continue to refer to the old string (unless you change them to refer to a different string) and will not be affected by the newly created string.
This has a number of implications for performance. Each time you are 'modifying' a string, you are actually creating a new string with all the overhead implied (memory allocation and garbage collection). So if you want to make a series of modifications to a string and care only about the final result (the intermediate strings will be dead as soon as you 'modify' them), it may make more sense to use a StringBuilder or StringBuffer instead.
To be totally exhaustive, things are different if you're using a JPA 1.0 or a JPA 2.0 implementation.
With JPA 1.0, you'd have to use EntityManager#getDelegate()
. But keep in mind that the result of this method is implementation specific i.e. non portable from application server using Hibernate to the other. For example with JBoss you would do:
org.hibernate.Session session = (Session) manager.getDelegate();
But with GlassFish, you'd have to do:
org.hibernate.Session session = ((org.hibernate.ejb.EntityManagerImpl) em.getDelegate()).getSession();
I agree, that's horrible, and the spec is to blame here (not clear enough).
With JPA 2.0, there is a new (and much better) EntityManager#unwrap(Class<T>)
method that is to be preferred over EntityManager#getDelegate()
for new applications.
So with Hibernate as JPA 2.0 implementation (see 3.15. Native Hibernate API), you would do:
Session session = entityManager.unwrap(Session.class);
Resolve is also more straightforward
from django.urls import resolve
resolve('edit_project', project_id=4)
Please check below javascript in IE. Don't know if other modern browser will work or not.
<html>
<head>
<script type="text/javascript">
function OpenOutlookDoc(){
try {
var outlookApp = new ActiveXObject("Outlook.Application");
var nameSpace = outlookApp.getNameSpace("MAPI");
mailFolder = nameSpace.getDefaultFolder(6);
mailItem = mailFolder.Items.add('IPM.Note.FormA');
mailItem.Subject="a subject test";
mailItem.To = "[email protected]";
mailItem.HTMLBody = "<b>bold</b>";
mailItem.display (0);
}
catch(e){
alert(e);
// act on any error that you get
}
}
</script>
</head>
<body>
<a href="javascript:OpenOutlookDoc()">Click</a>
</body>
</html>
try something like
background: url(bgimage.jpg) no-repeat;
background-size: 100%;
The SQL is somewhat like the syntax of MS SQL.
SELECT * FROM [table$] WHERE *;
It is important that the table name is ended with a $ sign and the whole thing is put into brackets. As conditions you can use any value, but so far Excel didn't allow me to use what I call "SQL Apostrophes" (ยด), so a column title in one word is recommended.
If you have users listed in a table called "Users", and the id is in a column titled "id" and the name in a column titled "Name", your query will look like this:
SELECT Name FROM [Users$] WHERE id = 1;
Hope this helps.
First,
sudo apt-get install libusb-1.0-0-dev
updatedb && locate libusb.h.
Second, replace <libusb.h>
with <libusb-1.0/libusb.h>
.
update:
don't need to change any file.just add this to your Makefile.
`pkg-config libusb-1.0 --libs --cflags`
its result is that -I/usr/include/libusb-1.0 -lusb-1.0
SELECT MAX(salary) salary
FROM tbl
WHERE salary <
(SELECT MAX(salary)
FROM tbl);
For curl
, how about using the -d
switch? Like: curl -X PUT "localhost:8080/urlstuffhere" -d "@filename"
?
Ctrl + R - to open the command line and then writes:
node -v
You can put a second element inside the element you wish to have a transparent background on.
<div class="container">
<div class="container-background"></div>
<div class="content">
Yay, happy content!
</div>
</div>
Then make the '.container-background' positioned absolutely to cover the parent element. At this point you'll be able to adjust the opacity of it without affecting the opacity of the content inside '.container'.
.container {
position: relative;
}
.container .container-background {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: url(background.png);
opacity: 0.5;
}
.container .content {
position: relative;
z-index: 1;
}
Replace following
curl_setopt ($setuploginurl, CURLOPT_SSLVERSION, 'CURL_SSLVERSION_TLSv1_2');
With
curl_setopt ($ch, CURLOPT_SSLVERSION, 6);
Should work flawlessly.
I have the same issue with Entity Framework 6.1.3
But with different scenario. My model property is of type nullable DateTime
DateTime? CreatedDate { get; set; }
So I need to query on today's date to check all the record, so this what works for me. Which means I need to truncate both records to get the proper query on DbContext
:
Where(w => DbFunctions.TruncateTime(w.CreatedDate) == DbFunctions.TruncateTime(DateTime.Now);
I had trouble with a crashing program *cough PHP cough* Upon crash the shell it was ran in reports the crash reason, Segmentation fault (core dumped)
To avoid this output not getting logged, the command can be run in a subshell that will capture and direct these kind of output:
sh -c 'your_command' > your_stdout.log 2> your_stderr.err
# or
sh -c 'your_command' > your_stdout.log 2>&1
Rendering didn't work for me too. I had <null>
value on the right side of the android icon. I ran
sudo apt-get install gradle
I restarted Android studio then and <null>
value changed to 23
.
Voila, it renders now! :)
Include this setting in xampp my.ini configuration file:
[mysqld]
group_concat_max_len = 1000000
Then restart xampp mysql
Take a look at Array.slice(begin, end)
const ar = [1, 2, 3, 4, 5];
// slice from 1..3 - add 1 as the end index is not included
const ar2 = ar.slice(1, 3 + 1);
console.log(ar2);
_x000D_
Function that will tokenize string into two parts, first word and remaining string.
Return Value: It will have first
and remaining
key in $return
array respectively.
first check strpos( $title," ") !== false
is mandatory in case when string has only one word and no space in it.
function getStringFirstWord( $title ){
$return = [];
if( strpos( $title," ") !== false ) {
$firstWord = strstr($title," ",true);
$remainingTitle = substr(strstr($title," "), 1);
if( !empty( $firstWord ) ) {
$return['first'] = $firstWord;
}
if( !empty( $remainingTitle ) ) {
$return['remaining'] = $remainingTitle;
}
}
else {
$return['first'] = $title;
}
return $return;
}
Only "keyboard focusable" elements can be focused with .focus()
. div
aren't meant to be natively focusable. You have to add tabindex="0"
attributes to it to achieve that. input
, button
, a
etc... are natively focusable.
In 2021 - use ES6 Template Literals for this task. If you need IE11 Support - use a transpiler.
let a = `something something`;
Template Literals are fast, powerful and produce cleaner code.
If you need IE11 support and you don't have transpiler, stay strong and use \xa0
- it is a NO-BREAK SPACE char.
Reference from UTF-8 encoding table and Unicode characters, you can write as below:
var a = 'something' + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0' + 'something';
Static libraries do not link with other static libraries. The only way to do this is to use your librarian/archiver tool (for example ar on Linux) to create a single new static library by concatenating the multiple libraries.
Edit: In response to your update, the only way I know to select only the symbols that are required is to manually create the library from the subset of the .o files that contain them. This is difficult, time consuming and error prone. I'm not aware of any tools to help do this (not to say they don't exist), but it would make quite an interesting project to produce one.
I make a link. A link is a link. A link navigates to another page. That is what links are for and everybody understands that. So Method 3 is the only correct method in my book.
I wouldn't want my link to look like a button at all, and when I do, I still think functionality is more important than looks.
Buttons are less accessible, not only due to the need of Javascript, but also because tools for the visually impaired may not understand this Javascript enhanced button well.
Method 4 would work as well, but it is more a trick than a real functionality. You abuse a form to post 'nothing' to this other page. It's not clean.
For me, I had simply forgotten to enter the actual domain name in the "Key Settings" area where it says Domains (one per line).
Rdocumentation.org has a very handy search function that - among other things - lets you find functions - from all the packages on CRAN, as well as from packages from Bioconductor and GitHub.
Use sortedWith
to sort a list with Comparator
.
You can then construct a comparator using several ways:
Assuming Bootstrap and Popper libraries were installed using Nuget package manager, for a web application using Visual Studio, in the Master page file (Site.Master), right below where body tag begins, include the reference to popper.min.js by typing:
<script src="Scripts/umd/popper.min.js"></script>
Here is an image to better display the location:
Notice the reference of the popper library to be added should be the one inside umd folder and not the one outside on Scripts folder.
This should fix the problem.
In order to get proper responses back from async methods, you need to put await while calling those task methods. That will wait for converting it back to the returned value type rather task type.
E.g var content = await StringAsyncTask (
where public async Task<String> StringAsyncTask ())
Looking through the answers, we have seen a lot of back and forth, whether or not list comprehension or filter may be faster or if it is even important or pythonic to care about such an issue. In the end, the answer is as most times: it depends.
I just stumbled across this question while optimizing code where this exact question (albeit combined with an in
expression, not ==
) is very relevant - the filter
+ lambda
expression is taking up a third of my computation time (of multiple minutes).
In my case, the list comprehension is much faster (twice the speed). But I suspect that this varies strongly based on the filter expression as well as the Python interpreter used.
Here is a simple code snippet that should be easy to adapt. If you profile it (most IDEs can do that easily), you will be able to easily decide for your specific case which is the better option:
whitelist = set(range(0, 100000000, 27))
input_list = list(range(0, 100000000))
proximal_list = list(filter(
lambda x: x in whitelist,
input_list
))
proximal_list2 = [x for x in input_list if x in whitelist]
print(len(proximal_list))
print(len(proximal_list2))
If you do not have an IDE that lets you profile easily, try this instead (extracted from my codebase, so a bit more complicated). This code snippet will create a profile for you that you can easily visualize using e.g. snakeviz:
import cProfile
from time import time
class BlockProfile:
def __init__(self, profile_path):
self.profile_path = profile_path
self.profiler = None
self.start_time = None
def __enter__(self):
self.profiler = cProfile.Profile()
self.start_time = time()
self.profiler.enable()
def __exit__(self, *args):
self.profiler.disable()
exec_time = int((time() - self.start_time) * 1000)
self.profiler.dump_stats(self.profile_path)
whitelist = set(range(0, 100000000, 27))
input_list = list(range(0, 100000000))
with BlockProfile("/path/to/create/profile/in/profile.pstat"):
proximal_list = list(filter(
lambda x: x in whitelist,
input_list
))
proximal_list2 = [x for x in input_list if x in whitelist]
print(len(proximal_list))
print(len(proximal_list2))
Let me make a conclusion. In Swift 5
You can choose to addSubview to keyWindow, if you add the view in the last. Otherwise, you can bringSubViewToFront.
let view = UIView()
UIApplication.shared.keyWindow?.addSubview(view)
UIApplication.shared.keyWindow?.bringSubviewToFront(view)
You can also set the zPosition. But the drawback is that you can not change the gesture responding order.
view.layer.zPosition = 1
The issue could be with the response you are receiving from back-end. If it was working fine on the server then the problem could be with the response headers. Check the Access-Control-Allow-Origin (ACAO) in the response headers. Usually react's fetch API will throw fail to fetch even after receiving response when the response headers' ACAO and the origin of request won't match.
This project on github may be your solution
When you define a server in server view, then it will create you a server runtime library with server libs (including servlet api), that can be assigned to your project. However, then everybody that uses your project, need to create the same type of runtime in his/her eclipse workspace even for compiling.
If you directly download the servlet api jar, than it could lead to problems, since it will be included into the artifacts of your projects, but will be also present in servlet container.
In Maven it is much nicer, since you can define the servlet api interfaces as a "provided" dependency, that means it is present in the "to be production" environment.
The REST API of Instagram has been discontinued. But you can use GraphQL to get the desired data. Here you can find an overview: https://developers.facebook.com/docs/instagram-api
JSONArray jsonChildArray = (JSONArray) jsonChildArray.get("LanguageLevels");
JSONObject secObject = (JSONObject) jsonChildArray.get(1);
I think this should work, but i do not have the possibility to test it at the moment..
Perhaps you want to do
soup.find("li", { "class" : "test" }).find('a')
This is a general issue, and doesn't appear in a single case. But, the common problem in all the cases is that you forget to import
a specific component (doesn't matter if it's either from a library that you installed or a custom made component that you created):
import {SomeClass} from 'some-library'
When you use it later, without importing it, the compiler thinks it's a function. Therefore, it breaks. This is a common example:
imports
...code...
and then somewhere inside your code
<Image {..some props} />
If you forgot to import the component <Image />
then the compiler will not complain like it does for other imports, but will break when it reaches your code.
If anyone needs the registry entries for Windows 7 64-bit, here they are. What was good for me as to remove the overlays for items not really used often: Drop Box, Google Drive, Microsoft Products, and just kept the overlays for Tortoise. These are all the overlays - nothing is removed.
** Caution ** Playing with the registry can make your system unstable. Be sure to backup your registry. See this Google search on various ways to backup your registry or registry setting(s).
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers]
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers\ AccExtIco1]
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers\ AccExtIco2]
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers\ AccExtIco3]
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers\ SkyDrivePro1 (ErrorConflict)]
@="{8BA85C75-763B-4103-94EB-9470F12FE0F7}"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers\ SkyDrivePro2 (SyncInProgress)]
@="{CD55129A-B1A1-438E-A425-CEBC7DC684EE}"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers\ SkyDrivePro3 (InSync)]
@="{E768CD3B-BDDC-436D-9C13-E1B39CA257B1}"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers\"DropboxExt1"]
@="{FB314ED9-A251-47B7-93E1-CDD82E34AF8B}"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers\"DropboxExt2"]
@="{FB314EDA-A251-47B7-93E1-CDD82E34AF8B}"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers\"DropboxExt3"]
@="{FB314EDD-A251-47B7-93E1-CDD82E34AF8B}"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers\"DropboxExt4"]
@="{FB314EDE-A251-47B7-93E1-CDD82E34AF8B}"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers\"DropboxExt5"]
@="{FB314EDB-A251-47B7-93E1-CDD82E34AF8B}"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers\"DropboxExt6"]
@="{FB314EDF-A251-47B7-93E1-CDD82E34AF8B}"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers\"DropboxExt7"]
@="{FB314EDC-A251-47B7-93E1-CDD82E34AF8B}"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers\"DropboxExt8"]
@="{FB314EE0-A251-47B7-93E1-CDD82E34AF8B}"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers\00avast]
@="{472083B0-C522-11CF-8763-00608CC02F24}"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers\1EldosIconOverlay]
@="{AF743E58-5357-404B-8314-32D2D8420F9D}"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers\1TortoiseNormal]
@="{C5994560-53D9-4125-87C9-F193FC689CB2}"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers\2TortoiseModified]
@="{C5994561-53D9-4125-87C9-F193FC689CB2}"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers\3TortoiseConflict]
@="{C5994562-53D9-4125-87C9-F193FC689CB2}"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers\4TortoiseLocked]
@="{C5994563-53D9-4125-87C9-F193FC689CB2}"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers\5TortoiseReadOnly]
@="{C5994564-53D9-4125-87C9-F193FC689CB2}"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers\6TortoiseDeleted]
@="{C5994565-53D9-4125-87C9-F193FC689CB2}"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers\7TortoiseAdded]
@="{C5994566-53D9-4125-87C9-F193FC689CB2}"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers\8TortoiseIgnored]
@="{C5994567-53D9-4125-87C9-F193FC689CB2}"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers\9TortoiseUnversioned]
@="{C5994568-53D9-4125-87C9-F193FC689CB2}"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers\EldosIconOverlay]
@="{5BB532A2-BF14-4CCC-86B7-71B81EF6F8BC}"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers\EnhancedStorageShell]
@="{D9144DCD-E998-4ECA-AB6A-DCD83CCBA16D}"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers\GDriveBlacklistedOverlay]
@="{81539FE6-33C7-4CE7-90C7-1C7B8F2F2D42}"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers\GDriveSharedEditOverlay]
@="{81539FE6-33C7-4CE7-90C7-1C7B8F2F2D44}"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers\GDriveSharedViewOverlay]
@="{81539FE6-33C7-4CE7-90C7-1C7B8F2F2D43}"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers\GDriveSyncedOverlay]
@="{81539FE6-33C7-4CE7-90C7-1C7B8F2F2D40}"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers\GDriveSyncingOverlay]
@="{81539FE6-33C7-4CE7-90C7-1C7B8F2F2D41}"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers\off0]
@="{8E33AEC3-C5F2-43C4-B048-9E3EB19B1DD5}"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers\off1]
@="{8E33AEC4-C5F2-43C4-B048-9E3EB19B1DD5}"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers\Offline Files]
@="{4E77131D-3629-431c-9818-C5679DC83E81}"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers\SharingPrivate]
@="{08244EE6-92F0-47f2-9FC9-929BAA2E7235}"
Remember, these are for Windows 64-bit and you should take a backup of your registry be
this function should work. basically does a recursive lookup till we get a distinct list of leaf nodes.
function distinctNodes(search, element) {
var d, e, ef;
e = [];
ef = [];
if (element) {
d = $(":contains(\""+ search + "\"):not(script)", element);
}
else {
d = $(":contains(\""+ search + "\"):not(script)");
}
if (d.length == 1) {
e.push(d[0]);
}
else {
d.each(function () {
var i, r = distinctNodes(search, this);
if (r.length === 0) {
e.push(this);
}
else {
for (i = 0; i < r.length; ++i) {
e.push(r[i]);
}
}
});
}
$.each(e, function () {
for (var i = 0; i < ef.length; ++i) {
if (this === ef[i]) return;
}
ef.push(this);
});
return ef;
}
What Oracle version are you using? Check this page which refers to Oracle 10:
http://www.acs.ilstu.edu/docs/Oracle/server.101/b10752/stats.htm
It says:
The recommended approach to gathering statistics is to allow Oracle to automatically gather the statistics. Oracle gathers statistics on all database objects automatically and maintains those statistics in a regularly-scheduled maintenance job.
Would Date.parse()
suffice?
See its relative MDN Documentation page.
In the .service file under the [Unit] section:
[Unit]
Description=My Website
After=syslog.target network.target mongodb.service
The important part is the mongodb.service
The manpage describes it however due to formatting it's not as clear on first sight
The choice of one or another depends on what you intend to do. From what I do understand:
jsonify would be useful when you are building an API someone would query and expect json in return. E.g: The REST github API could use this method to answer your request.
dumps, is more about formating data/python object into json and work on it inside your application. For instance, I need to pass an object to my representation layer where some javascript will display graph. You'll feed javascript with the Json generated by dumps.
#include <sys/types.h>
#include <sys/stat.h>
int status;
...
status = mkdir("/tmp/a/b/c", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
From here. You may have to do separate mkdirs for /tmp, /tmp/a, /tmp/a/b/ and then /tmp/a/b/c because there isn't an equivalent of the -p flag in the C api. Be sure and ignore the EEXISTS errno while you're doing the upper level ones.
Just for completeness and because I did not see anyone else suggest it:
Before implementing any of the complicated suggestions above consider if SQL injection is indeed a problem in your scenario.
In many cases the value provided to IN (...) is a list of ids that have been generated in a way that you can be sure that no injection is possible... (e.g. the results of a previous select some_id from some_table where some_condition.)
If that is the case you might just concatenate this value and not use the services or the prepared statement for it or use them for other parameters of this query.
query="select f1,f2 from t1 where f3=? and f2 in (" + sListOfIds + ");";
Delete the .keyring file under the location: configuration\org.eclipse.core.runtime, and after that, you will be invited to prompt your new svn account. for me it worked.
if os.path.exists(filePath):
#the file is there
elif os.access(os.path.dirname(filePath), os.W_OK):
#the file does not exists but write privileges are given
else:
#can not write there
Note that path.exists
can fail for more reasons than just the file is not there
so you might have to do finer tests like testing if the containing directory exists and so on.
After my discussion with the OP it turned out, that the main problem seems to be, that the file name might contain characters that are not allowed by the filesystem. Of course they need to be removed but the OP wants to maintain as much human readablitiy as the filesystem allows.
Sadly I do not know of any good solution for this. However Cecil Curry's answer takes a closer look at detecting the problem.
First, we need to filter the XML so as to parse that change objects become array
//catch xml
$xmlElement = file_get_contents ('php://input');
//change become array
$Data = (array)simplexml_load_string($xmlElement);
//and see
print_r($Data);
To invoke Firefox Browser headlessly, you can set the headless
property through Options()
class as follows:
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
options = Options()
options.headless = True
driver = webdriver.Firefox(options=options, executable_path=r'C:\Utility\BrowserDrivers\geckodriver.exe')
driver.get("http://google.com/")
print ("Headless Firefox Initialized")
driver.quit()
There's another way to accomplish headless mode. If you need to disable or enable the headless mode in Firefox, without changing the code, you can set the environment variable MOZ_HEADLESS
to whatever if you want Firefox to run headless, or don't set it at all.
This is very useful when you are using for example continuous integration and you want to run the functional tests in the server but still be able to run the tests in normal mode in your PC.
$ MOZ_HEADLESS=1 python manage.py test # testing example in Django with headless Firefox
or
$ export MOZ_HEADLESS=1 # this way you only have to set it once
$ python manage.py test functional/tests/directory
$ unset MOZ_HEADLESS # if you want to disable headless mode
How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium?
I just use this solution in Kotlin:
var date : String = DateFormat.format("EEEE dd-MMM-yyyy HH:mm a" , Date()) as String
To call any method of an object instantiated from a class (with statement new), you need to "point" to it. From the outside you just use the resource created by the new statement.
Inside any object PHP created by new, saves the same resource into the $this variable.
So, inside a class you MUST point to the method by $this.
In your class, to call smallTest
from inside the class, you must tell PHP which of all the objects created by the new statement you want to execute, just write:
$this->smallTest();
The document.location
is an object that contains properties for the current location.
The href
property is one of these properties, containing the complete URL, i.e. all the other properties put together.
Some browsers allow you to assign an URL to the location
object and acts as if you assigned it to the href
property. Some other browsers are more picky, and requires you to use the href
property. Thus, to make the code work in all browsers, you have to use the href
property.
Both the window
and document
objects has a location
object. You can set the URL using either window.location.href
or document.location.href
. However, logically the document.location
object should be read-only (as you can't change the URL of a document; changing the URL loads a new document), so to be on the safe side you should rather use window.location.href
when you want to set the URL.
The instruction MOV reg,addr means read a variable stored at address addr into register reg. The instruction LEA reg,addr means read the address (not the variable stored at the address) into register reg.
Another form of the MOV instruction is MOV reg,immdata which means read the immediate data (i.e. constant) immdata into register reg. Note that if the addr in LEA reg,addr is just a constant (i.e. a fixed offset) then that LEA instruction is essentially exactly the same as an equivalent MOV reg,immdata instruction that loads the same constant as immediate data.
Regex + Replace()
Although regex can be slower, in many use cases the developer is only manipulating a few strings at once so considering speed is irrelevant. Even though / / is faster than /\s/, having the '\s' explains what is going on to another developer perhaps more clearly.
let string = '/var/www/site/Brand new document.docx';
let path = string.replace(/\s/g, '');
// path => '/var/www/site/Brandnewdocument.docx'
Split() + Join()
Using Split + Join allows for further chained manipulation of the string.
let string = '/var/www/site/Brand new document.docx';
let path => string.split('').map(char => /(\s|\.)/.test(char) ? '/' : char).join('');
// "/var/www/site/Brand/new/document/docx";
This is due to wrong coding in bootstrap.css and bootstrap.min.css. When you download Bootstrap 3.0 from the Customizer the following code is missing:
@font-face {
font-family: 'Glyphicons Halflings';
src: url('../fonts/glyphicons-halflings-regular.eot');
src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}
Since this is the main code for using Glyphicons, it won't work ofc...
Download the css-files from the full package and this code will be implemented.
Yes, according to RFC 3696 apostrophes are valid as long as they come before the @ symbol.
If you run into this issue and you have Visual Studio, you can do the following:
Right-click on your branch and select View History
:
Right-click on commit you want to go back to. And Revert or Reset as needed.
I know it's an old post ... but it may be useful for someone ... in a "functional" way ...
import Data.List
safeIndex :: [a] -> Int -> Maybe a
safeIndex xs i
| (i> -1) && (length xs > i) = Just (xs!!i)
| otherwise = Nothing
ntile
from dplyr
now does this but behaves weirdly with NA
's.
I've used similar code in the following function that works in base R and does the equivalent of the cut2
solution above:
ntile_ <- function(x, n) {
b <- x[!is.na(x)]
q <- floor((n * (rank(b, ties.method = "first") - 1)/length(b)) + 1)
d <- rep(NA, length(x))
d[!is.na(x)] <- q
return(d)
}
I did not realize that the first nested element is actually an array. The correct way access to the post code key is as follows:
r = requests.get('http://api.zippopotam.us/us/ma/belmont')
j = r.json()
print j['state']
print j['places'][1]['post code']
If I were you, I would use BABEL: http://babel.pocoo.org/en/latest/index.html
from babel.numbers import format_decimal
format_decimal(188518982.18, locale='en_US')
Marshaling refers to converting the signature and parameters of a function into a single byte array. Specifically for the purpose of RPC.
Serialization more often refers to converting an entire object / object tree into a byte array Marshaling will serialize object parameters in order to add them to the message and pass it across the network. *Serialization can also be used for storage to disk.*
Use related name to count votes for a specific contest
class Item(models.Model):
name = models.CharField()
class Contest(models.Model);
name = models.CharField()
class Votes(models.Model):
user = models.ForeignKey(User)
item = models.ForeignKey(Item)
contest = models.ForeignKey(Contest, related_name="contest_votes")
comment = models.TextField()
>>> comments = Contest.objects.get(id=contest_id).contest_votes.count()
You hide Bootstrap modals with:
$('#modal').modal('hide');
Saying $().hide()
makes the matched element invisible, but as far as the modal-related code is concerned, it's still there. See the Methods section in the Modals documentation.
You can also do this, for readability's sake
boolean passwordVerified=(pword.equals(pwdRetypePwd.getText());
if(!passwordVerified ){
txtaError.setEditable(true);
txtaError.setText("*Password didn't match!");
txtaError.setForeground(Color.red);
txtaError.setEditable(false);
}else{
addNewUser();
}
return passwordVerified;
If you use Google Guava library this is what you can do, see Lists#transform
String s = "AttributeGet:1,16,10106,10111";
List<Integer> attributeIDGet = new ArrayList<Integer>();
if(s.contains("AttributeGet:")) {
List<String> attributeIDGetS = Arrays.asList(s.split(":")[1].split(","));
attributeIDGet =
Lists.transform(attributeIDGetS, new Function<String, Integer>() {
public Integer apply(String e) {
return Integer.parseInt(e);
};
});
}
Yep, agree with above answer that's it's bloated, but stylish. But it's just another way.
node
comes with npm
installed so you should have a version of npm
, however npm
gets updated more frequently than node
does, so you'll want to make sure it's the latest version.
sudo npm install npm -g
Test: Run npm -v
. The version should be higher than 2.1.8.
npm install
THAT'S IT!
If you are using MySQL or MariaDB, the easiest and performant way dump CSV for single table is -
SELECT customer_id, firstname, surname INTO OUTFILE '/exportdata/customers.txt'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM customers;
Now you can use other techniques to repeat this command for multiple tables. See more details here:
You'll have to have a ContextLoaderListener in your web.xml - It loads your configuration files.
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
You need to understand the difference between Web application context and root application context .
In the web MVC framework, each DispatcherServlet has its own WebApplicationContext, which inherits all the beans already defined in the root WebApplicationContext. These inherited beans defined can be overridden in the servlet-specific scope, and new scope-specific beans can be defined local to a given servlet instance.
The dispatcher servlet's application context is a web application context which is only applicable for the Web classes . You cannot use these for your middle tier layers . These need a global app context using ContextLoaderListener .
Read the spring reference here for spring mvc .
<a href="javaScript:{openPopUp();}"></a>
<form action="actionName">
<div id="divId" style="display:none;">
UsreName:<input type="text" name="userName"/>
</div>
</form>
function openPopUp()
{
$('#divId').css('display','block');
$('#divId').dialog();
}
Vinay (above) gave an effective work-around. What's actually causing the button's OnClick event to not work following the OnClientClick event function is that MS has defined it where, once the button is disabled (in the function called by the OnClientClick event), the button "honors" this by not trying to complete the button's activity by calling the OnClick event's defined method.
I struggled several hours trying to figure this out. Once I removed the statement to disable the submit button (that was inside the OnClientClick function), the OnClick method was called with no further problem.
Microsoft, if you're listening, once the button is clicked it should complete it's assigned activity even if it is disabled part of the way through this activity. As long as it is not disabled when it is clicked, it should complete all assigned methods.
I know the answer by @Pascal Thivent has solved the issue. I would like to add a bit more to his answer to others who might be surfing this thread.
If you are like me in the initial days of learning and wrapping your head around the concept of using the @OneToMany
annotation with the 'mappedBy
' property, it also means that the other side holding the @ManyToOne
annotation with the @JoinColumn
is the 'owner' of this bi-directional relationship.
Also, mappedBy
takes in the instance name (mCustomer
in this example) of the Class variable as an input and not the Class-Type (ex:Customer) or the entity name(Ex:customer).
BONUS :
Also, look into the orphanRemoval
property of @OneToMany
annotation. If it is set to true, then if a parent is deleted in a bi-directional relationship, Hibernate automatically deletes it's children.
I needed to use this as a cell function (like SUM
or VLOOKUP
) and found that it was easy to:
Create the following function either in workbook or in its own module:
Function REGPLACE(myRange As Range, matchPattern As String, outputPattern As String) As Variant
Dim regex As New VBScript_RegExp_55.RegExp
Dim strInput As String
strInput = myRange.Value
With regex
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = matchPattern
End With
REGPLACE = regex.Replace(strInput, outputPattern)
End Function
Then you can use in cell with =REGPLACE(B1, "(\w) (\d+)", "$1$2")
(ex: "A 243" to "A243")
Here you go:
http://jsfiddle.net/damsarabi/gwAdA/
You cannot use width: 100px, because the display is table-cell. You can however use Max-width: 100px. then your box will never get bigger than 100px. but you need to add overflow:hidden to make sure the contect don't bleed to other cells. you can also add white-space: nowrap if you wish to keep the height from increasing.
@RequestMapping("/download")
public byte[] download() throws Exception {
File f = new File("C:\\WorkSpace\\Text\\myDoc.txt");
byte[] byteArray = new byte[(int) f.length()];
byteArray = FileUtils.readFileToByteArray(f);
return byteArray;
}
private ResponseEntity<byte[]> getDownload(){
URI end = URI.create(your url which server has exposed i.e. bla
bla/download);
return rest.getForEntity(end,byte[].class);
}
public static void main(String[] args) throws Exception {
byte[] byteArray = new TestClient().getDownload().getBody();
FileOutputStream fos = new
FileOutputStream("C:\\WorkSpace\\testClient\\abc.txt");
fos.write(byteArray);
fos.close();
System.out.println("file written successfully..");
}