Go to the folder in which eclipse is installed then open readme folder followed by the readme txt file. Here you will find all the info you need.
Thanks a lot guys!
I overlooked my ECLIPSE VERSION it was 64Bit and 3.6
I had to make sure it's 32Bit Eclipse, 32 Bit JVM so i uninstalled Eclipse & all JVM for clean start. Installed 32Bit JDK1.6 from here and 32Bit Eclipse from here
This way Convert all Data From Filelds(Columns) In Table To Record (Row).
Declare @TableName [nvarchar](128)
Declare @ExecStr nvarchar(max)
Declare @Where nvarchar(max)
Set @TableName = 'myTableName'
--Enter Filtering If Exists
Set @Where = ''
--Set @ExecStr = N'Select * From '+quotename(@TableName)+@Where
--Exec(@ExecStr)
Drop Table If Exists #tmp_Col2Row
Create Table #tmp_Col2Row
(Field_Name nvarchar(128) Not Null
,Field_Value nvarchar(max) Null
)
Set @ExecStr = N' Insert Into #tmp_Col2Row (Field_Name , Field_Value) '
Select @ExecStr += (Select N'Select '''+C.name+''' ,Convert(nvarchar(max),'+quotename(C.name) + ') From ' + quotename(@TableName)+@Where+Char(10)+' Union All '
from sys.columns as C
where (C.object_id = object_id(@TableName))
for xml path(''))
Select @ExecStr = Left(@ExecStr,Len(@ExecStr)-Len(' Union All '))
--Print @ExecStr
Exec (@ExecStr)
Select * From #tmp_Col2Row
Go
Since text files are sequential, you can't directly erase data on them. Your options are:
Look at the seek
/truncate
function/method to implement any of the ideas above. Both Python and C have those functions.
Gonna give another answer, since the libraries mentioned haven't been actively developed anymore.
Consider using YoutubeExplode. It has a very rich and consistent API and allows you to do a lot of other things with youtube videos beside downloading them.
Obfuscation can never really work. For anyone who really wants to get at your code, it's just a speed bump. Worse, it keeps your users from fixing bugs (and shipping the fixes back to you), and makes it harder for you to diagnose problems in the field. Its a waste of your time and money.
Talk to a lawyer about intellectual property law and what your legal options are. "Open Source" does not mean "people can read the source". Instead, Open Source is a particular licensing model granting permission to freely use and modify your code. If you don't grant such a license then people copying your code are in violation and (in most of the world) you have legal options to stop them.
The only way you can really protect your code is to not ship it. Move the important code server-side and have your public Javascript code do Ajax calls to it.
This will vary depending on your architecture and how it treats basic data types. It will also depend on whether the system requires natural alignment.
Im putting this in an answer because it's too long for a comment:
If you need the VM to be aware when the CheckBox
is changed, you should really bind the CheckBox
to the VM, and not a static value:
public class ViewModel
{
private bool _caseSensitive;
public bool CaseSensitive
{
get { return _caseSensitive; }
set
{
_caseSensitive = value;
NotifyPropertyChange(() => CaseSensitive);
Settings.Default.bSearchCaseSensitive = value;
}
}
}
XAML:
<CheckBox Content="Case Sensitive" IsChecked="{Binding CaseSensitive}"/>
Use the display property in CSS:
<body>
<div id="invisible" style="display:none;">Invisible DIV</div>
<div>Another DIV
<button onclick="document.getElementById('invisible').style.display='block'">
Button
</button>
</div>
</body>
When the the display of the first div is set back to block
it will appear and shift the second div down.
I use favicons-webpack-plugin
const FaviconsWebpackPlugin = require("favicons-webpack-plugin");
module.exports={
plugins:[
new FaviconsWebpackPlugin("./public/favicon.ico"),
//public is in the root folder in this app.
]
}
When I want to take into account extra characters like your commas (in my case each token may be entered with quotes), I'd do a string.replace() to change the other delimiters to blanks and then split on whitespace.
&something
gives you the address of the std::vector
object, not the address of the data it holds. &something.begin()
gives you the address of the iterator returned by begin()
(as the compiler warns, this is not technically allowed because something.begin()
is an rvalue expression, so its address cannot be taken).
Assuming the container has at least one element in it, you need to get the address of the initial element of the container, which you can get via
&something[0]
or &something.front()
(the address of the element at index 0), or
&*something.begin()
(the address of the element pointed to by the iterator returned by begin()
).
In C++11, a new member function was added to std::vector
: data()
. This member function returns the address of the initial element in the container, just like &something.front()
. The advantage of this member function is that it is okay to call it even if the container is empty.
(I presume you are aware that using UDP(User Datagram Protocol) does not guarantee delivery, checks for duplicates and congestion control and will just answer your question).
In your server this line:
var data = udpServer.Receive(ref groupEP);
re-assigns groupEP
from what you had to a the address you receive something on.
This line:
udpServer.Send(new byte[] { 1 }, 1);
Will not work since you have not specified who to send the data to. (It works on your client because you called connect which means send will always be sent to the end point you connected to, of course we don't want that on the server as we could have many clients). I would:
UdpClient udpServer = new UdpClient(UDP_LISTEN_PORT);
while (true)
{
var remoteEP = new IPEndPoint(IPAddress.Any, 11000);
var data = udpServer.Receive(ref remoteEP);
udpServer.Send(new byte[] { 1 }, 1, remoteEP); // if data is received reply letting the client know that we got his data
}
Also if you have server and client on the same machine you should have them on different ports.
Apache POI can do this for you. Specifically the HSSF module. The quick guide is most useful. Here's how to do what you want - specifically create a sheet and write it out.
Workbook wb = new HSSFWorkbook();
//Workbook wb = new XSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("new sheet");
// Create a row and put some cells in it. Rows are 0 based.
Row row = sheet.createRow((short)0);
// Create a cell and put a value in it.
Cell cell = row.createCell(0);
cell.setCellValue(1);
// Or do it on one line.
row.createCell(1).setCellValue(1.2);
row.createCell(2).setCellValue(
createHelper.createRichTextString("This is a string"));
row.createCell(3).setCellValue(true);
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
Well, you're missing the letter 'd' in url("~/fonts/Lato-Bol.ttf"); - but assuming that's not it, I would open up your page with developer tools in Chrome and make sure there's no errors loading any of the files (you would probably see an issue in the JavaScript console, or you can check the Network tab and see if anything is red).
(I don't see anything obviously wrong with the code you have posted above)
Other things to check: 1) Are you including your CSS file in your html above the lines where you are trying to use the font-family style? 2) What do you see in the CSS panel in the developer tools for that div? Is font-family: lato crossed out?
This answer is for react-router-4. You can wrap all the routes in Switch block, which functions just like the switch-case expression, and renders the component with the first matched route. eg)
<Switch>
<Route path="/" component={home}/>
<Route path="/home" component={home}/>
<Route component={GenericNotFound}/> {/* The Default not found component */}
</Switch>
When to use exact
Without exact:
<Route path='/home'
component = {Home} />
{/* This will also work for cases like https://<domain>/home/anyvalue. */}
With exact:
<Route exact path='/home'
component = {Home} />
{/*
This will NOT work for cases like https://<domain>/home/anyvalue.
Only for https://<url>/home and https://<domain>/home/
*/}
Now if you are accepting routing parameters, and if it turns out incorrect, you can handle it in the target component itself. eg)
<Route exact path='/user/:email'
render = { (props) => <ProfilePage {...props} user={this.state.user} />} />
Now in ProfilePage.js
if(this.props.match.params.email != desiredValue)
{
<Redirect to="/notFound" component = {GenericNotFound}/>
//Or you can show some other component here itself.
}
For more details you can go through this code:
If you are using mac-OS , export JAVA_HOME=/usr/libexec/java_home
need to be changed to export JAVA_HOME=$(/usr/libexec/java_home)
.
Steps to do this :
$ vim .bash_profile
export JAVA_HOME=$(/usr/libexec/java_home)
$ source .bash_profile
where /usr/libexec/java_home
is the path of your jvm
Well, it costed me 2 days to figure out the problem. In short, by default you shall just keep the max version to be the highest level you had downloaded, says, Level 23 (Android M) for my case.
otherwise you will get these errors. You have to go to project properties of both your project and appcompat to change the target version.
sigh.
If the goal is to have a reusable RestTemplate which is in general useful for attaching the same header to a series of similar request a org.springframework.boot.web.client.RestTemplateCustomizer
parameter can be used with a RestTemplateBuilder
:
String accessToken= "<the oauth 2 token>";
RestTemplate restTemplate = new RestTemplateBuilder(rt-> rt.getInterceptors().add((request, body, execution) -> {
request.getHeaders().add("Authorization", "Bearer "+accessToken);
return execution.execute(request, body);
})).build();
Since this is a Python 3 project, you only need to delete __pycache__
directories -- all .pyc
/.pyo
files are inside them.
find . -type d -name __pycache__ -exec rm -r {} \+
or its simpler form,
find . -type d -name __pycache__ -delete
which didn't work for me for some reason (files were deleted but directories weren't), so I'm including both for the sake of completeness.
Alternatively, if you're doing this in a directory that's under revision control, you can tell the RCS to ignore __pycache__
folders recursively. Then, at the required moment, just clean up all the ignored files. This will likely be more convenient because there'll probably be more to clean up than just __pycache__
.
As of 2014, here is a statement from a Microsoft representative (the Scripting Guy):
As much as we might hate to admit it, there are still no Windows PowerShell cmdlets from Microsoft that permit creating local user accounts or local user groups. We finally have a Desired State Configuration (DSC ) provider that can do this—but to date, no cmdlets.
I tried several solutions above, but none solved my problem. Solution to refresh a subform in a form after saving data to database:
Me.subformname.Requery
It worked fine for me. Good luck.
Current time with AM/PM designator:
DateTime.Now.ToString("hh:mm:ss tt", System.Globalization.DateTimeFormatInfo.InvariantInfo)
DateTime.Now.ToString("hh:mm:ss.fff tt", System.Globalization.DateTimeFormatInfo.InvariantInfo)
Current time using 0-23 hour notation:
DateTime.Now.ToString("HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo)
DateTime.Now.ToString("HH:mm:ss.fff", System.Globalization.DateTimeFormatInfo.InvariantInfo)
There are two ways:
If you are patient (requires Ubuntu corral pc and Android SDK and some heavy terminal work to get it all set up). See Using the 3.0 SDK without paying for the priviledge.
If you are immoral (requires Mac OS X Leopard and virtualization, both only obtainable through great expense or pirating) - remove space from the following link. htt p://iphonewo rld. codinghut.com /2009/07/using-the-3-0-sdk-without-paying-for-the-priviledge/
I use the Ubuntu method myself.
Here is my solution, i have been reading a lot of post and they was really helpfull, finaly i build a code for small files, with cUrl and Php, that i think its really usefull.
public function postFile()
{
$file_url = "test.txt"; //here is the file route, in this case is on same directory but you can set URL too like "http://examplewebsite.com/test.txt"
$eol = "\r\n"; //default line-break for mime type
$BOUNDARY = md5(time()); //random boundaryid, is a separator for each param on my post curl function
$BODY=""; //init my curl body
$BODY.= '--'.$BOUNDARY. $eol; //start param header
$BODY .= 'Content-Disposition: form-data; name="sometext"' . $eol . $eol; // last Content with 2 $eol, in this case is only 1 content.
$BODY .= "Some Data" . $eol;//param data in this case is a simple post data and 1 $eol for the end of the data
$BODY.= '--'.$BOUNDARY. $eol; // start 2nd param,
$BODY.= 'Content-Disposition: form-data; name="somefile"; filename="test.txt"'. $eol ; //first Content data for post file, remember you only put 1 when you are going to add more Contents, and 2 on the last, to close the Content Instance
$BODY.= 'Content-Type: application/octet-stream' . $eol; //Same before row
$BODY.= 'Content-Transfer-Encoding: base64' . $eol . $eol; // we put the last Content and 2 $eol,
$BODY.= chunk_split(base64_encode(file_get_contents($file_url))) . $eol; // we write the Base64 File Content and the $eol to finish the data,
$BODY.= '--'.$BOUNDARY .'--' . $eol. $eol; // we close the param and the post width "--" and 2 $eol at the end of our boundary header.
$ch = curl_init(); //init curl
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'X_PARAM_TOKEN : 71e2cb8b-42b7-4bf0-b2e8-53fbd2f578f9' //custom header for my api validation you can get it from $_SERVER["HTTP_X_PARAM_TOKEN"] variable
,"Content-Type: multipart/form-data; boundary=".$BOUNDARY) //setting our mime type for make it work on $_FILE variable
);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/1.0 (Windows NT 6.1; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0'); //setting our user agent
curl_setopt($ch, CURLOPT_URL, "api.endpoint.post"); //setting our api post url
curl_setopt($ch, CURLOPT_COOKIEJAR, $BOUNDARY.'.txt'); //saving cookies just in case we want
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); // call return content
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1); navigate the endpoint
curl_setopt($ch, CURLOPT_POST, true); //set as post
curl_setopt($ch, CURLOPT_POSTFIELDS, $BODY); // set our $BODY
$response = curl_exec($ch); // start curl navigation
print_r($response); //print response
}
With this we shoud be get on the "api.endpoint.post" the following vars posted You can easly test with this script, and you should be recive this debugs on the function postFile() at the last row
print_r($response); //print response
public function getPostFile()
{
echo "\n\n_SERVER\n";
echo "<pre>";
print_r($_SERVER['HTTP_X_PARAM_TOKEN']);
echo "/<pre>";
echo "_POST\n";
echo "<pre>";
print_r($_POST['sometext']);
echo "/<pre>";
echo "_FILES\n";
echo "<pre>";
print_r($_FILEST['somefile']);
echo "/<pre>";
}
Here you are it should be work good, could be better solutions but this works and is really helpfull to understand how the Boundary and multipart/from-data mime works on php and curl library,
My Best Reggards,
my apologies about my english but isnt my native language.
This is instruction for MAC only.
I had the same problem. I solved it by configuring $GRADLE_HOME
in .bash_profile
. Here's how you do it:
.bash_profile
(usually it's located in the user’s home directory).$PATH
variable:
export GRADLE_HOME=/usr/local/opt/gradle/libexec
export PATH=$GRADLE_HOME/bin:$PATH
source .bash_profile
I wrote my own article with instruction in a case if somebody will encounter the same problem.
No it won't, Java will short-circuit and stop evaluating once it knows the result.
You can do like this:
a {font-size: 100px}
Try avoid using font tag because it's deprecated. Use CSS like above instead. You can give your anchors specific class and apply any style for them.
Actually we get this error also when we create canvas in javascript as below.
document.createElement('canvas');
Here point to be noted we have to provide argument name correctly as 'canvas' not anything else.
Thanks
The following worked and the images to be set is resources in properties:
var bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(MyProject.Properties.Resources.myImage.GetHbitmap(),
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
MyButton.Background = new ImageBrush(bitmapSource);
img_username.Source = bitmapSource;
Open the Frameworks folder in your project and make sure there are only frameworks inside. I added by mistake the whole Developer folder!
No, JavaScript doesn't have access to writing files as this would be a huge security risk to say the least. If you wanted to get/store information server-side, though, you can certainly make an Ajax call to a PHP/ASP/Python/etc. script that can then get/store the data in the server. If you meant store data on the client machine, this is impossible with JavaScript alone. I suspect Flash/Java may be able to, but I am not sure.
If you are only trying to store a small amount of information for an unreliable period of time regarding a specific user, I think you want Web Storage API or cookies. I am not sure from your question what you are trying to accomplish, though.
I have updated the controller to:
.controller('BusinessCtrl',
function ($scope, $http, $location, Business, BusinessService, UserService, Photo) {
$scope.$watch('createBusinessForm.$valid', function(newVal) {
//$scope.valid = newVal;
$scope.informationStatus = true;
});
...
The problem for me was that I had .rnd in my home directory but it was owned by root. Deleting it and reissuing the openssl command fixed this.
I came across this small presentation while researching this question on my own. I was surprised at how well it was laid out, both the info and the presentation of it.
http://openmymind.net/Multiple-Collections-Versus-Embedded-Documents
It summarized:
As a general rule, if you have a lot of [child documents] or if they are large, a separate collection might be best.
Smaller and/or fewer documents tend to be a natural fit for embedding.
Use a JSON library to parse the string and retrieve the value.
The following very basic example uses the built-in JSON parser from Android.
String jsonString = "{ \"name\" : \"John\", \"age\" : \"20\", \"address\" : \"some address\" }";
JSONObject jsonObject = new JSONObject(jsonString);
int age = jsonObject.getInt("age");
More advanced JSON libraries, such as jackson, google-gson, json-io or genson, allow you to convert JSON objects to Java objects directly.
In Eclipse 3.3:
It's installed under your Eclipse workspace. Something like:
.metadata\.plugins\org.eclipse.core.resources\.projects\
within your workspace folder.
Under that folder is one folder per project. There's a file in there called .location, but it's binary.
So it looks like you can't do what you want, without interacting w/ Eclipse programmatically.
1) Clear your chache. http://support.google.com/chrome/bin/answer.py?hl=en&answer=95582 And test another browser, lets say safari. How did you import the favicon?
2) How you should add it:
Normal favicon:
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
PNG/GIF favicon:
<link rel="icon" type="image/gif" href="favicon.gif" />
<link rel="icon" type="image/png" href="favicon.png" />
3) Another thing could be the problem that chrome can't display favicons, if it's local (not uploaded to a webserver).
4) Try to rename it from favicon.{whatever}
to {yourfaviconname}.{whatever}
but I would suggest you to still have the normal favicon. This has solved my issue on IE.
5) Found another solution for this which works great! I simply added my favicon as Base64 Encoded Image directly inside the tag like this:
<link href="data:image/x-icon;base64,AAABAAIAEBAAAAEAIABoBAAAJgAAACAgAAABACAAqBAAAI4EAAAoAAAAEAAAACAAAAABACAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AIaDgv+Gg4L/hoOC/4aDgv+Gg4L/hoOC/4aDgv+Gg4L/hoOC/4aDgv////8A////AP///wD///8A////AP///wCGg4L/////AP///wD///8A////AP///wD///8A////AP///wCGg4L/////AP///wD///8A////AP///wD///8AhoOC/////wCGg4L/hoOC/4aDgv+Gg4L/hoOC/4aDgv////8AhoOC/////wD///8A////AP///wD///8A////AIaDgv////8A////AP///wD///8A////AP///wD///8A////AIaDgv////8A////AP///wD///8A////AP///wCGg4L/////AHCMqP9wjKj/cIyo/3CMqP9wjKj/cIyo/////wCGg4L/////AP///wD///8A////AP///wD///8AhoOC/////wBTlsIAU5bCAFOWwgBTlsIAU5bCM1OWwnP///8AhoOC/////wD///8A////AP///wD///8A////AP///wD///8AU5bCBlOWwndTlsLHU5bC+FOWwv1TlsLR////AP///wD///8A////AP///wD///8A////AP///wD///8A////AFOWwvtTlsLuU5bCu1OWwlc2k9cANpPXqjaT19H///8A////AP///wD///8A////AP///wD///8A////AP///wBTlsIGNpPXADaT1wA2k9dINpPX8TaT1+40ktpDH4r2tB+K9hL///8A////AP///wD///8A////AP///wD///8A////ADaT1wY2k9e7NpPX/TaT16AfivYGH4r23R+K9u4tg/WQLoL1mP///wD///8A////AP///wD///8A////AP///wA2k9fuNpPX5zaT1zMfivYGH4r23R+K9uwjiPYXLoL1+S6C9W7///8A////AP///wD///8A////AP///wD///8ANpPXLjaT1wAfivYGH4r22x+K9usfivYSLoL1oC6C9esugvUA////AP///wD///8A////AP///wD///8A////AP///wD///8AH4r2zx+K9usfivYSLoL1DC6C9fwugvVXLoL1AP///wD///8A////AP///wD///8A////AP///wD///8A////AB+K9kgfivYMH4r2AC6C9bEugvXhLoL1AC6C9QD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAugvXyLoL1SC6C9QAugvUA////AP//AADgBwAA7/cAAOgXAADv9wAA6BcAAO+XAAD4HwAA+E8AAPsDAAD8AQAA/AEAAP0DAAD/AwAA/ycAAP/nAAAoAAAAIAAAAEAAAAABACAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/////wD///8AhISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP8AAAAA////AISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AISEhP+EhIT/////AP///wCEhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/wAAAAD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP/4+vsA4ujuAOLo7gDi6O4A4ujuAN3k6wDZ4OgA2eDoANng6ADZ4OgA2eDoANng6ADW3uYAJS84APj6+wCEhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/9Xd5QBwjKgAcIyoRnCMqGRwjKhxcIyogHCMqI9wjKidcIyoq3CMqLlwjKjHcIyo1HCMqLhogpwA/f7+AISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AISEhP+EhIT/xtHcAHCMqABwjKjAcIyo/3CMqP9wjKj/cIyo/3CMqP9wjKj/cIyo/3CMqP9wjKj/cIyo4EdZawD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP+2xNMAcIyoAHCMqJhwjKjPcIyowHCMqLFwjKijcoymlXSMpIh0jKR6co2mbG+OqGFqj61zXZO4AeXv9gCEhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/6i5ygDF0dwAIiozACQyPQAoP1AALlBmADhlggBblLkGVJbBPFOWwnxTlsK5U5bC9FOWwv9TlsIp3erzAISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAALztHAAAAAAAuU2sAU5bCClOWwkNTlsKAU5bCwFOWwvhTlsL/U5bC/1OWwv9TlsL/U5bC/ViVvVcXOFAAAAAAAAAAAAD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAALDhEALVFoAFOWwjpTlsL6U5bC/1OWwv9TlsL/U5bC/1OWwvxTlsLIV5W+i2CRs0xHi71TKYzUnyuM0gIJHi4AAAAAAAAAAAAAAAAA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAACtNZABTlsIAU5bCD1OWwv1TlsL6U5bCxFOWwoRVlsBHZJKwDCNObAA8icJAKYzUwimM1P8pjNT/KYzUWCaCxgALLUsAAAAAAAAAAAD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAApS2EAU5bCAFOWwgBTlsIAU5bCNVOWwgg+cJEAIT1QABU/XQA1isg4KYzUuymM1P8pjNT/KYzU/ymM1LAti9E0JYvmDhdouAAAAAAAAAAAAP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AFyk1AE+PuQBTlsIAU5bCAER7nwAmRVoADBojABRFaQAwi80xKYzUsymM1P8pjNT/KYzU/ymM1LgsjNE2MovXFB+K9MUfivbBH4r2BgcdNAARQH8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAQIDABIgKgAPGiIABRMcABdQeQAti9AqKYzUrCmM1P8pjNT/KYzU/ymM1MAqjNM9HmqmACWK7SIfivbZH4r2/x+K9vsuiudAFE2YACB69AD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAABhQfABtejgAoitEAKYzUACmM1JQpjNT/KYzU/ymM1MgpjNREH2mgABlosQAfivY0H4r26R+K9v8fivbyKIrtR0CB1SggevTQIHr0Nv///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAACBwsAJX2+ACmM1AApjNQAKYzUGSmM1MYpjNRMInWxABNHdQAcfuEAH4r2Sx+K9vUfivb/H4r25iGK9DE2gt4EIHr0yyB69P8gevTQ////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAAAAAAAAOMUsAKYzUACmM1AApjNQAJX6/ABE7WgAUWJwAH4r2AB+K9mYfivb9H4r2/x+K9tYfivYfG27RACB69HsgevT/IHr0+yB69DL///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAAAAAAAAAAAAAfaJ4AJ4XKABVGagAKKkoAG3raAB+K9gEfivaEH4r2/x+K9v8fivbCH4r2EB133wAgevQsIHr0+SB69P8gevSAIHr0AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAAAAAAAAAAAAAUSGwAFERwAElCOAB+J9QAfivYAH4r2lx+K9v8fivb/H4r2qR+K9gYefuoAIHr0BSB69M4gevT/IHr00CB69AUgevQA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAkqSgAfivYAH4r2AB+K9gAfivZLH4r2/R+K9osfivYBH4PwACB69AAgevSAIHr0/yB69PkgevQwIHr0ACB69AD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAAAAAAAAAAAAAAAAAAEEiAAB+K9gAfivYAH4r2AB+K9gAfivYsH4r2AB+G8wAge/QAIHr0MCB69PsgevT/IHr0eyB69AAgevQAIHr0AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAAAAAAAAAAAAAAAAAAXZrYAH4r2AB+K9gAfivYAH4r2AB+K9gAfifUAIHz0ACB69AcgevTQIHr0/yB69MwgevQEIHr0ACB69AAgevQA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAAAAAAAAAAAAAAAIDAB6E6gAfivYAH4r2AB+K9gAfivYAH4r2ACB+9QAgevQAIHr0fCB69P8gevT5IHr0LCB69AAgevQAIHr0ACB69AD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAAAAAAAAAAAAABBAcAEUqDAB6E6wAfivYAH4r2AB+K9gAggPUAIHr0ACB69AAgevQTIHr0qCB69HYgevQAIHr0ACB69AAgevQAIHr0AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP////////////////wAAH/8AAB//P/+f/z//n/8wAZ//MAGf/z//n/8wAZ//MAGf/zAAn/8/gJ//+AD///AAf//wEH//+cA///8AH//8BB///BgH//xwB///4If//4EP//+CD///hh///9w////4P///+H////j////////////" rel="icon" type="image/x-icon" />
Used this page here for this: http://www.motobit.com/util/base64-decoder-encoder.asp
// Excuse my beginner's english
There is msgHTML() method, which, also, call IsHTML().
Hrm... name IsHTML
is confusing...
/**
* Create a message from an HTML string.
* Automatically makes modifications for inline images and backgrounds
* and creates a plain-text version by converting the HTML.
* Overwrites any existing values in $this->Body and $this->AltBody
* @access public
* @param string $message HTML message string
* @param string $basedir baseline directory for path
* @param bool $advanced Whether to use the advanced HTML to text converter
* @return string $message
*/
public function msgHTML($message, $basedir = '', $advanced = false)
You should use IS rather than = for comparing to NULL.
UPDATE `smartmeter_usage`.`users_reporting`
SET panel_id = 3
WHERE panel_id IS null
The LIMIT
clause in MySQL when applied to an update does not permit an offset to be specified.
With the help of raincoat's code on GitHub, I managed to get a running version accessing the clipboard with plain JavaScript.
function TrelloClipboard() {
var me = this;
var utils = {
nodeName: function (node, name) {
return !!(node.nodeName.toLowerCase() === name)
}
}
var textareaId = 'simulate-trello-clipboard',
containerId = textareaId + '-container',
container, textarea
var createTextarea = function () {
container = document.querySelector('#' + containerId)
if (!container) {
container = document.createElement('div')
container.id = containerId
container.setAttribute('style', [, 'position: fixed;', 'left: 0px;', 'top: 0px;', 'width: 0px;', 'height: 0px;', 'z-index: 100;', 'opacity: 0;'].join(''))
document.body.appendChild(container)
}
container.style.display = 'block'
textarea = document.createElement('textarea')
textarea.setAttribute('style', [, 'width: 1px;', 'height: 1px;', 'padding: 0px;'].join(''))
textarea.id = textareaId
container.innerHTML = ''
container.appendChild(textarea)
textarea.appendChild(document.createTextNode(me.value))
textarea.focus()
textarea.select()
}
var keyDownMonitor = function (e) {
var code = e.keyCode || e.which;
if (!(e.ctrlKey || e.metaKey)) {
return
}
var target = e.target
if (utils.nodeName(target, 'textarea') || utils.nodeName(target, 'input')) {
return
}
if (window.getSelection && window.getSelection() && window.getSelection().toString()) {
return
}
if (document.selection && document.selection.createRange().text) {
return
}
setTimeout(createTextarea, 0)
}
var keyUpMonitor = function (e) {
var code = e.keyCode || e.which;
if (e.target.id !== textareaId || code !== 67) {
return
}
container.style.display = 'none'
}
document.addEventListener('keydown', keyDownMonitor)
document.addEventListener('keyup', keyUpMonitor)
}
TrelloClipboard.prototype.setValue = function (value) {
this.value = value;
}
var clip = new TrelloClipboard();
clip.setValue("test");
See a working example: http://jsfiddle.net/AGEf7/
The innerHTML
property is used to get or set the HTML content of an element node.
Example: http://jsfiddle.net/mQMVc/
// get the element with the "someElement" id, and give it new content
document.getElementById('someElement').innerHTML = "<p>new content</p>";
// retrieve the content from an element
var content = document.getElementById('someElement').innerHTML;
alert( content );
in vb.net just do this
mylist.addrange(intsArray)
or
Dim mylist As New List(Of Integer)(intsArray)
You need to return your promise to the calling function.
islogged:function(){
var cUid=sessionService.get('uid');
alert("in loginServce, cuid is "+cUid);
var $checkSessionServer=$http.post('data/check_session.php?cUid='+cUid);
$checkSessionServer.then(function(){
alert("session check returned!");
console.log("checkSessionServer is "+$checkSessionServer);
});
return $checkSessionServer; // <-- return your promise to the calling function
}
use strip_tags
$text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
echo strip_tags($text); //output Test paragraph. Other text
<?php echo substr(strip_tags($row_get_Business['business_description']),0,110) . "..."; ?>
Try executing your command with sudo(Super User), this worked for me :)
Run : $ sudo your_command
After than enter the super user password. Thats All..
After converting your varchar2
date to a true date
datatype, then convert back to varchar2
with the desired mask:
to_char(to_date('01/02/2012','MM/DD/YYYY'),'WW')
If you want the week number in a number
datatype, you can wrap the statement in to_number()
:
to_number(to_char(to_date('01/02/2012','MM/DD/YYYY'),'WW'))
However, you have several week number options to consider:
WW Week of year (1-53) where week 1 starts on the first day of the year and continues to the seventh day of the year.
W Week of month (1-5) where week 1 starts on the first day of the month and ends on the seventh.
IW Week of year (1-52 or 1-53) based on the ISO standard.
As stated, there is no non Microsoft / compiler vendor way to do this on the windows platform. However, it is obviously useful to catch these types of exceptions in the normal try { } catch (exception ex) { } way for error reporting and more a graceful exit of your app (as JaredPar says, the app is now probably in trouble). We use _se_translator_function in a simple class wrapper that allows us to catch the following exceptions in a a try handler:
DECLARE_EXCEPTION_CLASS(datatype_misalignment)
DECLARE_EXCEPTION_CLASS(breakpoint)
DECLARE_EXCEPTION_CLASS(single_step)
DECLARE_EXCEPTION_CLASS(array_bounds_exceeded)
DECLARE_EXCEPTION_CLASS(flt_denormal_operand)
DECLARE_EXCEPTION_CLASS(flt_divide_by_zero)
DECLARE_EXCEPTION_CLASS(flt_inexact_result)
DECLARE_EXCEPTION_CLASS(flt_invalid_operation)
DECLARE_EXCEPTION_CLASS(flt_overflow)
DECLARE_EXCEPTION_CLASS(flt_stack_check)
DECLARE_EXCEPTION_CLASS(flt_underflow)
DECLARE_EXCEPTION_CLASS(int_divide_by_zero)
DECLARE_EXCEPTION_CLASS(int_overflow)
DECLARE_EXCEPTION_CLASS(priv_instruction)
DECLARE_EXCEPTION_CLASS(in_page_error)
DECLARE_EXCEPTION_CLASS(illegal_instruction)
DECLARE_EXCEPTION_CLASS(noncontinuable_exception)
DECLARE_EXCEPTION_CLASS(stack_overflow)
DECLARE_EXCEPTION_CLASS(invalid_disposition)
DECLARE_EXCEPTION_CLASS(guard_page)
DECLARE_EXCEPTION_CLASS(invalid_handle)
DECLARE_EXCEPTION_CLASS(microsoft_cpp)
The original class came from this very useful article:
Bash job control involves multiple processes, not multiple threads.
You can execute a command in background with the &
suffix.
You can wait for completion of a background command with the wait
command.
You can execute multiple commands in parallel by separating them with |
. This provides also a synchronization mechanism, since stdout of a command at left of |
is connected to stdin of command at right.
For people landing here from google like me and just want to build containers using multiple docker-compose files with one shared service:
Sometimes you have different projects that would share e.g. a database docker container. Only the first run should start the DB-Docker, the second should be detect that the DB is already running and skip this. To achieve such a behaviour we need the Dockers to lay in the same network and in the same project. Also the docker container name needs to be the same.
1st: Set the same network and container name in docker-compose
docker-compose in project 1:
version: '3'
services:
service1:
depends_on:
- postgres
# ...
networks:
- dockernet
postgres:
container_name: project_postgres
image: postgres:10-alpine
restart: always
# ...
networks:
- dockernet
networks:
dockernet:
docker-compose in project 2:
version: '3'
services:
service2:
depends_on:
- postgres
# ...
networks:
- dockernet
postgres:
container_name: project_postgres
image: postgres:10-alpine
restart: always
# ...
networks:
- dockernet
networks:
dockernet:
2nd: Set the same project using -p
param or put both files in the same directory.
docker-compose -p {projectname} up
Value added:
Session.getInstance()
recommended over Session.getDefaultInstance()
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.activation.DataHandler;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
public class Gmailer {
private static final Logger LOGGER = Logger.getLogger(Gmailer.class.getName());
public static void main(String[] args) {
send();
}
public static void send() {
Transport transport = null;
try {
String accountEmail = "[email protected]";
String accountAppPassword = "";
String displayName = "Display-Name ?";
String replyTo = "[email protected]";
String to = "[email protected]";
String cc = "[email protected]";
String bcc = "[email protected]";
String subject = "Subject ?";
String message = "<span style='color: red;'>?</span>";
String type = "html"; // or "plain"
String mimeTypeWithEncoding = "text/" + type + "; charset=" + StandardCharsets.UTF_8.name();
File attachmentFile = new File("Attachment.pdf");
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
String attachmentMimeType = "application/pdf";
byte[] bytes = ...; // read file to byte array
Properties properties = System.getProperties();
properties.put("mail.debug", "true");
// i found that this is the only property necessary for a modern java mail version
properties.put("mail.smtp.starttls.enable", "true");
// https://javaee.github.io/javamail/FAQ#getdefaultinstance
Session session = Session.getInstance(properties);
MimeMessage mimeMessage = new MimeMessage(session);
// probably best to use the account email address, to avoid landing in spam or blacklists
// not even sure if the server would accept a differing from address
InternetAddress from = new InternetAddress(accountEmail);
from.setPersonal(displayName, StandardCharsets.UTF_8.name());
mimeMessage.setFrom(from);
mimeMessage.setReplyTo(InternetAddress.parse(replyTo));
mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
mimeMessage.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
mimeMessage.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc));
mimeMessage.setSubject(subject, StandardCharsets.UTF_8.name());
MimeMultipart multipart = new MimeMultipart();
MimeBodyPart messagePart = new MimeBodyPart();
messagePart.setContent(mimeMessage, mimeTypeWithEncoding);
multipart.addBodyPart(messagePart);
MimeBodyPart attachmentPart = new MimeBodyPart();
attachmentPart.setDataHandler(new DataHandler(new ByteArrayDataSource(bytes, attachmentMimeType)));
attachmentPart.setFileName(attachmentFile.getName());
multipart.addBodyPart(attachmentPart);
mimeMessage.setContent(multipart);
transport = session.getTransport();
transport.connect("smtp.gmail.com", 587, accountEmail, accountAppPassword);
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
}
catch(Exception e) {
// I prefer to bubble up exceptions, so the caller has the info that someting went wrong, and gets a chance to handle it.
// I also prefer not to force the exception in the signature.
throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e);
}
finally {
if(transport != null) {
try {
transport.close();
}
catch(Exception e) {
LOGGER.log(Level.WARNING, "failed to close java mail transport: " + e);
}
}
}
}
}
This worked for me:
This could happen on any device, therefore in your app you will have to make sure to handle this error correctly. I reckon you give the user feedback why Login With Facebook failed and ask the user to check their Facebook settings on their device.
- (void)facebookSessionStateChanged:(FBSession *)session state:(FBSessionState)state error:(NSError *)error
{
switch (state) {
case FBSessionStateOpen:
// handle successful login here
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
[FBSession.activeSession closeAndClearTokenInformation];
if (error) {
// handle error here, for example by showing an alert to the user
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Could not login with Facebook"
message:@"Facebook login failed. Please check your Facebook settings on your phone."
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}
break;
default:
break;
}
<style name="WhiteTextWithShadow" parent="@android:style/TextAppearance">
<item name="android:shadowDx">1</item>
<item name="android:shadowDy">1</item>
<item name="android:shadowRadius">1</item>
<item name="android:shadowColor">@android:color/black</item>
<item name="android:textColor">@android:color/white</item>
</style>
then use as
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp"
tools:text="Today, May 21"
style="@style/WhiteTextWithShadow"/>
You could do this:
echo "<script>alert('Successfully Updated'); window.location = './edit.php';</script>";
You need to use ECHO
. Also, put the quotes around the entire file path if it contains spaces.
One other note, use >
to overwrite a file if it exists or create if it does not exist. Use >>
to append to an existing file or create if it does not exist.
Overwrite the file with a blank line:
ECHO.>"C:\My folder\Myfile.log"
Append a blank line to a file:
ECHO.>>"C:\My folder\Myfile.log"
Append text to a file:
ECHO Some text>>"C:\My folder\Myfile.log"
Append a variable to a file:
ECHO %MY_VARIABLE%>>"C:\My folder\Myfile.log"
Here I resolved this issue
The reason behind this issue is, there is already an application with the same package name in the phone, but you cannot find it in phone menu(U already made the un-installation but actually its still in your phone).
To see the application go to phones SETTINGS -> APPS. There you can see the application, but inside that the UNINSTALL button may be disabled. click on the menu overflow button to see Uninstall for all users.
After performed uninstalled for all users I have successfully installed my signed apk. You can also use adb to uninstall the app from phone.
adb uninstall package name
In addition to this, if your mobile supports multiple users then check if respective app is not installed for other users. If it is installed for others then first uninstall previous app and try again
For a method that works with both C and C++, you might want to consider using the standard library function strtol().
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
string s = "abcd";
char * p;
long n = strtol( s.c_str(), & p, 16 );
if ( * p != 0 ) { //my bad edit was here
cout << "not a number" << endl;
}
else {
cout << n << endl;
}
}
Here is some SQL that actually make sense:
SELECT m.id FROM match m LEFT JOIN email e ON e.id = m.id WHERE e.id IS NULL
Simple is always better.
Directory Services/LDAP lookups can be used to serve this purpose. It involves some changes at infrastructure level, but most production environments have such provision
To get all the messages stored for the topic you can seek the consumer to the beginning and end of the stream for each partition and sum the results
List<TopicPartition> partitions = consumer.partitionsFor(topic).stream()
.map(p -> new TopicPartition(topic, p.partition()))
.collect(Collectors.toList());
consumer.assign(partitions);
consumer.seekToEnd(Collections.emptySet());
Map<TopicPartition, Long> endPartitions = partitions.stream()
.collect(Collectors.toMap(Function.identity(), consumer::position));
consumer.seekToBeginning(Collections.emptySet());
System.out.println(partitions.stream().mapToLong(p -> endPartitions.get(p) - consumer.position(p)).sum());
Typically with Angular you would be outputting these spans using the ngRepeat directive and (like in your case) each item would have an id. I know this is not true for all situations but it is typical if requesting data from a backend - objects in an array tend to have unique identifiers.
You can use this id to facilitate the toggling of classes on items in your list (see plunkr or code below).
Using the objects id's can also eliminate the undesirable effect when the $index (described in other answers) is messed up due to sorting in Angular.
Example Plunkr: http://plnkr.co/edit/na0gUec6cdMABK9L6drV
(basically apply the .active-selection class if the person.id is equal to $scope.activeClass - which we set when the user clicks an item.
Hope this helps someone, I've found expressions in ng-class to be very useful!
HTML
<ul>
<li ng-repeat="person in people"
data-ng-class="{'active-selection': person.id == activeClass}">
<a data-ng-click="selectPerson(person.id)">
{{person.name}}
</a>
</li>
</ul>
JS
app.controller('MainCtrl', function($scope) {
$scope.people = [{
id: "1",
name: "John",
}, {
id: "2",
name: "Lucy"
}, {
id: "3",
name: "Mark"
}, {
id: "4",
name: "Sam"
}];
$scope.selectPerson = function(id) {
$scope.activeClass = id;
console.log(id);
};
});
CSS:
.active-selection {
background-color: #eee;
}
I Hope below code will help someone ..!!! :)
jQuery(document).ready(function(){
jQuery("input[type=submit]").prop('disabled', true);
jQuery("input[name=textField]").focusin(function(){
jQuery("input[type=submit]").prop('disabled', false);
});
jQuery("input[name=textField]").focusout(function(){
var checkvalue = jQuery(this).val();
if(checkvalue!=""){
jQuery("input[type=submit]").prop('disabled', false);
}
else{
jQuery("input[type=submit]").prop('disabled', true);
}
});
}); /*DOC END*/
bundle exec rake db:rollback
rails destroy model <model_name>
When you generate a model, it creates a database migration. If you run 'destroy' on that model, it will delete the migration file, but not the database table. So before run
bundle exec rake db:rollback
Just for reference's sake. This is how to do it with JQuery (useful for instance when you cannot query by element id):
$('#iframe').get(0).contentWindow.document.body.innerHTML
you can also use this :
import requests
from bs4 import BeautifulSoup
import csv
url = "http://58.68.130.147/"
r = requests.get(url)
data = r.text
soup = BeautifulSoup(data, "html.parser")
get_details = soup.find_all("input", attrs={"name":"stainfo"})
for val in get_details:
get_val = val["value"]
print(get_val)
What I use everywhere :
Runtime.getRuntime().exec("pm clear me.myapp");
Executing above piece of code closes application and removes all databases and shared preferences
Its importante to note that these methods all must be run from the UI thread to work. See changing KeepScreenOn from javascript in Android cordova app
ran into this problem today and wanted to include NaNs so I replace them temporarily with "" (empty string). Please comment if you do not understand something :). This solution assumes that "" is not a relevant value for you. It should also work with numerical data (I have tested it sucessfully but not extensively) since pandas will infer the data type again after replacing "" with np.nan.
import pandas as pd
# create test data
df = pd.DataFrame({'test':['foo','bar',None,None,'foo'],
'test2':['bar',None,None,None,'bar'],
'test3':[None, 'foo','bar',None,None]})
# fill null values with '' to not lose them during groupby
# groupby all columns and calculate the length of the resulting groups
# rename the series obtained with groupby to "group_count"
# reset the index to get a DataFrame
# replace '' with np.nan (this reverts our first operation)
# sort DataFrame by "group_count" descending
df = (df.fillna('')\
.groupby(df.columns.tolist()).apply(len)\
.rename('group_count')\
.reset_index()\
.replace('',np.nan)\
.sort_values(by = ['group_count'], ascending = False))
df
test test2 test3 group_count
3 foo bar NaN 2
0 NaN NaN NaN 1
1 NaN NaN bar 1
2 bar NaN foo 1
Is there a command that does?
thread apply all where
fflush()
only flushes the buffering added by the stdio fopen()
layer, as managed by the FILE *
object. The underlying file itself, as seen by the kernel, is not buffered at this level. This means that writes that bypass the FILE *
layer, using fileno()
and a raw write()
, are also not buffered in a way that fflush()
would flush.
As others have pointed out, try not mixing the two. If you need to use "raw" I/O functions such as ioctl()
, then open()
the file yourself directly, without using fopen<()
and friends from stdio.
You probably don't want to do it that way. By putting an explicit sleep()
in your button-clicked event handler, you would actually lock up the whole UI for a second. One alternative is to use some sort of single-shot Timer. Create a TimerTask to change the background color back to the default color, and schedule it on the Timer.
Another possibility is to use a Handler. There's a tutorial about somebody who switched from using a Timer to using a Handler.
Incidentally, you can't pause a process. A Java (or Android) process has at least 1 thread, and you can only sleep threads.
What will you have? You'll probably end up with a default search and a search that you load from somewhere. Default search requires a default constructor, so make one like Dismissile has already suggested.
If you load the search criteria from elsewhere, then you should probably have some mapping logic.
I have used paramiko a bunch (nice) and pxssh (also nice). I would recommend either. They work a little differently but have a relatively large overlap in usage.
The below list of time format specifiers most commonly used.,
dd -- day of the month, from 01 through 31.
MM -- month, from 01 through 12.
yyyy -- year as a four-digit number.
hh -- hour, using a 12-hour clock from 01 to 12.
mm -- minute, from 00 through 59.
ss -- second, from 00 through 59.
HH -- hour, using a 24-hour clock from 00 to 23.
tt -- AM/PM designator.
Using the above you will be able to form a unique name to your file name.
Here i have provided example
string fileName = "fileName_" + DateTime.Now.ToString("MM-dd-yyyy_hh-mm-ss-tt") + ".pdf";
OR
If you don't prefer to use symbols you can try this also.,
string fileName = "fileName_" + DateTime.Now.ToString("MMddyyyyhhmmsstt") + ".pdf";
Hope this helps to someone now or in future. :)
The example implementation when you want to have an abstract class with implementation. Subclasses must:
In this case, the properties that are necessary for the implementation should not be available for use except for the abstract class and its own subclass.
internal abstract class AbstractClass
{
//Properties for parameterization from concrete class
protected abstract string Param1 { get; }
protected abstract string Param2 { get; }
//Internal fields need for manage state of object
private string var1;
private string var2;
internal AbstractClass(string _var1, string _var2)
{
this.var1 = _var1;
this.var2 = _var2;
}
internal void CalcResult()
{
//The result calculation uses Param1, Param2, var1, var2;
}
}
internal class ConcreteClassFirst : AbstractClass
{
private string param1;
private string param2;
protected override string Param1 { get { return param1; } }
protected override string Param2 { get { return param2; } }
public ConcreteClassFirst(string _var1, string _var2) : base(_var1, _var2) { }
internal void CalcParams()
{
//The calculation param1 and param2
}
}
internal class ConcreteClassSecond : AbstractClass
{
private string param1;
private string param2;
protected override string Param1 { get { return param1; } }
protected override string Param2 { get { return param2; } }
public ConcreteClassSecond(string _var1, string _var2) : base(_var1, _var2) { }
internal void CalcParams()
{
//The calculation param1 and param2
}
}
static void Main(string[] args)
{
string var1_1 = "val1_1";
string var1_2 = "val1_2";
ConcreteClassFirst concreteClassFirst = new ConcreteClassFirst(var1_1, var1_2);
concreteClassFirst.CalcParams();
concreteClassFirst.CalcResult();
string var2_1 = "val2_1";
string var2_2 = "val2_2";
ConcreteClassSecond concreteClassSecond = new ConcreteClassSecond(var2_1, var2_2);
concreteClassSecond.CalcParams();
concreteClassSecond.CalcResult();
//Param1 and Param2 are not visible in main method
}
This file works properly as it is: just copy and paste in your computer. Surfing on the web I have found this easy implementation on wikipedia page here. The page is in italian, so I re-wrote the code with some translations. Here there are almost the same informations but in english. ENJOY!
#include <iostream>
#include <complex>
#define MAX 200
using namespace std;
#define M_PI 3.1415926535897932384
int log2(int N) /*function to calculate the log2(.) of int numbers*/
{
int k = N, i = 0;
while(k) {
k >>= 1;
i++;
}
return i - 1;
}
int check(int n) //checking if the number of element is a power of 2
{
return n > 0 && (n & (n - 1)) == 0;
}
int reverse(int N, int n) //calculating revers number
{
int j, p = 0;
for(j = 1; j <= log2(N); j++) {
if(n & (1 << (log2(N) - j)))
p |= 1 << (j - 1);
}
return p;
}
void ordina(complex<double>* f1, int N) //using the reverse order in the array
{
complex<double> f2[MAX];
for(int i = 0; i < N; i++)
f2[i] = f1[reverse(N, i)];
for(int j = 0; j < N; j++)
f1[j] = f2[j];
}
void transform(complex<double>* f, int N) //
{
ordina(f, N); //first: reverse order
complex<double> *W;
W = (complex<double> *)malloc(N / 2 * sizeof(complex<double>));
W[1] = polar(1., -2. * M_PI / N);
W[0] = 1;
for(int i = 2; i < N / 2; i++)
W[i] = pow(W[1], i);
int n = 1;
int a = N / 2;
for(int j = 0; j < log2(N); j++) {
for(int i = 0; i < N; i++) {
if(!(i & n)) {
complex<double> temp = f[i];
complex<double> Temp = W[(i * a) % (n * a)] * f[i + n];
f[i] = temp + Temp;
f[i + n] = temp - Temp;
}
}
n *= 2;
a = a / 2;
}
free(W);
}
void FFT(complex<double>* f, int N, double d)
{
transform(f, N);
for(int i = 0; i < N; i++)
f[i] *= d; //multiplying by step
}
int main()
{
int n;
do {
cout << "specify array dimension (MUST be power of 2)" << endl;
cin >> n;
} while(!check(n));
double d;
cout << "specify sampling step" << endl; //just write 1 in order to have the same results of matlab fft(.)
cin >> d;
complex<double> vec[MAX];
cout << "specify the array" << endl;
for(int i = 0; i < n; i++) {
cout << "specify element number: " << i << endl;
cin >> vec[i];
}
FFT(vec, n, d);
cout << "...printing the FFT of the array specified" << endl;
for(int j = 0; j < n; j++)
cout << vec[j] << endl;
return 0;
}
Yet another (modern) way to solve it.
public class FileUtils {
public static void delete(File fileOrDirectory) {
if(fileOrDirectory != null && fileOrDirectory.exists()) {
if(fileOrDirectory.isDirectory() && fileOrDirectory.listFiles() != null) {
Arrays.stream(fileOrDirectory.listFiles())
.forEach(FileUtils::delete);
}
fileOrDirectory.delete();
}
}
}
On Android since API 26
public class FileUtils {
public static void delete(File fileOrDirectory) {
if(fileOrDirectory != null) {
delete(fileOrDirectory.toPath());
}
}
public static void delete(Path path) {
try {
if(Files.exists(path)) {
Files.walk(path)
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
// .peek(System.out::println)
.forEach(File::delete);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
The simple answer for this one is that you have an undeclared (null) variable. In this case it is $md5
. From the comment you put this needed to be declared elsewhere in your code
$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
The error was because you are trying to execute a method that does not exist.
PS C:\Users\Matt> $md5 | gm
TypeName: System.Security.Cryptography.MD5CryptoServiceProvider
Name MemberType Definition
---- ---------- ----------
Clear Method void Clear()
ComputeHash Method byte[] ComputeHash(System.IO.Stream inputStream), byte[] ComputeHash(byte[] buffer), byte[] ComputeHash(byte[] buffer, int offset, ...
The .ComputeHash()
of $md5.ComputeHash()
was the null valued expression. Typing in gibberish would create the same effect.
PS C:\Users\Matt> $bagel.MakeMeABagel()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $bagel.MakeMeABagel()
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
PowerShell by default allows this to happen as defined its StrictMode
When Set-StrictMode is off, uninitialized variables (Version 1) are assumed to have a value of 0 (zero) or $Null, depending on type. References to non-existent properties return $Null, and the results of function syntax that is not valid vary with the error. Unnamed variables are not permitted.
Attaching / Detaching
Eloquent also provides a few additional helper methods to make working with related models more convenient. For example, let's imagine a user can have many roles and a role can have many users. To attach a role to a user by inserting a record in the intermediate table that joins the models, use the attach method:
$user = App\User::find(1);
$user->roles()->attach($roleId);
When attaching a relationship to a model, you may also pass an array of additional data to be inserted into the intermediate table:
$user->roles()->attach($roleId, ['expires' => $expires]);
You can also use Sync if you want to remove old roles and only keep the new ones you are attaching now
$user->roles()->sync([1 => ['expires' => $expires], 2 => ['expires' => $expires]);
The default behaviour can be changed by passing a 'false' as a second argument. This will attach the roles with ids 1,2,3 without affecting the existing roles.
In this mode sync behaves similar to the attach method.
$user->roles()->sync([1 => ['expires' => $expires], 2 => ['expires' => $expires], false);
Reference: https://laravel.com/docs/5.4/eloquent-relationships
You do not need to use moment-timezone for this. The main moment.js library has full functionality for working with UTC and the local time zone.
var testDateUtc = moment.utc("2015-01-30 10:00:00");
var localDate = moment(testDateUtc).local();
From there you can use any of the functions you might expect:
var s = localDate.format("YYYY-MM-DD HH:mm:ss");
var d = localDate.toDate();
// etc...
Note that by passing testDateUtc
, which is a moment
object, back into the moment()
constructor, it creates a clone. Otherwise, when you called .local()
, it would also change the testDateUtc
value, instead of just the localDate
value. Moments are mutable.
Also note that if your original input contains a time zone offset such as +00:00
or Z
, then you can just parse it directly with moment
. You don't need to use .utc
or .local
. For example:
var localDate = moment("2015-01-30T10:00:00Z");
use spans. ex) <span style='color: #FF0000;'>January 30, 2011</span>
The ::
are used to dereference scopes.
const int x = 5;
namespace foo {
const int x = 0;
}
int bar() {
int x = 1;
return x;
}
struct Meh {
static const int x = 2;
}
int main() {
std::cout << x; // => 5
{
int x = 4;
std::cout << x; // => 4
std::cout << ::x; // => 5, this one looks for x outside the current scope
}
std::cout << Meh::x; // => 2, use the definition of x inside the scope of Meh
std::cout << foo::x; // => 0, use the definition of x inside foo
std::cout << bar(); // => 1, use the definition of x inside bar (returned by bar)
}
unrelated: cout and cin are not functions, but instances of stream objects.
EDIT fixed as Keine Lust suggested
Like others have mentioned, anything declared outside a class is global.
You can also create singletons:
class TestClass {
static let sharedInstance = TestClass()
// Anything else goes here
var number = 0
}
Whenever you want to use something from this class, you e.g. write:
TestClass.sharedInstance.number = 1
If you now write println(TestClass.sharedInstance.number)
from anywhere in your project you will print 1
to the log. This works for all kinds of objects.
tl;dr: Any time you want to make everything in a class global, add static let sharedInstance = YourClassName()
to the class, and address all values of the class with the prefix YourClassName.sharedInstance
I have implemented this function in my application through fragments using SurfaceView. The link to this stackoverflow question and its answer can be found here
Hope this helps :)
If you have loads of columns in your table and don't want to type out each one you can do it using a temporary table, like;
SELECT *
INTO #Temp
FROM Table WHERE Event_ID = "120"
GO
UPDATE #TEMP
SET Column = "Changed"
GO
INSERT INTO Table
SELECT *
FROM #Temp
This is the Kotlin version of the function posted by VVB. I used it in the ListView Adapter to implement the "go to next row first EditText when Enter key is pressed on the last EditText of current row" feature in the getView().
In the ListViewAdapter class, fun getView(), add lastEditText.setOnKeyListner as below:
lastEditText.setOnKeyListener { v, keyCode, event ->
var setOnKeyListener = false
if (keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_UP) {
try {
val nextRow = getViewByPosition(position + 1, parent as ListView) as LinearLayout
val nextET = nextRow.findViewById(R.id.firstEditText) as EditText
nextET.isFocusableInTouchMode = true
nextET.requestFocus()
} catch (e: Exception) {
// do nothing
}
setOnKeyListener = true
}
setOnKeyListener
}
add the fun getViewByPosition() after fun getView() as below:
private fun getViewByPosition(pos: Int, listView: ListView): View? {
val firstListItemPosition: Int = listView.firstVisiblePosition
val lastListItemPosition: Int = firstListItemPosition + listView.childCount - 1
return if (pos < firstListItemPosition || pos > lastListItemPosition) {
listView.adapter.getView(pos, null, listView)
} else {
val childIndex = pos + listView.headerViewsCount - firstListItemPosition
listView.getChildAt(childIndex)
}
}
My take on this for future people watching this:
This could also happen if you're using: <?
instead of <?php
.
To demonstrate how the USING and ON clauses work, let's assume we have the following post
and post_comment
database tables, which form a one-to-many table relationship via the post_id
Foreign Key column in the post_comment
table referencing the post_id
Primary Key column in the post
table:
The parent post
table has 3 rows:
| post_id | title |
|---------|-----------|
| 1 | Java |
| 2 | Hibernate |
| 3 | JPA |
and the post_comment
child table has the 3 records:
| post_comment_id | review | post_id |
|-----------------|-----------|---------|
| 1 | Good | 1 |
| 2 | Excellent | 1 |
| 3 | Awesome | 2 |
Traditionally, when writing an INNER JOIN
or LEFT JOIN
query, we happen to use the ON clause to define the join condition.
For example, to get the comments along with their associated post title and identifier, we can use the following SQL projection query:
SELECT
post.post_id,
title,
review
FROM post
INNER JOIN post_comment ON post.post_id = post_comment.post_id
ORDER BY post.post_id, post_comment_id
And, we get back the following result set:
| post_id | title | review |
|---------|-----------|-----------|
| 1 | Java | Good |
| 1 | Java | Excellent |
| 2 | Hibernate | Awesome |
When the Foreign Key column and the column it references have the same name, we can use the USING clause, like in the following example:
SELECT
post_id,
title,
review
FROM post
INNER JOIN post_comment USING(post_id)
ORDER BY post_id, post_comment_id
And, the result set for this particular query is identical to the previous SQL query that used the ON clause:
| post_id | title | review |
|---------|-----------|-----------|
| 1 | Java | Good |
| 1 | Java | Excellent |
| 2 | Hibernate | Awesome |
The USING clause works for Oracle, PostgreSQL, MySQL, and MariaDB. SQL Server doesn't support the USING clause, so you need to use the ON clause instead.
The USING clause can be used with INNER, LEFT, RIGHT, and FULL JOIN statements.
SELECT *
Now, if we change the previous ON clause query to select all columns using SELECT *
:
SELECT *
FROM post
INNER JOIN post_comment ON post.post_id = post_comment.post_id
ORDER BY post.post_id, post_comment_id
We are going to get the following result set:
| post_id | title | post_comment_id | review | post_id |
|---------|-----------|-----------------|-----------|---------|
| 1 | Java | 1 | Good | 1 |
| 1 | Java | 2 | Excellent | 1 |
| 2 | Hibernate | 3 | Awesome | 2 |
As you can see, the
post_id
is duplicated because both thepost
andpost_comment
tables contain apost_id
column.
SELECT *
On the other hand, if we run a SELECT *
query that features the USING clause for the JOIN condition:
SELECT *
FROM post
INNER JOIN post_comment USING(post_id)
ORDER BY post_id, post_comment_id
We will get the following result set:
| post_id | title | post_comment_id | review |
|---------|-----------|-----------------|-----------|
| 1 | Java | 1 | Good |
| 1 | Java | 2 | Excellent |
| 2 | Hibernate | 3 | Awesome |
You can see that this time, the
post_id
column is deduplicated, so there is a singlepost_id
column being included in the result set.
If the database schema is designed so that Foreign Key column names match the columns they reference, and the JOIN conditions only check if the Foreign Key column value is equal to the value of its mirroring column in the other table, then you can employ the USING clause.
Otherwise, if the Foreign Key column name differs from the referencing column or you want to include a more complex join condition, then you should use the ON clause instead.
It is possible to create instances of Void
if you change the security manager, so something like this:
static Void getVoid() throws SecurityException, InstantiationException,
IllegalAccessException, InvocationTargetException {
class BadSecurityManager extends SecurityManager {
@Override
public void checkPermission(Permission perm) { }
@Override
public void checkPackageAccess(String pkg) { }
}
System.setSecurityManager(badManager = new BadSecurityManager());
Constructor<?> constructor = Void.class.getDeclaredConstructors()[0];
if(!constructor.isAccessible()) {
constructor.setAccessible(true);
}
return (Void) constructor.newInstance();
}
Obviously this is not all that practical or safe; however, it will return an instance of Void
if you are able to change the security manager.
select *
from YourTable
where ','+replace(col, ' ', '')+',' like '%,Cat,%'
Here you go:
div{
display: none;
}
document.querySelector("button").addEventListener("click", function(){
document.querySelector("div").style.display = "block";
});
<div>blah blah blah</div>
<button>Show</button>
LIVE DEMO: http://jsfiddle.net/DerekL/p78Qq/
Use cmp command. Refer to Binary Files and Forcing Text Comparisons for more information.
cmp -b file1 file2
Use a for
loop instead of .forEach()
var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false
for(var call of myObj) {
console.log(call)
var a = call['a'], b = call['b']
if(a == null || b == null) {
result = false
break
}
}
Oh, dear. A few little problems...
As pointed out by others, you need to quote to protect against empty/space-containing entries, and use the !delayed_expansion! facility.
Two other matters of which you should be aware:
First, set/p
will assign a user-input value to a variable. That's not news - but the gotcha is that pressing enter
in response will leave the variable UNCHANGED - it will not ASSIGN a zero-length string to the variable (hence deleting the variable from the environment.) The safe method is:
set "var="
set /p var=
That is, of course, if you don't WANT enter
to repeat the existing value.
Another useful form is
set "var=default"
set /p var=
or
set "var=default"
set /p "var=[%var%]"
(which prompts with the default value; !var!
if in a block statement with delayedexpansion)
Second issue is that on some Windows versions (although W7 appears to "fix" this issue) ANY label - including a :: comment
(which is a broken-label) will terminate any 'block' - that is, parenthesised compound statement)
As of October 2014:
For latest remote version:
npm view <module_name> version
Note, version is singular.
If you'd like to see all available (remote) versions, then do:
npm view <module_name> versions
Note, versions is plural. This will give you the full listing of versions to choose from.
To get the version you actually have locally you could use:
npm list --depth=0 | grep <module_name>
Note, even with package.json declaring your versions, the installed version might actually differ slightly - for instance if tilda was used in the version declaration
Should work across NPM versions 1.3.x, 1.4.x, 2.x and 3.x
Sometimes, PHP will emit a X-Powered-By:
response header which you can look at e.g. using Firebug.
If this setting (controlled by the ini setting expose_php
) is turned off (it often is), there is no way to tell the PHP version used - and rightly so. What PHP version is running is none of the outside world's business, and it's good to obscure this from a security perspective.
you can use show
instead of shown
for making the function to load just before modal open, instead of after modal open.
$('#code').on('show.bs.modal', function (e) {
// do something...
})
As the warning message states, the SDK location should not contain whitespace.
Your SDK is at C:\Users\Giacomo B\AppData\Local\Android\sdk
. There is a whitespace character in Giacomo B
.
The easiest solution is to move the SDK somewhere else, where there is no space or other whitespace character in the path, such as C:\Android\sdk
. You can point both Android Studio installations to the new location.
svn copy http://URL/svn/trukSource http://URL/svn/tagDestination -m "Test tag code"
$error[0].Exception | Select-object Data
All you have to do change URL path. This command will create new dir "tagDestination". The second line will be let know you the full error details if any occur. Create svn env variable if not created. Can check (Cmd:- set, Powershell:- Get-ChildItem Env:) Default path is "C:\Program Files\TortoiseSVN\bin\TortoiseProc.exe"
<div id="invocieContainer">
<div class="row">
...Your html Page content here....
</div>
</div>
<script src="/Scripts/printThis.js"></script>
<script>
$(document).on("click", "#btnPrint", function(e) {
e.preventDefault();
e.stopPropagation();
$("#invocieContainer").printThis({
debug: false, // show the iframe for debugging
importCSS: true, // import page CSS
importStyle: true, // import style tags
printContainer: true, // grab outer container as well as the contents of the selector
loadCSS: "/Content/bootstrap.min.css", // path to additional css file - us an array [] for multiple
pageTitle: "", // add title to print page
removeInline: false, // remove all inline styles from print elements
printDelay: 333, // variable print delay; depending on complexity a higher value may be necessary
header: null, // prefix to html
formValues: true // preserve input/form values
});
});
</script>
For printThis.js souce code, copy and pase below URL in new tab https://raw.githubusercontent.com/jasonday/printThis/master/printThis.js
The official instructions seem to be here: https://docs.anaconda.com/anaconda/install/uninstall/
but if you like me that didn't work for some reason and for some reason your conda was installed somewhere else with telling you do this:
rm -rf ~/opt
I have no idea why it was saved there but that's what did it for me.
This was useful to me in fixing my conda installation (if that is the reason you are uninstalling it in the first place like me): https://stackoverflow.com/a/60902863/1601580 that ended up fixing it for me. Not sure why conda was acting weird in the first place or installing things wrongly in the first place though...
I usually run this command when I have to copy my ssh-key
:
cat ~/.ssh/id_rsa.pub | pbcopy
ctrl+v
anywhere else.
See this link http://momentjs.com/docs/#/displaying/unix-timestamp-milliseconds/
valueOf()
is the function you're looking for.
Editing my answer (OP wants milliseconds of today, not since epoch)
You want the milliseconds()
function OR you could go the route of moment().valueOf()
Commands:
To start the kafka:
$ nohup ~/kafka/bin/kafka-server-start.sh ~/kafka/config/server.properties > ~/kafka/kafka.log 2>&1 &
To list out all the topic on on kafka;
$ bin/kafka-topics.sh --list --zookeeper localhost:2181
To check the data is landing on kafka topic and to print it out;
$ bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic your_topic_name --from-beginning
EF Core: Using "ThenInclude" to load mutiple levels: For example:
var blogs = context.Blogs
.Include(blog => blog.Posts)
.ThenInclude(post => post.Author)
.ThenInclude(author => author.Photo)
.ToList();
By default a span
is an inline
element... so that's not the default behavior.
You can make the span
behave that way by adding display: block;
to your CSS.
span {
display: block;
width: 100px;
}
I like @ninjagecko's answer the most.
This would also work:
for Python 2.x
isinstance(n, (int, long, float))
Python 3.x doesn't have long
isinstance(n, (int, float))
there is also type complex for complex numbers
If the child is always going to be a specific tag then you could do it like this
function test(el)
{
var children = el.getElementsByTagName('div');// any tag could be used here..
for(var i = 0; i< children.length;i++)
{
if (children[i].getAttribute('id') == 'child') // any attribute could be used here
{
// do what ever you want with the element..
// children[i] holds the element at the moment..
}
}
}
I'm using, Angular CLI: 8.1.2 Node: 12.14.1 OS: win32 x64
Strangely, this helped me
npm cache clean --force
npm uninstall @angular/cli
npm install @angular/[email protected]
Write code in this manner ...
<canvas id="canvas" width="640" height="480"></canvas>
<script>
var Grid = function(width, height) {
...
this.draw = function() {
var canvas = document.getElementById("canvas");
if(canvas.getContext) {
var context = canvas.getContext("2d");
for(var i = 0; i < width; i++) {
for(var j = 0; j < height; j++) {
if(isLive(i, j)) {
context.fillStyle = "lightblue";
}
else {
context.fillStyle = "yellowgreen";
}
context.fillRect(i*15, j*15, 14, 14);
}
}
}
}
}
First write canvas tag and then write script tag. And write script tag in body.
This misled me a bit - it should be setImageResource
instead of setBackgroundResource
:) !!
The following works fine :
ImageButton btn = (ImageButton)findViewById(R.id.imageButton1);
btn.setImageResource(R.drawable.actions_record);
while when using the setBackgroundResource
the actual imagebutton's image
stays while the background image is changed which leads to a ugly looking imageButton object
Thanks.
If you split the filename on underscore and dot, you get an array of 3 strings. Join the first and third string, i.e. with index 0 and 2
$x = '237801_201011221155.xml'
( $x.split('_.')[0] , $x.split('_.')[2] ) -join '.'
Another way to do the same thing:
'237801_201011221155.xml'.split('_.')[0,2] -join '.'
Here's a dead simple usage of multiprocessing.Queue
and multiprocessing.Process
that allows callers to send an "event" plus arguments to a separate process that dispatches the event to a "do_" method on the process. (Python 3.4+)
import multiprocessing as mp
import collections
Msg = collections.namedtuple('Msg', ['event', 'args'])
class BaseProcess(mp.Process):
"""A process backed by an internal queue for simple one-way message passing.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.queue = mp.Queue()
def send(self, event, *args):
"""Puts the event and args as a `Msg` on the queue
"""
msg = Msg(event, args)
self.queue.put(msg)
def dispatch(self, msg):
event, args = msg
handler = getattr(self, "do_%s" % event, None)
if not handler:
raise NotImplementedError("Process has no handler for [%s]" % event)
handler(*args)
def run(self):
while True:
msg = self.queue.get()
self.dispatch(msg)
Usage:
class MyProcess(BaseProcess):
def do_helloworld(self, arg1, arg2):
print(arg1, arg2)
if __name__ == "__main__":
process = MyProcess()
process.start()
process.send('helloworld', 'hello', 'world')
The send
happens in the parent process, the do_*
happens in the child process.
I left out any exception handling that would obviously interrupt the run loop and exit the child process. You can also customize it by overriding run
to control blocking or whatever else.
This is really only useful in situations where you have a single worker process, but I think it's a relevant answer to this question to demonstrate a common scenario with a little more object-orientation.
They use a combination of IP geolocation, as well as comparing the results of a scan for nearby wireless networks with a database on their side (which is built by collecting GPS coordinates alongside wifi scan data when Android phone users use their GPS)
@Test(expected = Exception.class)
Tells Junit that exception is the expected result so test will be passed (marked as green) when exception is thrown.
For
@Test
Junit will consider test as failed if exception is thrown, provided it's an unchecked exception. If the exception is checked it won't compile and you will need to use other methods. This link might help.
@media print{_x000D_
body{_x000D_
visibility: hidden; /* no print*/_x000D_
}_x000D_
.print{_x000D_
_x000D_
visibility:visible; /*print*/_x000D_
}_x000D_
}
_x000D_
<body>_x000D_
<div class="noprint"> <!---no print--->_x000D_
<div class="noprint"> <!---no print--->_x000D_
<div class="print"> <!---print--->_x000D_
<div class="print"> <!---print--->_x000D_
_x000D_
_x000D_
</body>
_x000D_
MarvinS.-
Try:
$.ajax({
url: uri+'?js',
success: function(data) {
var imgAttr = $("img", data).attr('src');
var htmlCode = $(data).html();
$('#imgSrc').html(imgAttr);
$('#fullHtmlOutput').html(htmlCode);
}
});
This should load the whole html block from data into #fullHtmlOutput and the src of the image into #imgSrc.
Yes that is correct. "Boolean variables only have two possible values: true (1) and false (0)." cpp tutorial on boolean values
Try using the overflow
CSS property. There are also separate properties to define the behaviour of just horizontal overflow (overflow-x
) and vertical overflow (overflow-y
).
Since you only want the vertical scroll, try this:
table {
height: 500px;
overflow-y: scroll;
}
EDIT:
Apparently <table>
elements don't respect the overflow
property. This appears to be because <table>
elements are not rendered as display: block
by default (they actually have their own display type). You can force the overflow
property to work by setting the <table>
element to be a block type:
table {
display: block;
height: 500px;
overflow-y: scroll;
}
Note that this will cause the element to have 100% width, so if you don't want it to take up the entire horizontal width of the page, you need to specify an explicit width for the element as well.
The debugger is making it simpler, because you don't want to step through the actual code that the compiler creates.
If the switch contains more than five items, it's implemented using a lookup table or hash table, otherwise it's implemeneted using an if..else.
See the closely related question is “else if” faster than “switch() case” ?.
Other languages than C# will of course implement it more or less differently, but a switch is generally more efficient.
For some reason none of the results above worked for me.
This selects the last 365 days.
SELECT ... From ... WHERE date BETWEEN CURDATE() - INTERVAL 1 YEAR AND CURDATE()
Used font-size:0
in parent TD
which has the image.
These have the same end result, but I would simply add that using the literal syntax can help one become accustomed to the syntax of JSON (a string-ified subset of JavaScript literal object syntax), so it might be a good practice to get into.
One other thing: you might have subtle errors if you forget to use the new
operator. So, using literals will help you avoid that problem.
Ultimately, it will depend on the situation as well as preference.
To fix your issue, i have made few changes in bla.js and it is working,
var foo= function (req, res, next) {
console.log('inside foo');
return ("foo");
}
var bar= function(req, res, next) {
this.foo();
}
module.exports = {bar,foo};
and no modification in app.js
var bla = require('./bla.js');
console.log(bla.bar());
Save it as a CSV file and import it as a flat source file.
You can stablish specific toolbar for div
div::-webkit-scrollbar {
width: 12px;
}
div::-webkit-scrollbar-track {
-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
border-radius: 10px;
}
see demo in jsfiddle.net
This hides the warning message:
jQuery.event.special.touchstart = {
setup: function( _, ns, handle ) {
this.addEventListener("touchstart", handle, { passive: !ns.includes("noPreventDefault") });
}
};
Open xampp application, then do the following:
go to: volumes,
click the [mount] button, and
finally click explore.
In config.php add or edit the following lines to this:
------------------------------------------------------
$config['log_threshold'] = 4; // (1/2/3)
$config['log_path'] = '/home/path/to/application/logs/';
Run this command in the terminal:
----------------------------------
sudo chmod -R 777 /home/path/to/application/logs/
I'm sure you know that a std::vector<X>
stores a whole bunch of X
objects, right? But if you have a std::map<X, Y>
, what it actually stores is a whole bunch of std::pair<const X, Y>
s. That's exactly what a map is - it pairs together the keys and the associated values.
When you iterate over a std::map
, you're iterating over all of these std::pair
s. When you dereference one of these iterators, you get a std::pair
containing the key and its associated value.
std::map<std::string, int> m = /* fill it */;
auto it = m.begin();
Here, if you now do *it
, you will get the the std::pair
for the first element in the map.
Now the type std::pair
gives you access to its elements through two members: first
and second
. So if you have a std::pair<X, Y>
called p
, p.first
is an X
object and p.second
is a Y
object.
So now you know that dereferencing a std::map
iterator gives you a std::pair
, you can then access its elements with first
and second
. For example, (*it).first
will give you the key and (*it).second
will give you the value. These are equivalent to it->first
and it->second
.
Check if a directory exists and create it if necessary?
The direct answer to this is, assuming a simple situation where you don't expect other users or processes to be messing with your directory:
if not os.path.exists(d):
os.makedirs(d)
or if making the directory is subject to race conditions (i.e. if after checking the path exists, something else may have already made it) do this:
import errno
try:
os.makedirs(d)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
But perhaps an even better approach is to sidestep the resource contention issue, by using temporary directories via tempfile
:
import tempfile
d = tempfile.mkdtemp()
Here's the essentials from the online doc:
mkdtemp(suffix='', prefix='tmp', dir=None) User-callable function to create and return a unique temporary directory. The return value is the pathname of the directory. The directory is readable, writable, and searchable only by the creating user. Caller is responsible for deleting the directory when done with it.
pathlib.Path
with exist_ok
There's a new Path
object (as of 3.4) with lots of methods one would want to use with paths - one of which is mkdir
.
(For context, I'm tracking my weekly rep with a script. Here's the relevant parts of code from the script that allow me to avoid hitting Stack Overflow more than once a day for the same data.)
First the relevant imports:
from pathlib import Path
import tempfile
We don't have to deal with os.path.join
now - just join path parts with a /
:
directory = Path(tempfile.gettempdir()) / 'sodata'
Then I idempotently ensure the directory exists - the exist_ok
argument shows up in Python 3.5:
directory.mkdir(exist_ok=True)
Here's the relevant part of the documentation:
If
exist_ok
is true,FileExistsError
exceptions will be ignored (same behavior as thePOSIX mkdir -p
command), but only if the last path component is not an existing non-directory file.
Here's a little more of the script - in my case, I'm not subject to a race condition, I only have one process that expects the directory (or contained files) to be there, and I don't have anything trying to remove the directory.
todays_file = directory / str(datetime.datetime.utcnow().date())
if todays_file.exists():
logger.info("todays_file exists: " + str(todays_file))
df = pd.read_json(str(todays_file))
Path
objects have to be coerced to str
before other APIs that expect str
paths can use them.
Perhaps Pandas should be updated to accept instances of the abstract base class, os.PathLike
.
Yes, Microsoft announced that xamrin is now free with VS15 and other latest versions.
Use setOnItemClickListener() api in your activity. Following is the sample.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<> parent, View view, int position, long id)
{
// your code here.
}
});
We can define maximum pool size in following way:
<pool>
<min-pool-size>5</min-pool-size>
<max-pool-size>200</max-pool-size>
<prefill>true</prefill>
<use-strict-min>true</use-strict-min>
<flush-strategy>IdleConnections</flush-strategy>
</pool>
Looks like you missed some options, try to add:
position: relative;
top: 25px;
A bit late but this is what I'm doing with journald
. It's pretty powerful.
You need to be running your docker containers on an OS with systemd-journald
.
docker run -d --log-driver=journald myapp
This pipes the whole lot into host's journald which takes care of stuff like log pruning, storage format etc and gives you some cool options for viewing them:
journalctl CONTAINER_NAME=myapp -f
which will feed it to your console as it is logged,
journalctl CONTAINER_NAME=myapp > output.log
which gives you the whole lot in a file to take away, or
journalctl CONTAINER_NAME=myapp --since=17:45
Plus you can still see the logs via docker logs ....
if that's your preference.
No more > my.log
or -v "/apps/myapp/logs:/logs"
etc
I have a Droid 3 (Verizon). I went to Motorola here and found the driver for the device 'Motorola ADB Interface' which was showing in device manager. It's kind of a big download for just the driver, but during installation it found it and installed correctly.
The presence of this data-attribute tells Bootstrap to switch between visual or a logical states of another element on user interaction.
It is used to show modals, tab content, tooltips and popover menus as well as setting a pressed-state for a toggle-button. It is used in multiple ways without a clear documentation.
For me the issue seems to have been caused by power failure. Restarting the server computer solved it.
You can do this (YAML block):
~~~
# This is a
# multiline
# comment
...
I tried with latex output only, please confirm for others.
No, you cant really do this by adding variables to the querystring portion of the JS file URL. If its writing the portion of code to parse the string that bothers you, perhaps another way would be to json encode your variables and put them in something like the rel attribute of the tag? I don't know how valid this is in terms of HTML validation, if thats something you're very worried about. Then you just need to find the rel attribute of the script and then json_decode that.
eg
<script type='text/javascript' src='file.js' rel='{"myvar":"somevalue","anothervar":"anothervalue"}'></script>
In case you want an awk-only solution without creating a temporary file and usable with version!=(gawk 4.1.0):
awk '{a[b++]=$0} END {for(c=0;c<=b;c++)print a[c]>ARGV[1]}' file
Here is my one liner. Here 'c' is the name of the column
df.select('c').withColumn('isNull_c',F.col('c').isNull()).where('isNull_c = True').count()
I find it far easier to change the display of the labels to inline-block and set a width
label {
display: inline-block;
width:100px;
text-align: right;
}
For those of you that prefer a more concise, easier to read lambda coding style...
This example removes all non-alphanumeric and white space characters from a wide string. You can mix it up with any of the other ctype.h helper functions to remove complex-looking character-based tests.
(I'm not sure how these functions would handle CJK languages, so walk softly there.)
// Boring C loops: 'for(int i=0;i<str.size();i++)'
// Boring C++ eqivalent: 'for(iterator iter=c.begin; iter != c.end; ++iter)'
See if you don't find this easier to understand than noisy C/C++ for/iterator loops:
TSTRING label = _T("1. Replen & Move RPMV");
TSTRING newLabel = label;
set<TCHAR> badChars; // Use ispunct, isalpha, isdigit, et.al. (lambda version, with capture list parameter(s) example; handiest thing since sliced bread)
for_each(label.begin(), label.end(), [&badChars](TCHAR n){
if (!isalpha(n) && !isdigit(n))
badChars.insert(n);
});
for_each(badChars.begin(), badChars.end(), [&newLabel](TCHAR n){
newLabel.erase(std::remove(newLabel.begin(), newLabel.end(), n), newLabel.end());
});
newLabel results after running this code: "1ReplenMoveRPMV"
This is just academic, since it would clearly be more precise, concise and efficient to combine the 'if' logic from lambda0 (first for_each) into the single lambda1 (second for_each), if you have already established which characters are the "badChars".
Also we can use streams for obtain command output:
public static void main(String[] args) throws IOException {
Runtime runtime = Runtime.getRuntime();
String[] commands = {"free", "-h"};
Process process = runtime.exec(commands);
BufferedReader lineReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
lineReader.lines().forEach(System.out::println);
BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
errorReader.lines().forEach(System.out::println);
}
No, As others said, "There is no Pointer in PHP." and I add, there is nothing RAM_related in PHP.
And also all answers are clear. But there were points being left out that I could not resist!
At first I have to say that PHP is really powerful language, knowing there is a construct named "eval", so you can create your PHP code while running it! (really cool!)
although there is the danger of PHP_Injection which is far more destructive that SQL_Injection. Beware!
example:
Code:
$a='echo "Hello World.";';
eval ($a);
Output
Hello World.
So instead of using a pointer to act like another Variable, You Can Make A Variable From Scratch!
$GLOBAL variable is pretty useful, You can access all variables by using its keys.
example:
Code:
$three="Hello";$variable=" Amazing ";$names="World";
$arr = Array("three","variable","names");
foreach($arr as $VariableName)
echo $GLOBALS[$VariableName];
Output
Hello Amazing World
Note: Other superglobals can do the same trick in smaller scales.
You can add as much as '$'s you want before a variable, If you know what you're doing.
example:
Code:
$a="b";
$b="c";
$c="d";
$d="e";
$e="f";
echo $a."-";
echo $$a."-"; //Same as $b
echo $$$a."-"; //Same as $$b or $c
echo $$$$a."-"; //Same as $$$b or $$c or $d
echo $$$$$a; //Same as $$$$b or $$$c or $$d or $e
Output
b-c-d-e-f
Reference are so close to pointers, but you may want to check this link for more clarification.
example 1:
Code:
$a="Hello";
$b=&$a;
$b="yello";
echo $a;
Output
yello
example 2:
Code:
function junk(&$tion)
{$GLOBALS['a'] = &$tion;}
$a="-Hello World<br>";
$b="-To You As Well";
echo $a;
junk($b);
echo $a;
Output
-Hello World
-To You As Well
Hope It Helps.
Tested with 2.3.7 Play framework. Works well.
./{application}/bin/{executable} -Dhttp.port=5000
Also remember that with a command like:
bower search twitter
You get a result with a list of any package related to twitter. This way you are up to date of everything regarding Twitter and Bower like for instance knowing if there is brand new bower component.
If the aforementioned answers don't help then check whether the backend server is up and running or not as in my case the server crashed and this error turns out to be totally misleading.
As I have struggled with this issue twice (even after fresh kubuntu 15.04 install) and installing freetype did not solve anything, I investigated further.
The solution:
From github issue:
This bug only occurs if pkg-config is not installed;
a simple
sudo apt-get install pkg-config
will shore up the include paths for now.
After this installation proceeds smoothly.
Every RDBMS is a DBMS, but the opposite is not true: RDBMS is a DBMS which is based on the relational model, but not every DBMS must be relational.
However, since RDBMS are most common, sometimes the term DBMS is used to denote a DBMS which is NOT relational. It depends on the context.
You can use literal quoting:
stmt := q'[insert into MY_TBL (Col) values('ER0002')]';
Documentation for literals can be found here.
Alternatively, you can use two quotes to denote a single quote:
stmt := 'insert into MY_TBL (Col) values(''ER0002'')';
The literal quoting mechanism with the Q syntax is more flexible and readable, IMO.
Just a side info, is_integer
is doing internally:
import math
isInteger = (math.floor(x) == x)
Not exactly in python, but the cpython implementation is implemented as mentioned above.
If you want to consider null values equality too, try the following
select column1, column2,
case
when column1 is NULL and column2 is NULL then 'true'
when column1=column2 then 'true'
else 'false'
end
from table;
The effect you want is to treat the NULL as the largest possible date then replace it with NULL again upon completion:
SELECT RecordId, MIN(StartDate), NULLIF(MAX(COALESCE(EndDate,'9999-12-31')),'9999-12-31')
FROM tmp GROUP BY RecordId
Per your fiddle this will return the exact results you specify under all conditions.
If we have a single server we can directly include it in the proxy_pass. But in case if we have many servers we use upstream to maintain the servers. Nginx will load-balance based on the incoming traffic.
You can use ffprobe
:
ffprobe -i <file> -show_entries format=duration -v quiet -of csv="p=0"
It will output the duration in seconds, such as:
154.12
Adding the -sexagesimal
option will output duration as hours:minutes:seconds.microseconds:
00:02:34.12
you can remove last comma from a string by using slice() method, find the below example:
var strVal = $.trim($('.txtValue').val());
var lastChar = strVal.slice(-1);
if (lastChar == ',') {
strVal = strVal.slice(0, -1);
}
Here is an Example
function myFunction() {_x000D_
var strVal = $.trim($('.txtValue').text());_x000D_
var lastChar = strVal.slice(-1);_x000D_
if (lastChar == ',') { // check last character is string_x000D_
strVal = strVal.slice(0, -1); // trim last character_x000D_
$("#demo").text(strVal);_x000D_
}_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<p class="txtValue">Striing with Commma,</p>_x000D_
_x000D_
<button onclick="myFunction()">Try it</button>_x000D_
_x000D_
<p id="demo"></p>
_x000D_
I wouldnt use this attribute as most browsers ignore it as CMS points out.
By all means use client side validation but only in conjunction with server side. Any client side validation can be got round.
Slightly off topic but some people check the content type to validate the uploaded file. You need to be careful about this as an attacker can easily change it and upload a php file for example. See the example at: http://www.scanit.be/uploads/php-file-upload.pdf
Here's a different approach. The heart of it was created by turning on the Macro Recorder and filtering the columns per your specifications. Then there's a bit of code to copy the results. It will run faster than looping through each row and column:
Sub FilterAndCopy()
Dim LastRow As Long
Sheets("Sheet2").UsedRange.Offset(0).ClearContents
With Worksheets("Sheet1")
.Range("$A:$E").AutoFilter
.Range("$A:$E").AutoFilter field:=1, Criteria1:="#N/A"
.Range("$A:$E").AutoFilter field:=2, Criteria1:="=String1", Operator:=xlOr, Criteria2:="=string2"
.Range("$A:$E").AutoFilter field:=3, Criteria1:=">0"
.Range("$A:$E").AutoFilter field:=5, Criteria1:="Number"
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
.Range("A1:A" & LastRow).SpecialCells(xlCellTypeVisible).EntireRow.Copy _
Destination:=Sheets("Sheet2").Range("A1")
End With
End Sub
As a side note, your code has more loops and counter variables than necessary. You wouldn't need to loop through the columns, just through the rows. You'd then check the various cells of interest in that row, much like you did.
$apply
should be called?TL;DR:
$apply
should be called whenever you want to apply changes made outside of Angular world.
Just to update @Dustin's answer, here is an explanation of what $apply exactly does and why it works.
$apply()
is used to execute an expression in AngularJS from outside of the AngularJS framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). Because we are calling into the AngularJS framework we need to perform proper scope life cycle of exception handling, executing watches.
Angular allows any value to be used as a binding target. Then at the end of any JavaScript code turn, it checks to see if the value has changed.
That step that checks to see if any binding values have changed actually has a method, $scope.$digest()
1. We almost never call it directly, as we use $scope.$apply()
instead (which will call $scope.$digest
).
Angular only monitors variables used in expressions and anything inside of a $watch
living inside the scope. So if you are changing the model outside of the Angular context, you will need to call $scope.$apply()
for those changes to be propagated, otherwise Angular will not know that they have been changed thus the binding will not be updated2.
Since Python 3.5, subprocess.run() is recommended over subprocess.check_output():
>>> subprocess.run(['cat','/tmp/text.txt'], stdout=subprocess.PIPE).stdout
b'First line\nSecond line\n'
Since Python 3.7, instead of the above, you can use capture_output=true
parameter to capture stdout and stderr:
>>> subprocess.run(['cat','/tmp/text.txt'], capture_output=True).stdout
b'First line\nSecond line\n'
Also, you may want to use universal_newlines=True
or its equivalent since Python 3.7 text=True
to work with text instead of binary:
>>> stdout = subprocess.run(['cat', '/tmp/text.txt'], capture_output=True, text=True).stdout
>>> print(stdout)
First line
Second line
See subprocess.run() documentation for more information.
Microsoft SQL Server 2005 Express Edition Service Pack 4 on Windows Server 2012 R2
Those steps are based on previous howto from https://stackoverflow.com/users/2385/eduardo-molteni
This works with Microsoft SQL Server 2005 Express Edition Service Pack 4 http://www.microsoft.com/en-us/download/details.aspx?id=184
std::queue<myclass*> my_queue;
will do the job.
See here for more information on this container.
Please try this:
#b {
display: -webkit-inline-flex;
display: -moz-inline-flex;
display: inline-flex;
-webkit-flex-flow: row nowrap;
-moz-flex-flow: row nowrap;
flex-flow: row nowrap;
-webkit-align-items: flex-end;
-moz-align-items: flex-end;
align-items: flex-end;}
Here's a JSFiddle demo: http://jsfiddle.net/rudiedirkx/7FGKN/.
Java - encrypt / decrypt user name and password from a configuration file
Code from above link
DESKeySpec keySpec = new DESKeySpec("Your secret Key phrase".getBytes("UTF8"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(keySpec);
sun.misc.BASE64Encoder base64encoder = new BASE64Encoder();
sun.misc.BASE64Decoder base64decoder = new BASE64Decoder();
.........
// ENCODE plainTextPassword String
byte[] cleartext = plainTextPassword.getBytes("UTF8");
Cipher cipher = Cipher.getInstance("DES"); // cipher is not thread safe
cipher.init(Cipher.ENCRYPT_MODE, key);
String encryptedPwd = base64encoder.encode(cipher.doFinal(cleartext));
// now you can store it
......
// DECODE encryptedPwd String
byte[] encrypedPwdBytes = base64decoder.decodeBuffer(encryptedPwd);
Cipher cipher = Cipher.getInstance("DES");// cipher is not thread safe
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] plainTextPwdBytes = (cipher.doFinal(encrypedPwdBytes));
You can do so with Javascript and/or an HTML attribute (which is really a Javascript event handler anyway) as described here: http://www.codeproject.com/KB/aspnet/Disabling_the_right_click.aspx
<script language="javascript">
document.onmousedown=disableclick;
status="Right Click Disabled";
Function disableclick(event)
{
if(event.button==2)
{
alert(status);
return false;
}
}
</script>
and
<body oncontextmenu="return false">
...
</body>
You are right, it is simple. Run (admin password required):
'/Library/Application Support/Jenkins/Uninstall.command'
It may be necessary to do this with admin privileges using sudo.
Merging various references found here in StackOverflow (including the article above) and in other sites, I did so using javascript and JQuery:
<html>
<body>
<canvas id="myCanvas" width="400" height="400" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<script src="jquery.js"></script>
<script type="text/javascript">
window.onload = function(){
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var img = new Image();
img.src = 'photo_apple.jpg';
context.drawImage(img, 0, 0);
};
function findPos(obj){
var current_left = 0, current_top = 0;
if (obj.offsetParent){
do{
current_left += obj.offsetLeft;
current_top += obj.offsetTop;
}while(obj = obj.offsetParent);
return {x: current_left, y: current_top};
}
return undefined;
}
function rgbToHex(r, g, b){
if (r > 255 || g > 255 || b > 255)
throw "Invalid color component";
return ((r << 16) | (g << 8) | b).toString(16);
}
$('#myCanvas').click(function(e){
var position = findPos(this);
var x = e.pageX - position.x;
var y = e.pageY - position.y;
var coordinate = "x=" + x + ", y=" + y;
var canvas = this.getContext('2d');
var p = canvas.getImageData(x, y, 1, 1).data;
var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
alert("HEX: " + hex);
});
</script>
<img src="photo_apple.jpg"/>
</body>
</html>
This is my complete solution. Here I only used canvas and one image, but if you need to use <map>
over the image, it's possible too.
Path Variables dialog has nothing to do with the environment variables.
Environment variables can be specified in your OS or customized in the Run configuration:
Use the standard XPath function contains().
Function: boolean contains(string, string)
The contains function returns true if the first argument string contains the second argument string, and otherwise returns false
You can either
TextView
by a ScrollView
; orScrollingMovementMethod.getInstance();
.I have found this works ONLY in Chrome (where it's red) and not Safari and all other browsers (where it's green)...
.style {
color: green;
(-bracket-:hack;
color: red;
);
}
From http://mynthon.net/howto/webdev/css-hacks-for-google-chrome.htm
Most answers have highlighted the reasons why one should not use doubles for money and currency calculations. And I totally agree with them.
It doesn't mean though that doubles can never be used for that purpose.
I have worked on a number of projects with very low gc requirements, and having BigDecimal objects was a big contributor to that overhead.
It's the lack of understanding about double representation and lack of experience in handling the accuracy and precision that brings about this wise suggestion.
You can make it work if you are able to handle the precision and accuracy requirements of your project, which has to be done based on what range of double values is one dealing with.
You can refer to guava's FuzzyCompare method to get more idea. The parameter tolerance is the key. We dealt with this problem for a securities trading application and we did an exhaustive research on what tolerances to use for different numerical values in different ranges.
Also, there might be situations when you're tempted to use Double wrappers as a map key with hash map being the implementation. It is very risky because Double.equals and hash code for example values "0.5" & "0.6 - 0.1" will cause a big mess.
You just have to post the data. and Using jquery ajax function set parameters. Here is an example.
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'your_complete url',
data: $('form').serialize(),
success: function (response) {
//$('form')[0].reset();
// $("#feedback").text(response);
if(response=="True") {
$('form')[0].reset();
$("#feedback").text("Your information has been stored.");
}
else
$("#feedback").text(" Some Error has occured Errror !!! ID duplicate");
}
});
});
});
</script>
Crawlers (or bots) are designed to crawl HTML content of web pages but due to AJAX operations for asynchronous data fetching, this became a problem as it takes sometime to render page and show dynamic content on it. Similarly, AngularJS
also use asynchronous model, which creates problem for Google crawlers.
Some developers create basic html pages with real data and serve these pages from server side at the time of crawling. We can render same pages with PhantomJS
on serve side which has _escaped_fragment_
(Because Google looks for #!
in our site urls and then takes everything after the #!
and adds it in _escaped_fragment_
query parameter). For more detail please read this blog .
Using the date helper worked for me
$this->load->helper('date');
You can find documentation for date_helper
here.
$data = array(
'created' => now(),
'modified' => now()
);
$this->db->insert('TABLENAME', $data);
According to RFC-7159, the current standard for JSON published by the Internet Engineering Task Force (IETF), states "The names within an object SHOULD be unique". However, according to RFC-2119 which defines the terminology used in IETF documents, the word "should" in fact means "... there may exist valid reasons in particular circumstances to ignore a particular item, but the full implications must be understood and carefully weighed before choosing a different course." What this essentially means is that while having unique keys is recommended, it is not a must. We can have duplicate keys in a JSON object, and it would still be valid.
From practical application, I have seen the value from the last key is considered when duplicate keys are found in a JSON.
at the lowest level, a framework is an environment, where you are given a set of tools to work with
this tools come in the form of libraries, configuration files, etc.
this so-called "environment" provides you with the basic setup (error reportings, log files, language settings, etc)...which can be modified,extended and built upon.
People actually do not need frameworks, it's just a matter of wanting to save time, and others just a matter of personal preferences.
People will justify that with a framework, you don't have to code from scratch. But those are just people confusing libraries with frameworks.
I'm not being biased here, I am actually using a framework right now.
On Solaris 11
Use LD_LIBRARY_PATH_64
to resolve symlink to python libs.
In my case for python3.6 LD_LIBRARY_PATH
didn't work but LD_LIBRARY_PATH_64
did.
Hope this helps.
Regards
If you want to cater to 1-word cell, use this... based upon astander's
=IFERROR(LEFT(A1,SEARCH(" ",A1)-1),A1)
I know this is really old but I think the solutions looked too complicated. Try this in VB:
Public Function HexToInt(sHEX as String) as long
Dim iLen as Integer
Dim i as Integer
Dim SumValue as Long
Dim iVal as long
Dim AscVal as long
iLen = Len(sHEX)
For i = 1 to Len(sHEX)
AscVal = Asc(UCase(Mid$(sHEX, i, 1)))
If AscVal >= 48 And AscVal <= 57 Then
iVal = AscVal - 48
ElseIf AscVal >= 65 And AscVal <= 70 Then
iVal = AscVal - 55
End If
SumValue = SumValue + iVal * 16 ^ (iLen- i)
Next i
HexToInt = SumValue
End Function
@Robino was suggesting to add some tests which make sense, so here is a simple benchmark between 3 possible ways (maybe the most used ones) to convert an iterator to a list:
list(my_iterator)
[*my_iterator]
[e for e in my_iterator]
I have been using simple_bechmark library
from simple_benchmark import BenchmarkBuilder
from heapq import nsmallest
b = BenchmarkBuilder()
@b.add_function()
def convert_by_type_constructor(size):
list(iter(range(size)))
@b.add_function()
def convert_by_list_comprehension(size):
[e for e in iter(range(size))]
@b.add_function()
def convert_by_unpacking(size):
[*iter(range(size))]
@b.add_arguments('Convert an iterator to a list')
def argument_provider():
for exp in range(2, 22):
size = 2**exp
yield size, size
r = b.run()
r.plot()
As you can see there is very hard to make a difference between conversion by the constructor and conversion by unpacking, conversion by list comprehension is the “slowest” approach.
I have been testing also across different Python versions (3.6, 3.7, 3.8, 3.9) by using the following simple script:
import argparse
import timeit
parser = argparse.ArgumentParser(
description='Test convert iterator to list')
parser.add_argument(
'--size', help='The number of elements from iterator')
args = parser.parse_args()
size = int(args.size)
repeat_number = 10000
# do not wait too much if the size is too big
if size > 10000:
repeat_number = 100
def test_convert_by_type_constructor():
list(iter(range(size)))
def test_convert_by_list_comprehension():
[e for e in iter(range(size))]
def test_convert_by_unpacking():
[*iter(range(size))]
def get_avg_time_in_ms(func):
avg_time = timeit.timeit(func, number=repeat_number) * 1000 / repeat_number
return round(avg_time, 6)
funcs = [test_convert_by_type_constructor,
test_convert_by_unpacking, test_convert_by_list_comprehension]
print(*map(get_avg_time_in_ms, funcs))
The script will be executed via a subprocess from a Jupyter Notebook (or a script), the size parameter will be passed through command-line arguments and the script results will be taken from standard output.
from subprocess import PIPE, run
import pandas
simple_data = {'constructor': [], 'unpacking': [], 'comprehension': [],
'size': [], 'python version': []}
size_test = 100, 1000, 10_000, 100_000, 1_000_000
for version in ['3.6', '3.7', '3.8', '3.9']:
print('test for python', version)
for size in size_test:
command = [f'python{version}', 'perf_test_convert_iterator.py', f'--size={size}']
result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True)
constructor, unpacking, comprehension = result.stdout.split()
simple_data['constructor'].append(float(constructor))
simple_data['unpacking'].append(float(unpacking))
simple_data['comprehension'].append(float(comprehension))
simple_data['python version'].append(version)
simple_data['size'].append(size)
df_ = pandas.DataFrame(simple_data)
df_
You can get my full notebook from here.
In most of the cases, in my tests, unpacking shows to be faster, but the difference is so small that the results may change from a run to the other. Again, the comprehension approach is the slowest, in fact, the other 2 methods are up to ~ 60% faster.
Yes, you either need to do this onload
or in a <script>
tag after the closing </body>
tag, when the lc
element is already found in the document's DOM tree.
You can fetch and then check out only one file in this way:
git fetch
git checkout -m <revision> <yourfilepath>
git add <yourfilepath>
git commit
Regarding the git checkout
command:
<revision>
-- a branch name, i.e. origin/master
<yourfilepath>
does not include the repository name (that you can get from clicking copy path
button on a file page on GitHub), i.e. README.md
I've SSL on Apache2.4.4 and executing this code at first, did the trick:
set OPENSSL_CONF=C:\wamp\bin\apache\Apache2.4.4\conf\openssl.cnf
then execute the rest codes..
Just wanted to share my solution using sqlalchemy and pandas in python 3. Perhaps, one would find it useful.
import sqlalchemy as sa
import pandas as pd
engine = sa.create_engine("postgresql://postgres:my_password@my_host:my_port/my_db")
values = [val1,val2,val3]
query = sa.text("""
SELECT *
FROM my_table
WHERE col1 IN :values;
""")
query = query.bindparams(values=tuple(values))
df = pd.read_sql(query, engine)
packages installed using pip can be uninstalled completely using
pip uninstall <package>
pip uninstall
is likely to fail if the package is installed using python setup.py install
as they do not leave behind metadata to determine what files were installed.
packages still show up in pip list
if their paths(.pth file) still exist in your site-packages or dist-packages folder. You'll need to remove them as well in case you're removing using rm -rf
you need to convert to char first because converting to int adds those days to 1900-01-01
select CONVERT (datetime,convert(char(8),rnwl_efctv_dt ))
here are some examples
select CONVERT (datetime,5)
1900-01-06 00:00:00.000
select CONVERT (datetime,20100101)
blows up, because you can't add 20100101 days to 1900-01-01..you go above the limit
convert to char first
declare @i int
select @i = 20100101
select CONVERT (datetime,convert(char(8),@i))
If you're using typing (introduced in Python 3.5) you can use typing.Optional
, where Optional[X]
is equivalent to Union[X, None]
. It is used to signal that the explicit value of None
is allowed . From typing.Optional:
def foo(arg: Optional[int] = None) -> None:
...
As proposed here, this is a pretty cross browser solution that works perfectly:
background: url('/img.png') no-repeat right center;
border-right: 10px solid transparent;
I used it since the CSS3 feature of specifying offsets proposed in the answer marked as solving the question is not supported in browsers so well yet. E.g.
You can use the *_Prefix.pch
file to declare project wide macros.
That file is usually in you Other Sources group.
As Matt said (https://stackoverflow.com/a/43323045/2767413) you should install the build-tools for windows. However, I did it via cmd and got an error, although I am the administrator -
Please restart this script from an administrative PowerShell!
The build tools cannot be installed without administrative rights.
To fix, right-click on PowerShell and run "as Administrator".
I got the same error via a PowerShell.
For windows 7, the administrative PowerShell can be found under:
Control Panel -> System and Security -> Administrative Tools -> Windows PowerShell Modules
Probably u might be using a incorrect SDK version. Right click on your project. Select Properties-->Android. Note that 2.2 is the latest SDK. Check it and see if it gets compiled...
Edit
Also Do a clean after that
You need to add dynamically created components to entryComponents
inside your @NgModule
@NgModule({
declarations: [
AppComponent,
LoginComponent,
DashboardComponent,
HomeComponent,
DialogResultExampleDialog
],
entryComponents: [DialogResultExampleDialog]
Note: In some cases entryComponents
under lazy loaded modules will not work, as a workaround put them in your app.module
(root)
As @stevebot said, do this:
https://<bucket-name>.s3.amazonaws.com/<key>
The one important thing I would like to add is that you either have to make your bucket objects all publicly accessible OR you can add a custom policy to your bucket policy. That custom policy could allow traffic from your network IP range or a different credential.
If you'd like to use a GUI tool to do this there's Sysinternals' TCPView.
As of OSX 10.10 (Yosemite) and since at least OS X 10.8 (Mountain Lion), the behavior is as follows when you open (double-click) executable scripts from Finder:
.command
:Preferences... > Profiles
you can opt to automatically close the window when the script exits.cd -- "$(dirname "$BASH_SOURCE")"
right after the shebang linecd -- "$(dirname "$0")"
.chmod +x <script>
in Terminal; otherwise, you'll see the following symptoms:.command
: Finder displays a misleading error message that suggests the problem can be fixed via File > Get Info
, which is not true - use the chmod +x
method suggested above.#!/bin/bash
): behavior is as if the suffix were .sh
- see below..sh
, whether executable or not:TextEdit.app
or, if installed, with Xcode.app
..scpt
or .applescript
(even if they're themselves marked as executable, which is not normally the case):
[Apple]Script Editor
[1] Executable means: a script with the executable permission bit(s) set and the calling user - relative to the ownership to the file - therefore potentially being allowed to execute it.
If you use chmod a+x
to set all permission bits (which is typical), anyone can invoke it (assuming they're also allowed to read the file based on the read permission bit(s) and the file's ownership).
Please walk me through the commands I should run to figure this out.
The simplest test you can do is to perform 1000 requests, 10 at a time (which approximately simulates 10 concurrent users getting 100 pages each - over the length of the test).
ab -n 1000 -c 10 -k -H "Accept-Encoding: gzip, deflate" http://www.example.com/
-n 1000
is the number of requests to make.
-c 10
tells AB to do 10 requests at a time, instead of 1 request at a time, to better simulate concurrent visitors (vs. sequential visitors).
-k
sends the KeepAlive
header, which asks the web server to not shut down the connection after each request is done, but to instead keep reusing it.
I'm also sending the extra header Accept-Encoding: gzip, deflate
because mod_deflate is almost always used to compress the text/html output 25%-75% - the effects of which should not be dismissed due to it's impact on the overall performance of the web server (i.e., can transfer 2x the data in the same amount of time, etc).
Results:
Benchmarking www.example.com (be patient)
Completed 100 requests
...
Finished 1000 requests
Server Software: Apache/2.4.10
Server Hostname: www.example.com
Server Port: 80
Document Path: /
Document Length: 428 bytes
Concurrency Level: 10
Time taken for tests: 1.420 seconds
Complete requests: 1000
Failed requests: 0
Keep-Alive requests: 995
Total transferred: 723778 bytes
HTML transferred: 428000 bytes
Requests per second: 704.23 [#/sec] (mean)
Time per request: 14.200 [ms] (mean)
Time per request: 1.420 [ms] (mean, across all concurrent requests)
Transfer rate: 497.76 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 0 0.1 0 1
Processing: 5 14 7.5 12 77
Waiting: 5 14 7.5 12 77
Total: 5 14 7.5 12 77
Percentage of the requests served within a certain time (ms)
50% 12
66% 14
75% 15
80% 16
90% 24
95% 29
98% 36
99% 41
100% 77 (longest request)
For the simplest interpretation, ignore everything BUT this line:
Requests per second: 704.23 [#/sec] (mean)
Multiply that by 60, and you have your requests per minute.
To get real world results, you'll want to test Wordpress instead of some static HTML or index.php file because you need to know how everything performs together: including complex PHP code, and multiple MySQL queries...
For example here is the results of testing a fresh install of Wordpress on the same system and WAMP environment (I'm using WampDeveloper, but there are also Xampp, WampServer, and others)...
Requests per second: 18.68 [#/sec] (mean)
That's 37x slower now!
After the load test, there are a number of things you can do to improve the overall performance (Requests Per Second), and also make the web server more stable under greater load (e.g., increasing the -n
and the -c
tends to crash Apache), that you can read about here: