HTML5 and the VLC web plugin were a no go for me but I was able to get this work using the following setup:
DivX Web Player (NPAPI browsers only)
And here is the HTML:
<embed id="divxplayer" type="video/divx" width="1024" height="768"
src ="path_to_file" autoPlay=\"true\"
pluginspage=\"http://go.divx.com/plugin/download/\"></embed>
The DivX player seems to allow for a much wider array of video and audio options than the native HTML5, so far I am very impressed by it.
Here is what I do using Intl api:
let currentTimeZone = new Intl.DateTimeFormat().resolvedOptions().timeZone; // For example: Australia/Sydney
this will return a time zone name. Pass this parameter to the following function to get the time
let dateTime = new Date(date).toLocaleDateString('en-US',{ timeZone: currentTimeZone, hour12: true});
let time = new Date(date).toLocaleTimeString('en-US',{ timeZone: currentTimeZone, hour12: true});
you can also format the time with moment like this:
moment(new Date(`${dateTime} ${time}`)).format('YYYY-MM-DD[T]HH:mm:ss');
I had just this problem and I found a similar answer here.
The method is to set top
the way you want it and then press W
(capital W).
This saves top
's current layout to a configuration file in $HOME/.toprc
Although this might not work if you want to run multiple top
's with different configurations.
So via what I consider a work around you can write to different config files / use different config files by doing one of the following...
1) Rename the binary
ln -s /usr/bin/top top2
./top2
Now .top2rc
is going to be written to your $HOME
2) Set $HOME to some alternative path, since it will write its config file to the $HOME/.binary-name.rc file
HOME=./
top
Now .toprc
is going to be written to the current folder.
Via use of other peoples comments to add the various usage accounting in top you can create a batch output for that information and latter coalesces the information via a script. Maybe not quite as simple as you script but I found top to provide me ALL processes so that later I can recap and capture a state during a long run that I might have missed otherwise (unexplained sudden CPU usage due to stray processes)
If you're planning to only set a few of the values in the array, but want to get the (custom) default value most of the time, you could try something like this:
public class SparseArray<T>
{
private Dictionary<int, T> values = new Dictionary<int, T>();
private T defaultValue;
public SparseArray(T defaultValue)
{
this.defaultValue = defaultValue;
}
public T this [int index]
{
set { values[index] = value; }
get { return values.ContainsKey(index) ? values[index] ? defaultValue; }
}
}
You'll probably need to implement other interfaces to make it useful, such as those on array itself.
Another option of course is to use Javascript (Jquery here):
$('.box1,.box2').each(function(){
$(this).height($(this).parent().height());
})
You can use a DecimalFormat, or String.format("%.2f", a);
More simply in one line:
proxy=192.168.2.1:8080;curl -v example.com
eg. $proxy=192.168.2.1:8080;curl -v example.com
xxxxxxxxx-ASUS:~$ proxy=192.168.2.1:8080;curl -v https://google.com|head -c 15 % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0
This might help someone like me that finds this answer when searching for solutions to how Rails handles the class loading ... I found that I had to define a module
whose name matched my filename appropriately, rather than just defining a class:
In file lib/development_mail_interceptor.rb (Yes, I'm using code from a Railscast :))
module DevelopmentMailInterceptor
class DevelopmentMailInterceptor
def self.delivering_email(message)
message.subject = "intercepted for: #{message.to} #{message.subject}"
message.to = "[email protected]"
end
end
end
works, but it doesn't load if I hadn't put the class inside a module.
If this is your app, if you connect the device to your computer, you can use the "Devices" option on Xcode's "Window" menu and then download the app's data container to your computer. Just select your app from the list of installed apps, and click on the "gear" icon and choose "Download Container".
Once you've downloaded it, right click on the file in the Finder and choose "Show Package Contents".
Simple solution that worked for me is, set the path of python in environment variables,it is done as follows
In the edit option click add and add following two paths to it one by one:
C:\Python27
C:\Python27\Scripts
and now close cmd and run it as administrator, by that pip will start working.
It's better to do this.
Navigate to the folder structure you require
Use the command
jar -xvf 'Path_to_ur_Jar_file'
I can see many answers showing how to solve problem, but only Stephen's answer is trying to explain why problem occurs so I will try to add something more on this subject. It is a story about possible reasons why Object[] toArray
wasn't changed to T[] toArray
where generics ware introduced to Java.
String[] stockArr = (String[]) stock_list.toArray();
wont work?In Java, generic type exists at compile-time only. At runtime information about generic type (like in your case <String>
) is removed and replaced with Object
type (take a look at type erasure). That is why at runtime toArray()
have no idea about what precise type to use to create new array, so it uses Object
as safest type, because each class extends Object so it can safely store instance of any class.
Object[]
to String[]
.Why? Take a look at this example (lets assume that class B extends A
):
//B extends A
A a = new A();
B b = (B)a;
Although such code will compile, at runtime we will see thrown ClassCastException
because instance held by reference a
is not actually of type B
(or its subtypes). Why is this problem (why this exception needs to be cast)? One of the reasons is that B
could have new methods/fields which A
doesn't, so it is possible that someone will try to use these new members via b
reference even if held instance doesn't have (doesn't support) them. In other words we could end up trying to use data which doesn't exist, which could lead to many problems. So to prevent such situation JVM throws exception, and stop further potentially dangerous code.
You could ask now "So why aren't we stopped even earlier? Why code involving such casting is even compilable? Shouldn't compiler stop it?". Answer is: no because compiler can't know for sure what is the actual type of instance held by a
reference, and there is a chance that it will hold instance of class B
which will support interface of b
reference. Take a look at this example:
A a = new B();
// ^------ Here reference "a" holds instance of type B
B b = (B)a; // so now casting is safe, now JVM is sure that `b` reference can
// safely access all members of B class
Now lets go back to your arrays. As you see in question, we can't cast instance of Object[]
array to more precise type String[]
like
Object[] arr = new Object[] { "ab", "cd" };
String[] arr2 = (String[]) arr;//ClassCastException will be thrown
Here problem is a little different. Now we are sure that String[]
array will not have additional fields or methods because every array support only:
[]
operator,length
filed,So it is not arrays interface which is making it impossible. Problem is that Object[]
array beside Strings
can store any objects (for instance Integers
) so it is possible that one beautiful day we will end up with trying to invoke method like strArray[i].substring(1,3)
on instance of Integer
which doesn't have such method.
So to make sure that this situation will never happen, in Java array references can hold only
String[] strArr
can hold String[]
)Object[]
can hold String[]
because String
is subtype of Object
),but can't hold
String[]
can't hold Object[]
)Integer[]
can't hold String[]
)In other words something like this is OK
Object[] arr = new String[] { "ab", "cd" }; //OK - because
// ^^^^^^^^ `arr` holds array of subtype of Object (String)
String[] arr2 = (String[]) arr; //OK - `arr2` reference will hold same array of same type as
// reference
You could say that one way to resolve this problem is to find at runtime most common type between all list elements and create array of that type, but this wont work in situations where all elements of list will be of one type derived from generic one. Take a look
//B extends A
List<A> elements = new ArrayList<A>();
elements.add(new B());
elements.add(new B());
now most common type is B
, not A
so toArray()
A[] arr = elements.toArray();
would return array of B
class new B[]
. Problem with this array is that while compiler would allow you to edit its content by adding new A()
element to it, you would get ArrayStoreException
because B[]
array can hold only elements of class B
or its subclass, to make sure that all elements will support interface of B
, but instance of A
may not have all methods/fields of B
. So this solution is not perfect.
Best solution to this problem is explicitly tell what type of array toArray()
should be returned by passing this type as method argument like
String[] arr = list.toArray(new String[list.size()]);
or
String[] arr = list.toArray(new String[0]); //if size of array is smaller then list it will be automatically adjusted.
I'm having a problem with your script in Firefox. When I scroll down, the script continues to add a margin to the page and I never reach the bottom of the page. This occurs because the ActionBox is still part of the page elements. I posted a demo here.
position: fixed
to the CSS definition, but I see this won't work for youtop
.UPDATED:
CSS
#ActionBox {
position: relative;
float: right;
}
Script
var alert_top = 0;
var alert_margin_top = 0;
$(function() {
alert_top = $("#ActionBox").offset().top;
alert_margin_top = parseInt($("#ActionBox").css("margin-top"),10);
$(window).scroll(function () {
var scroll_top = $(window).scrollTop();
if (scroll_top > alert_top) {
$("#ActionBox").css("margin-top", ((scroll_top-alert_top)+(alert_margin_top*2)) + "px");
console.log("Setting margin-top to " + $("#ActionBox").css("margin-top"));
} else {
$("#ActionBox").css("margin-top", alert_margin_top+"px");
};
});
});
Also it is important to add a base (10 in this case) to your parseInt()
, e.g.
parseInt($("#ActionBox").css("top"),10);
In the current version of Sublime Text 2 (Build: 2139), you can set the syntax for all files of a certain file extension using an option in the menu bar. Open a file with the extension you want to set a default for and navigate through the following menus: View -> Syntax -> Open all with current extension as... ->[your syntax choice]
.
Updated 2012-06-28: Recent builds of Sublime Text 2 (at least since Build 2181) have allowed the syntax to be set by clicking the current syntax type in the lower right corner of the window. This will open the syntax selection menu with the option to Open all with current extension as...
at the top of the menu.
Updated 2016-04-19: As of now, this also works for Sublime Text 3.
To print the columns with a specific string, you use the // search pattern. For example, if you are looking for second columns that contains abc:
awk '$2 ~ /abc/'
... and if you want to print only a particular column:
awk '$2 ~ /abc/ { print $3 }'
... and for a particular line number:
awk '$2 ~ /abc/ && FNR == 5 { print $3 }'
For Angular 6+ things have changed a little.
Cli setup is now done in angular.json (replaced .angular-cli.json) in your workspace root directory. The output path in default angular.json should look like this (irrelevant lines removed):
{
"projects": {
"my-app-name": {
"architect": {
"options": {
"outputPath": "dist/my-app-name",
Obviously, this will generate your app in WORKSPACE/dist/my-app-name. Modify outputPath if you prefer another directory.
You can overwrite the output path using command line arguments (e.g. for CI jobs):
ng build -op dist/example
ng build --output-path=dist/example
S.a. https://github.com/angular/angular-cli/wiki/build
Setting the output path, will tell angular where to place the "compiled" files but however you change the output path, when running the app, angular will still assume that the app is hosted in the webserver's document root.
To make it work in a sub directory, you'll have to set the base href.
In angular.json:
{
"projects": {
"my-app-name": {
"architect": {
"options": {
"baseHref": "/my-folder/",
Cli:
ng build --base-href=/my-folder/
If you don't know where the app will be hosted on build time, you can change base tag in generated index.html.
Here's an example how we do it in our docker container:
entrypoint.sh
if [ -n "${BASE_PATH}" ]
then
files=( $(find . -name "index.html") )
cp -n "${files[0]}" "${files[0]}.org"
cp "${files[0]}.org" "${files[0]}"
sed -i "s*<base href=\"/\">*<base href=\"${BASE_PATH}\">*g" "${files[0]}"
fi
Oddly it looks like the other two answers don't spell it out, and it's definitely worth saying:
i++
means 'tell me the value of i
, then increment'
++i
means 'increment i
, then tell me the value'
They are Pre-increment, post-increment operators. In both cases the variable is incremented, but if you were to take the value of both expressions in exactly the same cases, the result will differ.
Encountered this error while using maven-shade-plugin, the solution was including:
META-INF/spring.schemas
and
META-INF/spring.handlers
transformers in the maven-shade-plugin when building...
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>META-INF/spring.handlers</resource>
</transformer>
<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>META-INF/spring.schemas</resource>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
I found the following to be a working solution::
npm install aws-sdk
Once you've installed the aws-sdk , use the following code replacing values with your where needed.
var AWS = require('aws-sdk');
var fs = require('fs');
var s3 = new AWS.S3();
// Bucket names must be unique across all S3 users
var myBucket = 'njera';
var myKey = 'jpeg';
//for text file
//fs.readFile('demo.txt', function (err, data) {
//for Video file
//fs.readFile('demo.avi', function (err, data) {
//for image file
fs.readFile('demo.jpg', function (err, data) {
if (err) { throw err; }
params = {Bucket: myBucket, Key: myKey, Body: data };
s3.putObject(params, function(err, data) {
if (err) {
console.log(err)
} else {
console.log("Successfully uploaded data to myBucket/myKey");
}
});
});
I found the complete tutorial on the subject here in case you're looking for references ::
I see this nice tutorial on how to get the like count from facebook using PHP.
public static function get_the_fb_like( $url = '' ){
$pageURL = 'http://nextopics.com';
$url = ($url == '' ) ? $pageURL : $url; // setting a value in $url variable
$params = 'select comment_count, share_count, like_count from link_stat where url = "'.$url.'"';
$component = urlencode( $params );
$url = 'http://graph.facebook.com/fql?q='.$component;
$fbLIkeAndSahre = json_decode( $this->file_get_content_curl( $url ) );
$getFbStatus = $fbLIkeAndSahre->data['0'];
return $getFbStatus->like_count;
}
here is a sample code.. I don't know how to paste the code with correct format in here, so just kindly visit this link for better view of the code.
I had a different experience loading SQL Server 2005 Express on Windows 8. I was using the installer that already had SP4 applied so maybe that explains the difference. The first error I received was when Setup tried to start the SQL VSS Writer. I just told it to Ignore and it continued. I then ran into the same error Sohail had where the SQL Server service failed to start. There was no point in following the rest of Sohail's method since I already was using a SP4 version of SQLServr.exe and SQLOS.dll. Instead, I just canceled the install rebooted the machine and ran the install again. Everything ran fine the second time around.
The place I found Sohail's technique invaluable was when I needed to install SQL Server 2005 Standard on Windows Server 2012. We have a few new servers we're looking to roll out with Windows 2012 but we didn't feel the need to upgrade SQL Server since the 2005 version has all the functionality we need and the cost to license SQL 2012 on these boxes would have been a 5-figure sum.
I wound up tweaking Sohail's technique a bit by adding steps to revert the SQLServr.exe and SQLOS.dll files so that I could then apply SP4 fully. Below are all the steps I took starting from a scratch install of Windows Server 2012 Standard. I hope this helps anyone else looking to get a fully updated install of SQL Server 2005 x64 on this OS.
add this to your form:
<form id="regform" action="insert.php" method="post">
add this to your function:
<script>
function myFunction() {
var pass1 = document.getElementById("pass1").value;
var pass2 = document.getElementById("pass2").value;
if (pass1 != pass2) {
//alert("Passwords Do not match");
document.getElementById("pass1").style.borderColor = "#E34234";
document.getElementById("pass2").style.borderColor = "#E34234";
}
else {
alert("Passwords Match!!!");
document.getElementById("regForm").submit();
}
}
</script>
To Select all
$('select[name=eventsFilter]').find('option').attr('selected', true);
$('select[name=eventsFilter]').select2();
To UnSellect all
$('select[name=eventsFilter]').find('option').attr('selected', false);
$('select[name=eventsFilter]').select2("");
According to the Facebook documentation it's not possible to get all the fans of a page:
Although you can't get a list of all the fans of a Facebook Page, you can find out whether a specific person has liked a Page.
You can create a utility class (which cannot have instances created) by declaring an enum type with no instances. i.e. you are specificly declaring that there are no instances.
public enum MyUtilities {;
public static void myMethod();
}
This: "\0"
is a string, not a character. A character uses single quotes, like '\0'
.
Webkit based browsers (like Google Chrome or Safari) has built-in developer tools. In Chrome you can open it Menu->Tools->Developer Tools
. The Network
tab allows you to see all information about every request and response:
In the bottom of the picture you can see that I've filtered request down to XHR
- these are requests made by javascript code.
Tip: log is cleared every time you load a page, at the bottom of the picture, the black dot button will preserve log.
After analyzing requests and responses you can simulate these requests from your web-crawler and extract valuable data. In many cases it will be easier to get your data than parsing HTML, because that data does not contain presentation logic and is formatted to be accessed by javascript code.
Firefox has similar extension, it is called firebug. Some will argue that firebug is even more powerful but I like the simplicity of webkit.
Why not simply set it up as a Scheduled Task that is scheduled to run at start up?
date('Y-m-d H:i:s')
. See the manual for more.
Following are eight ways to find the Uptime in Windows OS.
In Windows Vista and Windows Server 2008, the Task Manager has been beefed up to show additional information about the system. One of these pieces of info is the server’s running time.
The current system uptime is shown under System or Performance ⇒ CPU for Win 8/10.
The systeminfo
command line utility checks and displays various system statistics such as installation date, installed hotfixes and more.
Open a Command Prompt and type the following command:
systeminfo
You can also narrow down the results to just the line you need:
systeminfo | find "System Boot Time:"
Microsoft have published a tool called Uptime.exe. It is a simple command line tool that analyses the computer's reliability and availability information. It can work locally or remotely. In its simple form, the tool will display the current system uptime. An advanced option allows you to access more detailed information such as shutdown, reboots, operating system crashes, and Service Pack installation.
Read the following KB for more info and for the download links:
To use it, follow these steps:
uptime.exe
utility. You can add a /? to the command in order
to get more options.
It does not offer many command line parameters:
C:\uptimefromcodeplex\> uptime /?
usage: Uptime [-V]
-V display version
C:\uptimefromcodeplex\> uptime -V
version 1.1.0
There is an older version of the "uptime.exe" utility. This has the advantage of NOT needing .NET. (It also has a lot more features beyond simple uptime.)
Download link: Windows NT 4.0 Server Uptime Tool (uptime.exe) (final x86)
C:\uptimev100download>uptime.exe /?
UPTIME, Version 1.00
(C) Copyright 1999, Microsoft Corporation
Uptime [server] [/s ] [/a] [/d:mm/dd/yyyy | /p:n] [/heartbeat] [/? | /help]
server Name or IP address of remote server to process.
/s Display key system events and statistics.
/a Display application failure events (assumes /s).
/d: Only calculate for events after mm/dd/yyyy.
/p: Only calculate for events in the previous n days.
/heartbeat Turn on/off the system's heartbeat
/? Basic usage.
/help Additional usage information.
Another easy method, if you can remember it, is to use the approximate information found in the statistics displayed by the NET STATISTICS command. Open a Command Prompt and type the following command:
net statistics workstation
The statistics should tell you how long it’s been running, although in some cases this information is not as accurate as other methods.
Probably the most accurate of them all, but it does require some clicking. It does not display an exact day or hour count since the last reboot, but it will display important information regarding why the computer was rebooted and when it did so. We need to look at Event ID 6005, which is an event that tells us that the computer has just finished booting, but you should be aware of the fact that there are virtually hundreds if not thousands of other event types that you could potentially learn from.
Note: BTW, the 6006 Event ID is what tells us when the server has gone down, so if there’s much time difference between the 6006 and 6005 events, the server was down for a long time.
Note: You can also open the Event Viewer by typing eventvwr.msc in the Run command, and you might as well use the shortcut found in the Administrative tools folder.
Get-WinEvent -ProviderName eventlog | Where-Object {$_.Id -eq 6005 -or $_.Id -eq 6006}
GetTickCount64 retrieves the number of milliseconds that have elapsed since the system was started.
wmic os get lastbootuptime
Like the tool from Microsoft, but compatible with all operating systems up to and including Windows 10 and Windows Server 2016, this uptime utility does not require an elevated command prompt and offers an option to show the uptime in both DD:HH:MM:SS and in human-readable formats (when executed with the -h
command-line parameter).
Additionally, this version of uptime.exe
will run and show the system uptime even when launched normally from within an explorer.exe session (i.e. not via the command line) and pause for the uptime to be read:
and when executed as uptime -h
:
public class AesCryptoService
{
private static byte[] Key = Encoding.ASCII.GetBytes(@"qwr{@^h`h&_`50/ja9!'dcmh3!uw<&=?");
private static byte[] IV = Encoding.ASCII.GetBytes(@"9/\~V).A,lY&=t2b");
public static string EncryptStringToBytes_Aes(string plainText)
{
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
byte[] encrypted;
using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
aesAlg.Mode = CipherMode.CBC;
aesAlg.Padding = PaddingMode.PKCS7;
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
return Convert.ToBase64String(encrypted);
}
public static string DecryptStringFromBytes_Aes(string Text)
{
if (Text == null || Text.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
string plaintext = null;
byte[] cipherText = Convert.FromBase64String(Text.Replace(' ', '+'));
using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
aesAlg.Mode = CipherMode.CBC;
aesAlg.Padding = PaddingMode.PKCS7;
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
}
String based operators will be deprecated in the future (You've probably seen the warning in console).
Getting this to work with symbolic operators was quite confusing for me, and I've updated the docs with two examples.
Post.findAll({
where: {
[Op.or]: [{authorId: 12}, {authorId: 13}]
}
});
// SELECT * FROM post WHERE authorId = 12 OR authorId = 13;
Post.findAll({
where: {
authorId: {
[Op.or]: [12, 13]
}
}
});
// SELECT * FROM post WHERE authorId = 12 OR authorId = 13;
Ok so this is the combination that worked for me when I had this problem on one of my websites:
html {
height: 100%;
}
body {
overflow-x: hidden;
}
I am using following:
using System.Web.Script.Serialization;
...
public static T ParseResponse<T>(string data)
{
return new JavaScriptSerializer().Deserialize<T>(data);
}
@Navaneeth and @Antfish, no need to transform you can do like this also because in above solution only top border is visible so for inside curve you can use bottom border.
.box {_x000D_
width: 500px;_x000D_
height: 100px;_x000D_
border: solid 5px #000;_x000D_
border-color: transparent transparent #000 transparent;_x000D_
border-radius: 0 0 240px 50%/60px;_x000D_
}
_x000D_
<div class="box"></div>
_x000D_
To find all files modified in the last 24 hours use the one below. The -1 here means changed 1 day or less ago.
find . -mtime -1 -ls
The single " | " operator will evaluate both sides of the expression.
if (ActionsLogWriter.Close | ErrorDumpWriter.Close == true)
{
// Do stuff here
}
The double operator " || " will only evaluate the left side if the expression returns true.
if (ActionsLogWriter.Close || ErrorDumpWriter.Close == true)
{
// Do stuff here
}
C# has many similarities to C++ but their still are differences between the two languages ;)
MySQL provides a very cute solution :
REPLACE INTO `table` VALUES (5, 'John', 'Doe', SHA1('password'));
Very easy to use since you have declared a unique primary key (here with value 5).
Jenkins has a link to their REST API in the bottom right of each page. This link appears on every page of Jenkins and points you to an API output for the exact page you are browsing. That should provide some understanding into how to build the API URls.
You can additionally use some wrapper, like I do, in Python, using http://jenkinsapi.readthedocs.io/en/latest/
Here is their website: https://wiki.jenkins-ci.org/display/JENKINS/Remote+access+API
Let us say we have a project social_login. To check the traffic to your repo, you can goto https://github.com//social_login/graphs/traffic
OK, there are two ways of doing that:
// GLOBAL_CONCURRENT_QUEUE
- (void)doCalculationsAndUpdateUIsWith_GlobalQUEUE
{
dispatch_queue_t globalConcurrentQ = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(globalConcurrentQ, ^{
// DATA PROCESSING 1
sleep(1);
NSLog(@"Hello world chekpoint 1");
dispatch_sync(dispatch_get_main_queue(), ^{
// UI UPDATION 1
sleep(1);
NSLog(@"Hello world chekpoint 2");
});
/* the control to come here after UI UPDATION 1 */
sleep(1);
NSLog(@"Hello world chekpoint 3");
// DATA PROCESSING 2
dispatch_sync(dispatch_get_main_queue(), ^{
// UI UPDATION 2
sleep(1);
NSLog(@"Hello world chekpoint 4");
});
/* the control to come here after UI UPDATION 2 */
sleep(1);
NSLog(@"Hello world chekpoint 5");
// DATA PROCESSING 3
dispatch_sync(dispatch_get_main_queue(), ^{
// UI UPDATION 3
sleep(1);
NSLog(@"Hello world chekpoint 6");
});
});
}
// SERIAL QUEUE
- (void)doCalculationsAndUpdateUIsWith_GlobalQUEUE
{
dispatch_queue_t serialQ = dispatch_queue_create("com.example.MyQueue", NULL);
dispatch_async(serialQ, ^{
// DATA PROCESSING 1
sleep(1);
NSLog(@"Hello world chekpoint 1");
dispatch_sync(dispatch_get_main_queue(), ^{
// UI UPDATION 1
sleep(1);
NSLog(@"Hello world chekpoint 2");
});
sleep(1);
NSLog(@"Hello world chekpoint 3");
// DATA PROCESSING 2
dispatch_sync(dispatch_get_main_queue(), ^{
// UI UPDATION 2
sleep(1);
NSLog(@"Hello world chekpoint 4");
});
});
}
Updating to use tibble()
You can pass a named vector of length greater than 1 to the by
argument of left_join()
:
library(dplyr)
d1 <- tibble(
x = letters[1:3],
y = LETTERS[1:3],
a = rnorm(3)
)
d2 <- tibble(
x2 = letters[3:1],
y2 = LETTERS[3:1],
b = rnorm(3)
)
left_join(d1, d2, by = c("x" = "x2", "y" = "y2"))
It seems you have found your solution, but still it will be helpful to others, on this page on point based on Chrome 59.
4.Note the red triangle in the top-right of the Animation Frame Fired event. Whenever you see a red triangle, it's a warning that there may be an issue related to this event.
If you hover on these triangle you can see those are the violation handler errors and as per point 4. yes there is some issue related to that event.
Linux: Remove redundant paths from $PATH variable
Linux From Scratch has this function in /etc/profile
# Functions to help us manage paths. Second argument is the name of the
# path variable to be modified (default: PATH)
pathremove () {
local IFS=':'
local NEWPATH
local DIR
local PATHVARIABLE=${2:-PATH}
for DIR in ${!PATHVARIABLE} ; do
if [ "$DIR" != "$1" ] ; then
NEWPATH=${NEWPATH:+$NEWPATH:}$DIR
fi
done
export $PATHVARIABLE="$NEWPATH"
}
This is intended to be used with these functions for adding to the path, so that you don't do it redundantly:
pathprepend () {
pathremove $1 $2
local PATHVARIABLE=${2:-PATH}
export $PATHVARIABLE="$1${!PATHVARIABLE:+:${!PATHVARIABLE}}"
}
pathappend () {
pathremove $1 $2
local PATHVARIABLE=${2:-PATH}
export $PATHVARIABLE="${!PATHVARIABLE:+${!PATHVARIABLE}:}$1"
}
Simple usage is to just give pathremove
the directory path to remove - but keep in mind that it has to match exactly:
$ pathremove /home/username/anaconda3/bin
This will remove each instance of that directory from your path.
If you want the directory in your path, but without the redundancies, you could just use one of the other functions, e.g. - for your specific case:
$ pathprepend /usr/local/sbin
$ pathappend /usr/local/bin
$ pathappend /usr/sbin
$ pathappend /usr/bin
$ pathappend /sbin
$ pathappend /bin
$ pathappend /usr/games
But, unless readability is the concern, at this point you're better off just doing:
$ export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
I would presume the above to work in sh
, dash
, and bash
at least. I would be surprised to learn it doesn't work in csh
, fish', or
ksh`. I doubt it would work in Windows command shell or Powershell.
If you have Python, the following sort of command should do what is directly asked (that is, remove redundant paths):
$ PATH=$( python -c "
import os
path = os.environ['PATH'].split(':')
print(':'.join(sorted(set(path), key=path.index)))
" )
A one-liner (to sidestep multiline issues):
$ PATH=$( python -c "import os; path = os.environ['PATH'].split(':'); print(':'.join(sorted(set(path), key=path.index)))" )
The above removes later redundant paths. To remove earlier redundant paths, use a reversed list's index and reverse it again:
$ PATH=$( python -c "
import os
path = os.environ['PATH'].split(':')[::-1]
print(':'.join(sorted(set(path), key=path.index, reverse=True)))
" )
You want:
foreach (int number in numbers) // <--- go back to here --------+
{ // |
if (number < 0) // |
{ // |
continue; // Skip the remainder of this iteration. -----+
}
// do work
}
Here's more about the continue
keyword.
Update: In response to Brian's follow-up question in the comments:
Could you further clarify what I would do if I had nested for loops, and wanted to skip the iteration of one of the extended ones?
for (int[] numbers in numberarrays) { for (int number in numbers) { // What to do if I want to // jump the (numbers/numberarrays)? } }
A continue
always applies to the nearest enclosing scope, so you couldn't use it to break out of the outermost loop. If a condition like that arises, you'd need to do something more complicated depending on exactly what you want, like break
from the inner loop, then continue
on the outer loop. See here for the documentation on the break
keyword. The break
C# keyword is similar to the Perl last
keyword.
Also, consider taking Dustin's suggestion to just filter out values you don't want to process beforehand:
foreach (var basket in baskets.Where(b => b.IsOpen())) {
foreach (var fruit in basket.Where(f => f.IsTasty())) {
cuteAnimal.Eat(fruit); // Om nom nom. You don't need to break/continue
// since all the fruits that reach this point are
// in available baskets and tasty.
}
}
Procedure :
1.Take an array.
2.Then by default function reverse(array_name, array_name + size) .
reverse(array_name, array_name + size) function exits in algorithm.h header file.
3.Now print the array.
N.B Here we use new and delete for dynamic memory allocation.
C++ implementation :
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
int *arr = new int[n];
for(int i=0; i<n; i++) cin>>arr[i];
reverse(arr, arr+n);
for(int i=0; i<n; i++) cout<<arr[i]<<" ";
delete[] arr;
return 0;
}
its kind of hacky but it works well-ish
function close_frame(){
if(!window.should_close){
window.should_close=1;
}else if(window.should_close==1){
location.reload();
//or iframe hide or whatever
}
}
<iframe src="iframe_index.php" onload="close_frame()"></iframe>
then inside the frame
$('#close_modal_main').click(function(){
window.location = 'iframe_index.php?close=1';
});
and if you want to get fancy through a
if(isset($_GET['close'])){
die;
}
at the top of your frame page to make that reload unnoticeable
so basically the first time the frame loads it doesnt hide itself but the next time it loads itll call the onload function and the parent will have a the window var causing the frame to close
Do we really need a Boost library for seemingly such a simple task?
To replace all occurences of a substring use this function:
std::string ReplaceString(std::string subject, const std::string& search,
const std::string& replace) {
size_t pos = 0;
while ((pos = subject.find(search, pos)) != std::string::npos) {
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
return subject;
}
If you need performance, here is an optimized function that modifies the input string, it does not create a copy of the string:
void ReplaceStringInPlace(std::string& subject, const std::string& search,
const std::string& replace) {
size_t pos = 0;
while ((pos = subject.find(search, pos)) != std::string::npos) {
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
}
Tests:
std::string input = "abc abc def";
std::cout << "Input string: " << input << std::endl;
std::cout << "ReplaceString() return value: "
<< ReplaceString(input, "bc", "!!") << std::endl;
std::cout << "ReplaceString() input string not modified: "
<< input << std::endl;
ReplaceStringInPlace(input, "bc", "??");
std::cout << "ReplaceStringInPlace() input string modified: "
<< input << std::endl;
Output:
Input string: abc abc def
ReplaceString() return value: a!! a!! def
ReplaceString() input string not modified: abc abc def
ReplaceStringInPlace() input string modified: a?? a?? def
For the basic tooltip, you want:
<span title="This is my tooltip"> Hover on me to see tooltip! </span>
_x000D_
I have found a npm package made with CoffeeScript that has a lot of incredible useful helpers for Handlebars. Take a look of the documentation in the following URL:
https://npmjs.org/package/handlebars-helpers
You can do a wget http://registry.npmjs.org/handlebars-helpers/-/handlebars-helpers-0.2.6.tgz
to download them and see the contents of the package.
You will be abled to do things like {{#is number 5}}
or {{formatDate date "%m/%d/%Y"}}
Use the Path
class from System.IO
. It contains useful calls for manipulating file paths, including GetDirectoryName
which does what you want, returning the directory portion of the file path.
Usage is simple.
string directoryPath = Path.GetDirectoryName(filePath);
SELECT <...>
FROM A.tableA JOIN B.tableB
If you are not familiar with the code and you want to find ViewController coresponding to given view, then you can try:
po (UIView *)0x7fe523bd3000 po [(UIView *)0x7fe523bd3000 nextResponder] po [[(UIView *)0x7fe523bd3000 nextResponder] nextResponder] po [[[(UIView *)0x7fe523bd3000 nextResponder] nextResponder] nextResponder] ...
In most cases you will get UIView, but from time to time there will be UIViewController based class.
The Servlet Specification JSR-315 clearly defines the web container behavior in the service (and doGet, doPost, doPut etc.) methods (2.3.3.1 Multithreading Issues, Page 9):
A servlet container may send concurrent requests through the service method of the servlet. To handle the requests, the Servlet Developer must make adequate provisions for concurrent processing with multiple threads in the service method.
Although it is not recommended, an alternative for the Developer is to implement the SingleThreadModel interface which requires the container to guarantee that there is only one request thread at a time in the service method. A servlet container may satisfy this requirement by serializing requests on a servlet, or by maintaining a pool of servlet instances. If the servlet is part of a Web application that has been marked as distributable, the container may maintain a pool of servlet instances in each JVM that the application is distributed across.
For servlets not implementing the SingleThreadModel interface, if the service method (or methods such as doGet or doPost which are dispatched to the service method of the HttpServlet abstract class) has been defined with the synchronized keyword, the servlet container cannot use the instance pool approach, but must serialize requests through it. It is strongly recommended that Developers not synchronize the service method (or methods dispatched to it) in these circumstances because of detrimental effects on performance
You could use something like this:
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?saddr=20.344,34.34&daddr=20.5666,45.345"));
startActivity(intent);
To start the navigation from the current location, remove the saddr
parameter and value.
You can use an actual street address instead of latitude and longitude. However this will give the user a dialog to choose between opening it via browser or Google Maps.
This will fire up Google Maps in navigation mode directly:
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("google.navigation:q=an+address+city"));
UPDATE
In May 2017 Google launched the new API for universal, cross-platform Google Maps URLs:
https://developers.google.com/maps/documentation/urls/guide
You can use Intents with the new API as well.
CsvHelper library is very popular in the Nuget.You worth it,man! https://github.com/JoshClose/CsvHelper/wiki/Basics
Using CsvHelper is really easy. It's default settings are setup for the most common scenarios.
Here is a little setup data.
Actors.csv:
Id,FirstName,LastName
1,Arnold,Schwarzenegger
2,Matt,Damon
3,Christian,Bale
Actor.cs (custom class object that represents an actor):
public class Actor
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
Reading the CSV file using CsvReader:
var csv = new CsvReader( new StreamReader( "Actors.csv" ) );
var actorsList = csv.GetRecords();
Writing to a CSV file.
using (var csv = new CsvWriter( new StreamWriter( "Actors.csv" ) ))
{
csv.WriteRecords( actorsList );
}
Note the guidelines for performing work on a UI thread, collected on my blog:
There are two techniques you should use:
1) Use ConfigureAwait(false)
when you can.
E.g., await MyAsync().ConfigureAwait(false);
instead of await MyAsync();
.
ConfigureAwait(false)
tells the await
that you do not need to resume on the current context (in this case, "on the current context" means "on the UI thread"). However, for the rest of that async
method (after the ConfigureAwait
), you cannot do anything that assumes you're in the current context (e.g., update UI elements).
For more information, see my MSDN article Best Practices in Asynchronous Programming.
2) Use Task.Run
to call CPU-bound methods.
You should use Task.Run
, but not within any code you want to be reusable (i.e., library code). So you use Task.Run
to call the method, not as part of the implementation of the method.
So purely CPU-bound work would look like this:
// Documentation: This method is CPU-bound.
void DoWork();
Which you would call using Task.Run
:
await Task.Run(() => DoWork());
Methods that are a mixture of CPU-bound and I/O-bound should have an Async
signature with documentation pointing out their CPU-bound nature:
// Documentation: This method is CPU-bound.
Task DoWorkAsync();
Which you would also call using Task.Run
(since it is partially CPU-bound):
await Task.Run(() => DoWorkAsync());
You could use Qt which, in case you don't know, is C++ with a bunch of additional libraries and classes and whatnot. Qt has a very convenient QByteArray class which I'm quite sure would suit your needs.
Well, I'm not sure that merge would be the way to go. Personally I would build a new data frame by creating an index of the dates and then constructing the columns using list comprehensions. Possibly not the most pythonic way, but it seems to work for me!
import pandas as pd
import numpy as np
df1 = pd.DataFrame(np.random.randn(5,3), index=pd.date_range('01/02/2014',periods=5,freq='D'), columns=['a','b','c'] )
df2 = pd.DataFrame(np.random.randn(8,3), index=pd.date_range('01/01/2014',periods=8,freq='D'), columns=['a','b','c'] )
# Create an index list from the set of dates in both data frames
Index = list(set(list(df1.index) + list(df2.index)))
Index.sort()
df3 = pd.DataFrame({'df1': [df1.loc[Date, 'c'] if Date in df1.index else np.nan for Date in Index],\
'df2': [df2.loc[Date, 'c'] if Date in df2.index else np.nan for Date in Index],},\
index = Index)
df3
Nate-Wilkins's improved function:
jQuery.fn.extend({
toggleText: function (a, b) {
var toggle = false, that = this;
this.on('click', function () {
that.text((toggle = !toggle) ? b : a);
});
return this;
}
});
html:
<button class="button-toggle-text">Hello World</button>
using:
$('.button-toggle-text').toggleText("Hello World", "Bye!");
Instead of putting it on top of the file (or even a header file), just wrap the code in question with #pragma warning (push)
, #pragma warning (disable)
and a matching #pragma warning (pop)
, as shown here.
Although there are some other options, including #pramga warning (once)
.
Arrays.toString: (from the API, at least for the Object[]
version of it)
public static String toString(Object[] a) {
if (a == null)
return "null";
int iMax = a.length - 1;
if (iMax == -1)
return "[]";
StringBuilder b = new StringBuilder();
b.append('[');
for (int i = 0; ; i++) {
b.append(String.valueOf(a[i]));
if (i == iMax)
return b.append(']').toString();
b.append(", ");
}
}
So that means it inserts the [
at the start, the ]
at the end, and the ,
between elements.
If you want it without those characters: (StringBuilder is faster than the below, but it can't be the small amount of code)
String str = "";
for (String i:arr)
str += i;
System.out.println(str);
Side note:
String[] arr[3]= [1,2,3]
won't compile.
Presumably you wanted: String[] arr = {"1", "2", "3"};
As of PHP >= 5.4.0
$translatedString = transliterator_transliterate('Any-Latin; Latin-ASCII; [\u0080-\u7fff] remove', $string);
class Grandpa
{
public function __construct()
{}
}
class Papa extends Grandpa
{
public function __construct()
{
//call Grandpa's constructor
parent::__construct();
}
}
class Kiddo extends Papa
{
public function __construct()
{
//this is not a bug, it works that way in php
Grandpa::__construct();
}
}
Not having a compiler by me right now, I'll answer by asking a question:
Have you tried this? Does it work?
long key = -1L;
PreparedStatement statement = connection.prepareStatement();
statement.executeUpdate(YOUR_SQL_HERE, PreparedStatement.RETURN_GENERATED_KEYS);
ResultSet rs = statement.getGeneratedKeys();
if (rs != null && rs.next()) {
key = rs.getLong(1);
}
Disclaimer: Obviously, I haven't compiled this, but you get the idea.
PreparedStatement is a subinterface of Statement, so I don't see a reason why this wouldn't work, unless some JDBC drivers are buggy.
You forgot to seek:
str.CopyTo(data);
data.Seek(0, SeekOrigin.Begin); // <-- missing line
byte[] buf = new byte[data.Length];
data.Read(buf, 0, buf.Length);
var startDate = $('#start_date').val().replace(/-/g,'/');
var endDate = $('#end_date').val().replace(/-/g,'/');
if(startDate > endDate){
// do your stuff here...
}
If you are doing it in eclipse, there are a few quick notes that if you are hovering your mouse over a class in your script, it will show a focus dialogue that says hit f2 for focus.
for computer apps, use ImageIcon. and for the path say,
ImageIcon thisImage = new ImageIcon("images/youpic.png");
specify the folder( images) then seperate with / and add the name of the pic file.
I hope this is helpful. If someone else posted it, I didn't read through. So...yea.. thought reinforcement.
This depends on the language being used. You wrote 'language-agnostic', so I'll give some examples.
In Java, C, and Python, recursion is fairly expensive compared to iteration (in general) because it requires the allocation of a new stack frame. In some C compilers, one can use a compiler flag to eliminate this overhead, which transforms certain types of recursion (actually, certain types of tail calls) into jumps instead of function calls.
In functional programming language implementations, sometimes, iteration can be very expensive and recursion can be very cheap. In many, recursion is transformed into a simple jump, but changing the loop variable (which is mutable) sometimes requires some relatively heavy operations, especially on implementations which support multiple threads of execution. Mutation is expensive in some of these environments because of the interaction between the mutator and the garbage collector, if both might be running at the same time.
I know that in some Scheme implementations, recursion will generally be faster than looping.
In short, the answer depends on the code and the implementation. Use whatever style you prefer. If you're using a functional language, recursion might be faster. If you're using an imperative language, iteration is probably faster. In some environments, both methods will result in the same assembly being generated (put that in your pipe and smoke it).
Addendum: In some environments, the best alternative is neither recursion nor iteration but instead higher order functions. These include "map", "filter", and "reduce" (which is also called "fold"). Not only are these the preferred style, not only are they often cleaner, but in some environments these functions are the first (or only) to get a boost from automatic parallelization — so they can be significantly faster than either iteration or recursion. Data Parallel Haskell is an example of such an environment.
List comprehensions are another alternative, but these are usually just syntactic sugar for iteration, recursion, or higher order functions.
It's legit and very handy!
Try this:
<script id="hello" type="text/template">
Hello world
</script>
<script>
alert($('#hello').html());
</script>
Several Javascript templating libraries use this technique. Handlebars.js is a good example.
I don't know what things were like in the alpha, but I'm using beta 12 right now and this works fine. If you have an array of objects, create a select like this:
<select [(ngModel)]="simpleValue"> // value is a string or number
<option *ngFor="let obj of objArray" [value]="obj.value">{{obj.name}}</option>
</select>
If you want to match on the actual object, I'd do it like this:
<select [(ngModel)]="objValue"> // value is an object
<option *ngFor="let obj of objArray" [ngValue]="obj">{{obj.name}}</option>
</select>
$replace_str = array('"', "'", ",");
$FileName = str_replace($replace_str, "", $UserInput);
To plot just a selection of your columns you can select the columns of interest by passing a list to the subscript operator:
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
What you tried was df['V1','V2']
this will raise a KeyError
as correctly no column exists with that label, although it looks funny at first you have to consider that your are passing a list hence the double square brackets [[]]
.
import matplotlib.pyplot as plt
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
ax.set_xlabel("Hour", fontsize=12)
ax.set_ylabel("V", fontsize=12)
plt.show()
Well, the code that renders the button enabled/disabled:
if(name.getText().equals("")) {
loginbt.setEnabled(false);
}else {
loginbt.setEnabled(true);
}
must be written in javax.swing.event.ChangeListener
and attached to the field (see here). A change in field's value should trigger the listener to reevaluate the object state. What did you expect?
Well, the code you've given is invalid to start with - List
is a generic type, and it has an Add
method instead of add
etc.
But you could do something like:
List<Person> list = new List<Person>
{
new person{ID=1,Name="jhon",salary=2500},
new person{ID=2,Name="Sena",salary=1500},
new person{ID=3,Name="Max",salary=5500}.
new person{ID=4,Name="Gen",salary=3500}
};
// The "Where" LINQ operator filters a sequence
var highEarners = list.Where(p => p.salary > 3000);
foreach (var person in highEarners)
{
Console.WriteLine(person.Name);
}
If you want to learn details of what all the LINQ operators do, and how they can be implemented in LINQ to Objects, you might be interested in my Edulinq blog series.
error_reporting(E_ALL ^ E_WARNING);
:)
You should change subject to "How to fix warning from date() in PHP"...
<a href="/#/#faq-1">Question 1</a>
<a href="/#/#faq-2">Question 2</a>
<a href="/#/#faq-3">Question 3</a>
It depends on the specific use case.
If your table is static and only has a short list of values (and there is just a small chance that this would change during a lifetime of DB), I would recommend this construction:
CREATE TABLE Foo
(
FooCode VARCHAR(16), -- short code or shortcut, but with some meaning.
Name NVARCHAR(128), -- full name of entity, can be used as fallback in case when your localization for some language doesn't exist
LocalizationCode AS ('Foo.' + FooCode) -- This could be a code for your localization table...
)
Of course, when your table is not static at all, using INT as primary key is the best solution.
Use a negative lookahead and a negative lookbehind:
> s = "one two 3.4 5,6 seven.eight nine,ten"
> parts = re.split('\s|(?<!\d)[,.](?!\d)', s)
['one', 'two', '3.4', '5,6', 'seven', 'eight', 'nine', 'ten']
In other words, you always split by \s
(whitespace), and only split by commas and periods if they are not followed (?!\d)
or preceded (?<!\d)
by a digit.
DEMO.
EDIT: As per @verdesmarald comment, you may want to use the following instead:
> s = "one two 3.4 5,6 seven.eight nine,ten,1.2,a,5"
> print re.split('\s|(?<!\d)[,.]|[,.](?!\d)', s)
['one', 'two', '3.4', '5,6', 'seven', 'eight', 'nine', 'ten', '1.2', 'a', '5']
This will split "1.2,a,5"
into ["1.2", "a", "5"]
.
DEMO.
myfun <- function(x, arg1) {
# doing something here with x and arg1
}
x
is a vector or a list and myfun
in lapply(x, myfun)
is called for each element of x
separately.
Option 1
If you'd like to use whole arg1
in each myfun
call (myfun(x[1], arg1)
, myfun(x[2], arg1)
etc.), use lapply(x, myfun, arg1)
(as stated above).
Option 2
If you'd however like to call myfun
to each element of arg1
separately alongside elements of x
(myfun(x[1], arg1[1])
, myfun(x[2], arg1[2])
etc.), it's not possible to use lapply
. Instead, use mapply(myfun, x, arg1)
(as stated above) or apply
:
apply(cbind(x,arg1), 1, myfun)
or
apply(rbind(x,arg1), 2, myfun).
I think one possible solution to this is to use display: table
:
.header {
display: table;
width: 100%;
box-sizing: border-box;
}
.header > * {
display: table-cell;
}
.header > *:last-child {
text-align: right;
}
h1 {
font-size: 32px;
}
nav {
vertical-align: baseline;
}
JSFiddle: http://jsfiddle.net/yxxrnn7j/1/
I use this code and RUN SUCCESS FULL:
$filename = 'apptoko-2016-12-23.sql'; //change to ur .sql file
$handle = fopen($filename, "r+");
$contents = fread($handle, filesize($filename));
$sql = explode(";",$contents);//
foreach($sql as $query){
$result=mysql_query($query);
if ($result){
echo '<tr><td><BR></td></tr>';
echo '<tr><td>' . $query . ' <b>SUCCESS</b></td></tr>';
echo '<tr><td><BR></td></tr>';
}
}
fclose($handle);
In C++11 and C++14 we have much better options with the random header. The presentation rand() Considered Harmful by Stephan T. Lavavej explains why we should eschew the use of rand()
in C++ in favor of the random
header and N3924: Discouraging rand() in C++14 further reinforces this point.
The example below is a modified version of the sample code on the cppreference site and uses the std::mersenne_twister_engine engine and the std::uniform_real_distribution which generates numbers in the [0,1)
range (see it live):
#include <iostream>
#include <iomanip>
#include <map>
#include <random>
int main()
{
std::random_device rd;
std::mt19937 e2(rd());
std::uniform_real_distribution<> dist(0, 1);
std::map<int, int> hist;
for (int n = 0; n < 10000; ++n) {
++hist[std::round(dist(e2))];
}
for (auto p : hist) {
std::cout << std::fixed << std::setprecision(1) << std::setw(2)
<< p.first << ' ' << std::string(p.second/200, '*') << '\n';
}
}
output will be similar to the following:
0 ************************
1 *************************
Since the post mentioned that speed was important then we should consider the cppreference section that describes the different random number engines (emphasis mine):
The choice of which engine to use involves a number of tradeoffs*: the **linear congruential engine is moderately fast and has a very small storage requirement for state. The lagged Fibonacci generators are very fast even on processors without advanced arithmetic instruction sets, at the expense of greater state storage and sometimes less desirable spectral characteristics. The Mersenne twister is slower and has greater state storage requirements but with the right parameters has the longest non-repeating sequence with the most desirable spectral characteristics (for a given definition of desirable).
So if there is a desire for a faster generator perhaps ranlux24_base or ranlux48_base are better choices over mt19937.
rand()
If you forced to use rand()
then the C FAQ for a guide on How can I generate floating-point random numbers?, gives us an example similar to this for generating an on the interval [0,1)
:
#include <stdlib.h>
double randZeroToOne()
{
return rand() / (RAND_MAX + 1.);
}
and to generate a random number in the range from [M,N)
:
double randMToN(double M, double N)
{
return M + (rand() / ( RAND_MAX / (N-M) ) ) ;
}
Use this query :
SELECT OBJECT_NAME(parent_id) as Table_Name, * FROM [Database_Name].sys.triggers
It's simple and useful.
Why do you care?
99.99% of the time, you shouldn't care.
These sorts of micro-optimizations are unlikely to affect the performance of your code.
Also, if you NEEDED to care, then you should be doing performance profiling on your code. In which case finding out the performance difference between a switch case and an if-else block would be trivial.
Edit: For clarity's sake: implement whichever design is clearer and more maintainable. Generally when faced with a huge switch-case or if-else block the solution is to use polymorphism. Find the behavior that's changing and encapsulate it. I've had to deal with huge, ugly switch case code like this before and generally it's not that difficult to simplify. But oh so satisfying.
In standard C++, technically there is no way to do this since standard C++ has no conception of directories. If you want to expand your net a little bit, you might like to look at using Boost.FileSystem. This has been accepted for inclusion in TR2, so this gives you the best chance of keeping your implementation as close as possible to the standard.
An example, taken straight from the website:
bool find_file( const path & dir_path, // in this directory,
const std::string & file_name, // search for this name,
path & path_found ) // placing path here if found
{
if ( !exists( dir_path ) ) return false;
directory_iterator end_itr; // default construction yields past-the-end
for ( directory_iterator itr( dir_path );
itr != end_itr;
++itr )
{
if ( is_directory(itr->status()) )
{
if ( find_file( itr->path(), file_name, path_found ) ) return true;
}
else if ( itr->leaf() == file_name ) // see below
{
path_found = itr->path();
return true;
}
}
return false;
}
A particular example:
I have Java 7 and Java 6 installed, I need to run some builds with 6, others with 7. Therefore I need to dynamically alter JAVA_HOME
so that maven picks up what I want for each build. I did the following:
j6.sh
script which simply does export JAVA_HOME=...
path to j6 install...j6.sh
in that respective command terminal. By default, my JAVA_HOME
is set to J7.Hope this helps.
Hi url should be calling a function which in return will give response
$.ajax({
url:'function to call url',
...
...
});
try using/calling API facebook method
I believe you can do this:
gem "foo", path: "/path/to/foo"
|*| Sorting an List :
import java.util.Collections;
|=> Sort Asc Order :
Collections.sort(NamAryVar);
|=> Sort Dsc Order :
Collections.sort(NamAryVar, Collections.reverseOrder());
|*| Reverse the order of List :
Collections.reverse(NamAryVar);
I think you have added firebase json file "google-services".json with the new file. Make sure to create a new file check the link on how to create json file from firebase and it should match with your package name
Second thing is that if you are changing the package name use the option " replace in path" when you right click under files when you select project from the drop down. You have to search for package name in the whole project and replace it !
Hope this helps !
There is a massive difference in the example you have posted, the first version:
var urls = await context.Urls.ToListAsync();
This is bad, it basically does select * from table
, returns all results into memory and then applies the where
against that in memory collection rather than doing select * from table where...
against the database.
The second method will not actually hit the database until a query is applied to the IQueryable
(probably via a linq .Where().Select()
style operation which will only return the db values which match the query.
If your examples were comparable, the async
version will usually be slightly slower per request as there is more overhead in the state machine which the compiler generates to allow the async
functionality.
However the major difference (and benefit) is that the async
version allows more concurrent requests as it doesn't block the processing thread whilst it is waiting for IO to complete (db query, file access, web request etc).
As the other answers state, changing the user's profile (e.g. the 'DEFAULT' profile) appropriately will lead to passwords, that once set, will never expire.
However, as one commenter points out, passwords set under the profile's old values may already be expired, and (if after the profile's specified grace period) the account locked.
The solution for expired passwords with locked accounts (as provided in an answering comment) is to use one version of the ALTER USER command:
ALTER USER xyz_user ACCOUNT UNLOCK;
However the unlock command only works for accounts where the account is actually locked, but not for those accounts that are in the grace period, i.e. where the password is expired but the account is not yet locked. For these accounts the password must be reset with another version of the ALTER USER command:
ALTER USER xyz_user IDENTIFIED BY new_password;
Below is a little SQL*Plus script that a privileged user (e.g. user 'SYS') can use to reset a user's password to the current existing hashed value stored in the database.
EDIT: Older versions of Oracle store the password or password-hash in the pword column, newer versions of Oracle store the password-hash in the spare4 column. Script below changed to collect the pword and spare4 columns, but to use the spare4 column to reset the user's account; modify as needed.
REM Tell SQL*Plus to show before and after versions of variable substitutions.
SET VERIFY ON
SHOW VERIFY
REM Tell SQL*Plus to use the ampersand '&' to indicate variables in substitution/expansion.
SET DEFINE '&'
SHOW DEFINE
REM Specify in a SQL*Plus variable the account to 'reset'.
REM Note that user names are case sensitive in recent versions of Oracle.
REM DEFINE USER_NAME = 'xyz_user'
REM Show the status of the account before reset.
SELECT
ACCOUNT_STATUS,
TO_CHAR(LOCK_DATE, 'YYYY-MM-DD HH24:MI:SS') AS LOCK_DATE,
TO_CHAR(EXPIRY_DATE, 'YYYY-MM-DD HH24:MI:SS') AS EXPIRY_DATE
FROM
DBA_USERS
WHERE
USERNAME = '&USER_NAME';
REM Create SQL*Plus variable to hold the existing values of the password and spare4 columns.
DEFINE OLD_SPARE4 = ""
DEFINE OLD_PASSWORD = ""
REM Tell SQL*Plus where to store the values to be selected with SQL.
REM Note that the password hash value is stored in spare4 column in recent versions of Oracle,
REM and in the password column in older versions of Oracle.
COLUMN SPARE4HASH NEW_VALUE OLD_SPARE4
COLUMN PWORDHASH NEW_VALUE OLD_PASSWORD
REM Select the old spare4 and password columns as delimited strings
SELECT
'''' || SPARE4 || '''' AS SPARE4HASH,
'''' || PASSWORD || '''' AS PWORDHASH
FROM
SYS.USER$
WHERE
NAME = '&USER_NAME';
REM Show the contents of the SQL*Plus variables
DEFINE OLD_SPARE4
DEFINE OLD_PASSWORD
REM Reset the password - Older versions of Oracle (e.g. Oracle 10g and older)
REM ALTER USER &USER_NAME IDENTIFIED BY VALUES &OLD_PASSWORD;
REM Reset the password - Newer versions of Oracle (e.g. Oracle 11g and newer)
ALTER USER &USER_NAME IDENTIFIED BY VALUES &OLD_SPARE4;
REM Show the status of the account after reset
SELECT
ACCOUNT_STATUS,
TO_CHAR(LOCK_DATE, 'YYYY-MM-DD HH24:MI:SS') AS LOCK_DATE,
TO_CHAR(EXPIRY_DATE, 'YYYY-MM-DD HH24:MI:SS') AS EXPIRY_DATE
FROM
DBA_USERS
WHERE
USERNAME = '&USER_NAME';
No, IIRC there is no getopt() on Windows.
Boost, however, has the program_options library... which works okay. It will seem like overkill at first, but it isn't terrible, especially considering it can handle setting program options in configuration files and environment variables in addition to command line options.
This method worked in my case.
video=getElementsByTagName('video');
function removeControls(video){
video.removeAttribute('controls');
}
window.onload=removeControls(video);
The Code part :
Image imProfile = new Image(getClass().getResourceAsStream("/img/profile128.png"));
ImageView profileImage=new ImageView(imProfile);
in a javafx maven:
You need to specify the master for the second button. Otherwise it will get packed onto the first window. This is needed not only for Button
, but also for other widgets and non-gui objects such as StringVar
.
Quick fix: add the frame new
as the first argument to your Button
in Demo2
.
Possibly better: Currently you have Demo2
inheriting from tk.Frame
but I think this makes more sense if you change Demo2
to be something like this,
class Demo2(tk.Toplevel):
def __init__(self):
tk.Toplevel.__init__(self)
self.title("Demo 2")
self.button = tk.Button(self, text="Button 2", # specified self as master
width=25, command=self.close_window)
self.button.pack()
def close_window(self):
self.destroy()
Just as a suggestion, you should only import tkinter
once. Pick one of your first two import statements.
For an easy fix, you could
echo 1 > /proc/sys/vm/overcommit_memory
if your're sure that your system has enough memory. See Linux over commit heuristic.
While @Eli is quite correct that there usually isn't much of a need to do it, it is possible. savefig
takes a bbox_inches
argument that can be used to selectively save only a portion of a figure to an image.
Here's a quick example:
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
# Make an example plot with two subplots...
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(range(10), 'b-')
ax2 = fig.add_subplot(2,1,2)
ax2.plot(range(20), 'r^')
# Save the full figure...
fig.savefig('full_figure.png')
# Save just the portion _inside_ the second axis's boundaries
extent = ax2.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
fig.savefig('ax2_figure.png', bbox_inches=extent)
# Pad the saved area by 10% in the x-direction and 20% in the y-direction
fig.savefig('ax2_figure_expanded.png', bbox_inches=extent.expanded(1.1, 1.2))
The full figure:
Area inside the second subplot:
Area around the second subplot padded by 10% in the x-direction and 20% in the y-direction:
sthing like ?
SELECT DISTINCT .... FROM table WHERE condition
http://www.felixgers.de/teaching/sql/sql_distinct.html
note: Homework question ? and god bless google..
No, they're not the same. Aside from the escaping on the client-side that it provides, a prepared statement is compiled on the server-side once, and then can be passed different parameters at each execution. Which means you can do:
$sth = $db->prepare("SELECT * FROM table WHERE foo = ?");
$sth->execute(array(1));
$results = $sth->fetchAll(PDO::FETCH_ASSOC);
$sth->execute(array(2));
$results = $sth->fetchAll(PDO::FETCH_ASSOC);
They generally will give you a performance improvement, although not noticeable on a small scale. Read more on prepared statements (MySQL version).
On linux (Ubuntu in my case) just install gradle:
sudo apt-get install gradle
Edit: It seems as though ubuntu repo only has gradle 2.10, for newer versions: https://www.vultr.com/docs/how-to-install-gradle-on-ubuntu-16-10
numpy has a great tool for this task ("numpy.reshape") link to reshape documentation
a = [[ 0 1]
[ 2 3]
[ 4 5]
[ 6 7]
[ 8 9]
[10 11]
[12 13]
[14 15]
[16 17]]
`numpy.reshape(a,(3,3))`
you can also use the "-1" trick
`a = a.reshape(-1,3)`
the "-1" is a wild card that will let the numpy algorithm decide on the number to input when the second dimension is 3
so yes.. this would also work:
a = a.reshape(3,-1)
and this:
a = a.reshape(-1,2)
would do nothing
and this:
a = a.reshape(-1,9)
would change the shape to (2,9)
You can use .filter
on a jQuery object that was created from the response:
success: function(data){
//Create jQuery object from the response HTML.
var $response=$(data);
//Query the jQuery object for the values
var oneval = $response.filter('#one').text();
var subval = $response.filter('#sub').text();
}
I had a similar problem and found the way that worked best was to rely on Event Bubbling and event delegation to handle it. The nice thing about event delegation is that once setup, you don't have to rebind events after an AJAX update.
What I do in my code is setup a delegate on the parent element of the update panel. This parent element is not replaced on an update and therefore the event binding is unaffected.
There are a number of good articles and plugins to handle event delegation in jQuery and the feature will likely be baked into the 1.3 release. The article/plugin I use for reference is:
http://www.danwebb.net/2008/2/8/event-delegation-made-easy-in-jquery
Once you understand what it happening, I think you'll find this a much more elegant solution that is more reliable than remembering to re-bind events after every update. This also has the added benefit of giving you one event to unbind when the page is unloaded.
Laravel ships with a pretty URL .htaccess already... you should be good to go out of the box... http://laravel.com/docs/installation#pretty-urls
Make sure mod_rewrite is enabled and that your home path is set to the public directory of your application.
After struggling with this issue too many times I found a very elegant solution in HTML 5. In HTML 5 you should not close several (li,p,etc) tags; the ambition to become XML is forever gone. For example, the preferred way to do a list is:
<ul>
<li>
<a ...>...</a>
<li>
<a ...>...</a>
</ul>
Browsers MUST close the LI and they must do this without introducing whitespace, solving this problem. If you still have the XML mindset it feels wrong but once you get over that it saves many a nightmare. And this is not a hack since it relies on the wording of the HTML 5 spec. Better, since not closing tags is pervasive I expect no compatibility issues (not tested though). Bonus is that HTML formatters handle this well.
A little worked out example: http://cssdesk.com/Ls7fK
For "100% of the browser window", if you mean this literally, you should use fixed positioning. The top, bottom, right, and left properties are then used to offset the divs edges from the respective edges of the viewport:
#nav, #content{position:fixed;top:0px;bottom:0px;}
#nav{left:0px;right:235px;}
#content{left:235px;right:0px}
This will set up a screen with the left 235 pixels devoted to the nav, and the right rest of the screen to content.
Note, however, you won't be able to scroll the whole screen at once. Though you can set it to scroll either pane individually, by applying overflow:auto
to either div.
Note also: fixed positioning is not supported in IE6 or earlier.
You also can do type switches:
switch v := myInterface.(type) {
case int:
// v is an int here, so e.g. v + 1 is possible.
fmt.Printf("Integer: %v", v)
case float64:
// v is a float64 here, so e.g. v + 1.0 is possible.
fmt.Printf("Float64: %v", v)
case string:
// v is a string here, so e.g. v + " Yeah!" is possible.
fmt.Printf("String: %v", v)
default:
// And here I'm feeling dumb. ;)
fmt.Printf("I don't know, ask stackoverflow.")
}
This is actually a bug in the tutorials code. I was having the same issue and I finally realized the issue was in the "note_edit.xml" file.
Some of the layout_heigh/width attributes were set to "match_parent" which is not a valid value, they're supposed to be set to "fill_parent".
This was throwing a bug, that was causing the generation of the R.java file to fail. So, if you're having this issue, or a similar one, check all of your xml files and make sure that none of them have any errors.
df['new'] = 0
For in-place modification, perform direct assignment. This assignment is broadcasted by pandas for each row.
df = pd.DataFrame('x', index=range(4), columns=list('ABC'))
df
A B C
0 x x x
1 x x x
2 x x x
3 x x x
df['new'] = 'y'
# Same as,
# df.loc[:, 'new'] = 'y'
df
A B C new
0 x x x y
1 x x x y
2 x x x y
3 x x x y
If you want to add an column of empty lists, here is my advice:
object
columns are bad news in terms of performance. Rethink how your data is structured. If you must store a column of lists, ensure not to copy the same reference multiple times.
# Wrong
df['new'] = [[]] * len(df)
# Right
df['new'] = [[] for _ in range(len(df))]
df.assign(new=0)
If you need a copy instead, use DataFrame.assign
:
df.assign(new='y')
A B C new
0 x x x y
1 x x x y
2 x x x y
3 x x x y
And, if you need to assign multiple such columns with the same value, this is as simple as,
c = ['new1', 'new2', ...]
df.assign(**dict.fromkeys(c, 'y'))
A B C new1 new2
0 x x x y y
1 x x x y y
2 x x x y y
3 x x x y y
Finally, if you need to assign multiple columns with different values, you can use assign
with a dictionary.
c = {'new1': 'w', 'new2': 'y', 'new3': 'z'}
df.assign(**c)
A B C new1 new2 new3
0 x x x w y z
1 x x x w y z
2 x x x w y z
3 x x x w y z
If you are using this in chrome/chromium browser(ex: in Ubuntu 14.04), You can use one of the below command to tackle this issue.
ThinkPad-T430:~$ google-chrome --allow-file-access-from-files
ThinkPad-T430:~$ google-chrome --allow-file-access-from-files fileName.html
ThinkPad-T430:~$ chromium-browser --allow-file-access-from-files
ThinkPad-T430:~$ chromium-browser --allow-file-access-from-files fileName.html
This will allow you to load the file in chrome or chromium. If you have to do the same operation for windows you can add this switch in properties of the chrome shortcut or run it from cmd
with the flag. This operation is not allowed in Chrome, Opera, Internet Explorer by default. By default it works only in firefox and safari. Hence using this command will help you.
Alternately you can also host it on any web server (Example:Tomcat-java,NodeJS-JS,Tornado-Python, etc) based on what language you are comfortable with. This will work from any browser.
df.info() function will give you result something like as below. If you are using read_csv method of Pandas without sep parameter or sep with ",".
raw_data = pd.read_csv("a1:\aa2/aaa3/data.csv")
raw_data.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5144 entries, 0 to 5143
Columns: 145 entries, R_fighter to R_age
Java 8
NOTE: All, but one, Date
's constructors are deprecated. Most of the Date
's methods are deprecated. REF: Date: Deprecated Methods. All, but Date::from(Instant)
, static methods are deprecated.
So, since java 8 consider using Instant
(immutable, thread-safe, leap-seconds aware) type rather than Date
. REF: Instant
static final LocalTime MARKETS_OPEN = LocalTime.of(07, 00);
static final LocalTime MARKETS_CLOSE = LocalTime.of(20, 00);
// Instant utcTime = testDate.toInstant();
var bigAppleTime = ZonedDateTime.ofInstant(utcTime, ZoneId.of("America/New_York"));
return !bigAppleTime.toLocalTime().isBefore(MARKETS_OPEN)
&& !bigAppleTime.toLocalTime().isAfter(MARKETS_CLOSE);
return bigAppleTime.toLocalTime().isAfter(MARKETS_OPEN)
&& bigAppleTime.toLocalTime().isBefore(MARKETS_CLOSE);
The primary flag seems to only work for vagrant ssh
for me.
In the past I have used the following method to hack around the issue.
# stage box intended for configuration closely matching production if ARGV[1] == 'stage' config.vm.define "stage" do |stage| box_setup stage, \ "10.9.8.31", "deploy/playbook_full_stack.yml", "deploy/hosts/vagrant_stage.yml" end end
I ran into this error with mysql (version: 5.6.46_2), Mac (Mojave 10.14.5):
brew update && brew upgrade
brew now setup_mysql
echo ‘export PATH=“/usr/local/opt/mysql56/bin:$PATH”’ >>
~/.bash_profile
/usr/local/opt/mysql56/bin/mysql.server start
I've always called them "compiler directives." They direct the compiler to do things, branching, including libs like shown above, disabling specific errors etc., during the compilation phase.
Compiler companies usually create their own extensions to facilitate their features. For example, (I believe) Microsoft started the "#pragma once" deal and it was only in MS products, now I'm not so sure.
Pragma Directives It includes "#pragma comment" in the table you'll see.
HTH
I suspect GCC, for example, has their own set of #pragma's.
There is a jQuery plugin that can deal with this very well
http://www.jqui.net/jquery-projects/jquery-mutate-official/
here is a demo of it with different scenarios as to when the height change, if you resize the red bordered div.
Using a for-of
on Object.keys()
Like:
let object = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
};
for (let key of Object.keys(object)) {
console.log(key + " : " + object[key])
}
_x000D_
Well I'm not exactly sure why your code is not working because I usually follow a different approach when trying to accomplish something similar.
But your code is erroring out.. There seems to be an issue with the way you are using scale
I got the jQuery to actually execute by changing your code to the following.
$(document).ready(function(){
$('img').hover(function() {
$(this).css("cursor", "pointer");
$(this).toggle({
effect: "scale",
percent: "90%"
},200);
}, function() {
$(this).toggle({
effect: "scale",
percent: "80%"
},200);
});
});
But I have always done it by using CSS
to setup my scaling and transition..
Here is an example, hopefully it helps.
$(document).ready(function(){
$('#content').hover(function() {
$("#content").addClass('transition');
}, function() {
$("#content").removeClass('transition');
});
});
You should check for ''
(empty string) before pushing into your array. Your array has elements that are empty strings. Then your album_text.length === 0
will work just fine.
I found an easier way to do it without the need of extra methods that arrange a queue.
JS
$.ajax({
type: 'POST',
url: 'ajax1.php',
data:{
id: 1,
cb:'method1'//declaration of callback method of ajax1.php
},
success: function(data){
//catching up values
var data = JSON.parse(data);
var cb=data[0].cb;//here whe catching up the callback 'method1'
eval(cb+"(JSON.stringify(data));");//here we calling method1 and pass all data
}
});
$.ajax({
type: 'POST',
url: 'ajax2.php',
data:{
id: 2,
cb:'method2'//declaration of callback method of ajax2.php
},
success: function(data){
//catching up values
var data = JSON.parse(data);
var cb=data[0].cb;//here whe catching up the callback 'method2'
eval(cb+"(JSON.stringify(data));");//here we calling method2 and pass all data
}
});
//the callback methods
function method1(data){
//here we have our data from ajax1.php
alert("method1 called with data="+data);
//doing stuff we would only do in method1
//..
}
function method2(data){
//here we have our data from ajax2.php
alert("method2 called with data="+data);
//doing stuff we would only do in method2
//..
}
PHP (ajax1.php)
<?php
//catch up callbackmethod
$cb=$_POST['cb'];//is 'method1'
$json[] = array(
"cb" => $cb,
"value" => "ajax1"
);
//encoding array in JSON format
echo json_encode($json);
?>
PHP (ajax2.php)
<?php
//catch up callbackmethod
$cb=$_POST['cb'];//is 'method2'
$json[] = array(
"cb" => $cb,
"value" => "ajax2"
);
//encoding array in JSON format
echo json_encode($json);
?>
You can find the full list here.
\t
Insert a tab in the text at this point.\b
Insert a backspace in the text at this point.\n
Insert a newline in the text at this point.\r
Insert a carriage return in the text at this point.\f
Insert a formfeed in the text at this point.\'
Insert a single quote character in the text at this point.\"
Insert a double quote character in the text at this point.\\
Insert a backslash character in the text at this point.With the launch of systemd, there's another scenario aswell. By default systemd will store core dumps in its journal, being accessible with the systemd-coredumpctl
command. Defined in the core_pattern-file:
$ cat /proc/sys/kernel/core_pattern
|/usr/lib/systemd/systemd-coredump %p %u %g %s %t %e
This behaviour can be disabled with a simple "hack":
$ ln -s /dev/null /etc/sysctl.d/50-coredump.conf
$ sysctl -w kernel.core_pattern=core # or just reboot
As always, the size of core dumps has to be equal or higher than the size of the core that is being dumped, as done by for example ulimit -c unlimited
.
set the wrapper to height 100%
.vwrapper {
display: flex;
flex-direction: column;
flex-wrap: nowrap;
justify-content: flex-start;
align-items: stretch;
align-content: stretch;
height: 100%;
}
and set the 3rd row to flex-grow
#row3 {
background-color: green;
flex: 1 1 auto;
display: flex;
}
I know this thread is a bit old, but it took me some time to get to the heart of this, so I wanted to share.
In my project, I had the main script in a parent directory, and, to differentiate the modules, I put all the supporting modules in a sub-folder called "modules". In my main script, I import these modules like this (for a module called report.py):
from modules.report import report, reportError
If I call my main script, this works. HOWEVER, I wanted to test each module by including a main()
in each, and calling each directly, as:
python modules/report.py
Now Python complains that it can't find "a module called modules". The key here is that, by default, Python includes the folder of the script in its search path, BUT NOT THE CWD. So what this error says, really, is "I can't find a modules subfolder". The is because there is no "modules" subdirectory from the directory where the report.py module resides.
I find that the neatest solution to this is to append the CWD in Python search path by including this at the top:
import sys
sys.path.append(".")
Now Python searches the CWD (current directory), finds the "modules" sub-folder, and all is well.
To align two divs horizontally you just have to combine two classes of Bootstrap: Here's how:
<div class ="container-fluid">
<div class ="row">
<div class ="col-md-6 col-sm-6">
First Div
</div>
<div class ="col-md-6 col-sm-6">
Second Div
</div>
</div>
</div>
I have experienced this "App not installed" error when the device I was installing to didn't have enough storage. Deleting a few files allowed the app to install. Odd that it didn't give me a "not enough space" message instead. (Note: I was installing an apk manually from an "unknown" location.)
See for a comparison of net-ioc-frameworks on google code including linfu and spring.net that are not on your list while i write this text.
I worked with spring.net: It has many features (aop, libraries , docu, ...) and there is a lot of experience with it in the dotnet and the java-world. The features are modularized so you donot have to take all features. The features are abstractions of common issues like databaseabstraction, loggingabstraction. however it is difficuilt to do and debug the IoC-configuration.
From what i have read so far: If i had to chooseh for a small or medium project i would use ninject since ioc-configuration is done and debuggable in c#. But i havent worked with it yet. for large modular system i would stay with spring.net because of abstraction-libraries.
Float is Approximate-number data type, which means that not all values in the data type range can be represented exactly.
Decimal/Numeric is Fixed-Precision data type, which means that all the values in the data type range can be represented exactly with precision and scale. You can use decimal for money saving.
Converting from Decimal or Numeric to float can cause some loss of precision. For the Decimal or Numeric data types, SQL Server considers each specific combination of precision and scale as a different data type. DECIMAL(2,2) and DECIMAL(2,4) are different data types. This means that 11.22 and 11.2222 are different types though this is not the case for float. For FLOAT(6) 11.22 and 11.2222 are same data types.
You can also use money data type for saving money. This is native data type with 4 digit precision for money. Most experts prefers this data type for saving money.
If your page really relies on the fact that people won't be able to see that menu, you should know that modern browsers (for example Firefox) let the user decide if he really wants to disable it or not. So you have no guarantee at all that the menu would be really disabled.
This error comes in two variatians:
$arr = [1, 2, 3];
This array initializer syntax was only introduced in PHP 5.4; it will raise a parser error on versions before that. If possible, upgrade your installation or use the old syntax:
$arr = array(1, 2, 3);
See also this example from the manual.
$suffix = explode(',', 'foo,bar')[1];
Array dereferencing function results was also introduced in PHP 5.4. If it's not possible to upgrade you need to use a (temporary) variable:
$parts = explode(',', 'foo,bar');
$suffix = $parts[1];
See also this example from the manual.
Thanks to the answer of redsquare I added a method like this:
$.validator.addMethod(
"regex",
function(value, element, regexp) {
var re = new RegExp(regexp);
return this.optional(element) || re.test(value);
},
"Please check your input."
);
Now all you need to do to validate against any regex is this:
$("#Textbox").rules("add", { regex: "^[a-zA-Z'.\\s]{1,40}$" })
Additionally, it looks like there is a file called additional-methods.js
that contains the method "pattern", which can be a RegExp
when created using the method without quotes.
The pattern
function is now the preferred way to do this, making the example:
$("#Textbox").rules("add", { pattern: "^[a-zA-Z'.\\s]{1,40}$" })
If you want to set Min 1 count and no Max length,
^.{1,}$
Try:
require(Hmisc)
sapply(name, function(x) {
paste(sapply(strsplit(x, ' '), capitalize), collapse=' ')
})
The first solution is to use the java.util.Random
class:
import java.util.Random;
Random rand = new Random();
// Obtain a number between [0 - 49].
int n = rand.nextInt(50);
// Add 1 to the result to get a number from the required range
// (i.e., [1 - 50]).
n += 1;
Another solution is using Math.random()
:
double random = Math.random() * 49 + 1;
or
int random = (int)(Math.random() * 50 + 1);
You can write as:
<div class="case" ng-if="mydata.id === '5' ">
<p> this will execute </p>
</div>
<div class="case" ng-if="mydata.id !== '5' ">
<p> this will execute </p>
</div>
I have a solution that I use only when I have to, after I build my html & css valid and working in most browsers, I do the occasional hack with this amazing piece of javascript from Rafael Lima. http://rafael.adm.br/css_browser_selector/
It keeps my CSS & HTML valid and clean, I know it's not the ideal solution, using javascript to fix hacks, but as long as your code is originally as close as possible (silly IE just breaks things sometimes) then moving something a few px with javascript isn't as big of a deal as some people think. Plus for time/cost reasons is a quick & easy fix.
You need to use ScriptManager.RegisterStartupScript for Ajax.
protected void ButtonPP_Click(object sender, EventArgs e) { if (radioBtnACO.SelectedIndex < 0) { string csname1 = "PopupScript"; var cstext1 = new StringBuilder(); cstext1.Append("alert('Please Select Criteria!')"); ScriptManager.RegisterStartupScript(this, GetType(), csname1, cstext1.ToString(), true); } }
MySQL says:
All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.
When do I use it ?
Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED
data type.
A common mistake is to use a primary key that is an auto-increment INT
starting at zero, yet the type is SIGNED
, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.
This is an interesting discussion. Clearly arrays of refs are outright illegal, but IMHO the reason why is not so simple as saying 'they are not objects' or 'they have no size'. I'd point out that arrays themselves are not full-fledged objects in C/C++ - if you object to that, try instantiating some stl template classes using an array as a 'class' template parameter, and see what happens. You can't return them, assign them, pass them as parameters. ( an array param is treated as a pointer). But it is legal to make arrays of arrays. References do have a size that the compiler can and must calculate - you can't sizeof() a reference, but you can make a struct containing nothing but references. It will have a size sufficient to contain all the pointers which implement the references. You can't instantiate such a struct without initializing all the members:
struct mys {
int & a;
int & b;
int & c;
};
...
int ivar1, ivar2, arr[200];
mys my_refs = { ivar1, ivar2, arr[12] };
my_refs.a += 3 ; // add 3 to ivar1
In fact you can add this line to the struct definition
struct mys {
...
int & operator[]( int i ) { return i==0?a : i==1? b : c; }
};
...and now I have something which looks a LOT like an array of refs:
int ivar1, ivar2, arr[200];
mys my_refs = { ivar1, ivar2, arr[12] };
my_refs[1] = my_refs[2] ; // copy arr[12] to ivar2
&my_refs[0]; // gives &my_refs.a == &ivar1
Now, this is not a real array, it's an operator overload; it won't do things that arrays normally do like sizeof(arr)/sizeof(arr[0]), for instance. But it does exactly what I want an array of references to do, with perfectly legal C++. Except (a) it's a pain to set up for more than 3 or 4 elements, and (b) it's doing a calculation using a bunch of ?: which could be done using indexing (not with normal C-pointer-calculation-semantics indexing, but indexing nonetheless). I'd like to see a very limited 'array of reference' type which can actually do this. I.e. an array of references would not be treated as a general array of things which are references, but rather it would be a new 'array-of-reference' thing which effectively maps to an internally generated class similar to the one above (but which you unfortunately can't make with templates).
this would probably work, if you don't mind this kind of nasty: recast '*this' as an array of int *'s and return a reference made from one: (not recommended, but it shows how the proper 'array' would work):
int & operator[]( int i ) { return *(reinterpret_cast<int**>(this)[i]); }
on the last line, don't use $(this).remove()
use $(this).hide()
instead.
EDIT: To clarify,on the close click event you're removing the #terms
div from the DOM which is why its not coming back. You just need to hide it instead.
We can create a tag for some past commit:
git tag [tag_name] [reference_of_commit]
eg:
git tag v1.0 5fcdb03
You are POSTing the json incorrectly -- but even if it were correct, you would not be able to test using print_r($_POST)
(read why here). Instead, on your second page, you can nab the incoming request using file_get_contents("php://input")
, which will contain the POSTed json. To view the received data in a more readable format, try this:
echo '<pre>'.print_r(json_decode(file_get_contents("php://input")),1).'</pre>';
In your code, you are indicating Content-Type:application/json
, but you are not json-encoding all of the POST data -- only the value of the "customer" POST field. Instead, do something like this:
$ch = curl_init( $url );
# Setup request to send json via POST.
$payload = json_encode( array( "customer"=> $data ) );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
# Return response instead of printing.
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
# Send request.
$result = curl_exec($ch);
curl_close($ch);
# Print response.
echo "<pre>$result</pre>";
Sidenote: You might benefit from using a third-party library instead of interfacing with the Shopify API directly yourself.
func fucntion()
{
var parameters = [String:String]()
let apiToken = "Bearer \(ApiUtillity.sharedInstance.getUserData(key: "vAuthToken"))"
let headers = ["Vauthtoken":apiToken]
parameters = ["firstname":name,"lastname":last_name,"mobile":mobile_number,"email":emails_Address]
Alamofire.request(ApiUtillity.sharedInstance.API(Join: "user/edit_profile"), method: .post, parameters: parameters, encoding: URLEncoding.default,headers:headers).responseJSON { response in
debugPrint(response)
if let json = response.result.value {
let dict:NSDictionary = (json as? NSDictionary)!
print(dict)
// print(response)
let StatusCode = dict.value(forKey: "status") as! Int
if StatusCode==200
{
ApiUtillity.sharedInstance.dismissSVProgressHUDWithSuccess(success: "Success")
let UserData = dict.value(forKey: "data") as! NSDictionary
print(UserData)
}
else if StatusCode==401
{
let ErrorDic:NSDictionary = dict.value(forKey: "message") as! NSDictionary
let ErrorMessage = ErrorDic.value(forKey: "error") as! String
}
else
{
let ErrorDic:NSDictionary = dict.value(forKey: "message") as! NSDictionary
let ErrorMessage = ErrorDic.value(forKey: "error") as! String
}
}
else
{
ApiUtillity.sharedInstance.dismissSVProgressHUDWithError(error: "Something went wrong")
}
}
The easiest way to remove inline styles (generated by jQuery) would be:
$(this).attr("style", "");
The inline code should disappear and your object should adapt the style predefined in your CSS files.
Worked for me!
Another solution is to make a runtime hook, which will copy(or move) your data (files/folders) to the directory at which the executable is stored. The hook is a simple python file that can almost do anything, just before the execution of your app. In order to set it, you should use the --runtime-hook=my_hook.py
option of pyinstaller. So, in case your data is an images folder, you should run the command:
pyinstaller.py --onefile -F --add-data=images;images --runtime-hook=cp_images_hook.py main.py
The cp_images_hook.py could be something like this:
import sys
import os
import shutil
path = getattr(sys, '_MEIPASS', os.getcwd())
full_path = path+"\\images"
try:
shutil.move(full_path, ".\\images")
except:
print("Cannot create 'images' folder. Already exists.")
Before every execution the images folder is moved to the current directory (from the _MEIPASS folder), so the executable will always have access to it. In that way there is no need to modify your project's code.
You can take advantage of the runtime-hook mechanism and change the current directory, which is not a good practice according to some developers, but it works fine.
The hook code can be found below:
import sys
import os
path = getattr(sys, '_MEIPASS', os.getcwd())
os.chdir(path)
Here's what works directly with Vue custom components.
<MyCustomComponent nativeOnScroll={this.handleScroll}>
or
<my-component v-on:scroll.native="handleScroll">
and define a method for handleScroll. Simple!
p $eax
works as of GDB 7.7.1
As of GDB 7.7.1, the command you've tried works:
set $eax = 0
p $eax
# $1 = 0
set $eax = 1
p $eax
# $2 = 1
This syntax can also be used to select between different union members e.g. for ARM floating point registers that can be either floating point or integers:
p $s0.f
p $s0.u
From the docs:
Any name preceded by ‘$’ can be used for a convenience variable, unless it is one of the predefined machine-specific register names.
and:
You can refer to machine register contents, in expressions, as variables with names starting with ‘$’. The names of registers are different for each machine; use info registers to see the names used on your machine.
But I haven't had much luck with control registers so far: OSDev 2012 http://f.osdev.org/viewtopic.php?f=1&t=25968 || 2005 feature request https://www.sourceware.org/ml/gdb/2005-03/msg00158.html || alt.lang.asm 2013 https://groups.google.com/forum/#!topic/alt.lang.asm/JC7YS3Wu31I
ARM floating point registers
Look at bda.cache http://pypi.python.org/pypi/bda.cache - uses ZCA and is tested with zope and bfg.
This is not using Set, Map, List or any extra collection, only two arrays:
package arrays.duplicates;
import java.lang.reflect.Array;
import java.util.Arrays;
public class ArrayDuplicatesRemover<T> {
public static <T> T[] removeDuplicates(T[] input, Class<T> clazz) {
T[] output = (T[]) Array.newInstance(clazz, 0);
for (T t : input) {
if (!inArray(t, output)) {
output = Arrays.copyOf(output, output.length + 1);
output[output.length - 1] = t;
}
}
return output;
}
private static <T> boolean inArray(T search, T[] array) {
for (T element : array) {
if (element.equals(search)) {
return true;
}
}
return false;
}
}
And the main to test it
package arrays.duplicates;
import java.util.Arrays;
public class TestArrayDuplicates {
public static void main(String[] args) {
Integer[] array = {1, 1, 2, 2, 3, 3, 3, 3, 4};
testArrayDuplicatesRemover(array);
}
private static void testArrayDuplicatesRemover(Integer[] array) {
final Integer[] expectedResult = {1, 2, 3, 4};
Integer[] arrayWithoutDuplicates = ArrayDuplicatesRemover.removeDuplicates(array, Integer.class);
System.out.println("Array without duplicates is supposed to be: " + Arrays.toString(expectedResult));
System.out.println("Array without duplicates currently is: " + Arrays.toString(arrayWithoutDuplicates));
System.out.println("Is test passed ok?: " + (Arrays.equals(arrayWithoutDuplicates, expectedResult) ? "YES" : "NO"));
}
}
And the output:
Array without duplicates is supposed to be: [1, 2, 3, 4]
Array without duplicates currently is: [1, 2, 3, 4]
Is test passed ok?: YES
This works for me, I hope helps to someone.
var frm = $('#frm');
let formData = new FormData(frm[0]);
axios.post('your-url', formData)
.then(res => {
console.log({res});
}).catch(err => {
console.error({err});
});
Generally the practice would be to pass data as a DateTime with a "timezone" of UTC and then pass a TimeZoneInfo object and when you are ready to display the data, you use the TimeZoneInfo object to convert the UTC DateTime.
The other option is to set the DateTime with the current timezone, and then make sure the "timezone" is unknown for the DateTime object, then make sure the DateTime is again passed with a TimeZoneInfo that indicates the TimeZone of the DateTime passed.
As others have indicated here, it would be nice if Microsoft got on top of this and created one nice object to do it all, but for now you have to deal with two objects.
Culprit is preflight request using OPTIONS method
For HTTP request methods that can cause side-effects on user data (in particular, for HTTP methods other than GET, or for POST usage with certain MIME types), the specification mandates that browsers "preflight" the request, soliciting supported methods from the server with an HTTP OPTIONS request method, and then, upon "approval" from the server, sending the actual request with the actual HTTP request method.
Web specification refer to: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
I resolved the problem by adding following lines in Nginx conf.
location / {
if ($request_method = OPTIONS ) {
add_header Access-Control-Allow-Origin "*";
add_header Access-Control-Allow-Methods "POST, GET, PUT, UPDATE, DELETE, OPTIONS";
add_header Access-Control-Allow-Headers "Authorization";
add_header Access-Control-Allow-Credentials "true";
add_header Content-Length 0;
add_header Content-Type text/plain;
return 200;
}
location ~ ^/(xxxx)$ {
if ($request_method = OPTIONS) {
rewrite ^(.*)$ / last;
}
}
If you define the ListView
in XAML:
<ListView x:Name="listView"/>
Then you can add columns and populate it in C#:
public Window()
{
// Initialize
this.InitializeComponent();
// Add columns
var gridView = new GridView();
this.listView.View = gridView;
gridView.Columns.Add(new GridViewColumn {
Header = "Id", DisplayMemberBinding = new Binding("Id") });
gridView.Columns.Add(new GridViewColumn {
Header = "Name", DisplayMemberBinding = new Binding("Name") });
// Populate list
this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}
See definition of MyItem
below.
However, it's easier to define the columns in XAML (inside the ListView
definition):
<ListView x:Name="listView">
<ListView.View>
<GridView>
<GridViewColumn Header="Id" DisplayMemberBinding="{Binding Id}"/>
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
</GridView>
</ListView.View>
</ListView>
And then just populate the list in C#:
public Window()
{
// Initialize
this.InitializeComponent();
// Populate list
this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}
See definition of MyItem
below.
MyItem
DefinitionMyItem
is defined like this:
public class MyItem
{
public int Id { get; set; }
public string Name { get; set; }
}
In his paper, Memory Optimization, Christer Ericson says that while restrict
is not part of the C++ standard yet, that it is supported by many compilers and he recommends it's usage when available:
restrict keyword
! New to 1999 ANSI/ISO C standard
! Not in C++ standard yet, but supported by many C++ compilers
! A hint only, so may do nothing and still be conforming
A restrict-qualified pointer (or reference)...
! ...is basically a promise to the compiler that for the scope of the pointer, the target of the pointer will only be accessed through that pointer (and pointers copied from it).
In C++ compilers that support it it should probably behave the same as in C.
See this SO post for details: Realistic usage of the C99 ‘restrict’ keyword?
Take half an hour to skim through Ericson's paper, it's interesting and worth the time.
Edit
I also found that IBM's AIX C/C++ compiler supports the __restrict__
keyword.
g++ also seems to support this as the following program compiles cleanly on g++:
#include <stdio.h>
int foo(int * __restrict__ a, int * __restrict__ b) {
return *a + *b;
}
int main(void) {
int a = 1, b = 1, c;
c = foo(&a, &b);
printf("c == %d\n", c);
return 0;
}
I also found a nice article on the use of restrict
:
Demystifying The Restrict Keyword
Edit2
I ran across an article which specifically discusses the use of restrict in C++ programs:
Load-hit-stores and the __restrict keyword
Also, Microsoft Visual C++ also supports the __restrict
keyword.
button {
background:transparent;
border:none;
outline:none;
display:block;
height:200px;
width:200px;
cursor:pointer;
}
Give the height and width with respect to the image in the background.This removes the borders and color of a button.You might also need to position it absolute so you can correctly place it where you need.I cant help you further without posting you code
To make it truly invisible you have to set outline:none; otherwise there would be a blue outline in some browsers and you have to set display:block if you need to click it and set dimensions to it
Maybe remove the semi-colon after set because now the where statement doesn't belong to the update statement. Also the idRequest
could be a problem, better write BookingRequest.idRequest
As noted here, you can also customise the getter/setter generation to take prefixes and suffixes (e.g. m for instance variables) into account. Go to File->Settings
and expand Code Style
, select Java
, and add your prefixes/suffixes under the Code Generation
tab.
Reinstall node, then update npm.
First I removed node
apt-get purge node
Then install node according to the distibution. Docs here .
Then
npm install npm@latest -g
A reference
in Docker is what points to an image. This could be in a remote registry or the local registry. Let me describe the error message first and then show the solutions for this.
invalid reference format
This means that the reference we have used is not a valid format. This means, the reference (pointer) we have used to identify an image is invalid. Generally, this is followed by a description as follows. This will make the error much clearer.
invalid reference format: repository name must be lowercase
This means the reference we are using should not have uppercase letters. Try running docker run Ubuntu
(wrong) vs docker run ubuntu
(correct). Docker does not allow any uppercase characters as an image reference. Simple troubleshooting steps.
1) Dockerfile contains a capital letters as images.
FROM Ubuntu (wrong)
FROM ubuntu (correct)
2) Image name defined in the docker-compose.yml had uppercase letters
3) If you are using Jenkins or GoCD for deploying your docker container, please check the run command, whether the image name includes a capital letter.
Please read this document written specifically for this error.
The "coef" option of the geom_boxplot function allows to change the outlier cutoff in terms of interquartile ranges. This option is documented for the function stat_boxplot. To deactivate outliers (in other words they are treated as regular data), one can instead of using the default value of 1.5 specify a very high cutoff value:
library(ggplot2)
# generate data with outliers:
df = data.frame(x=1, y = c(-10, rnorm(100), 10))
# generate plot with increased cutoff for outliers:
ggplot(df, aes(x, y)) + geom_boxplot(coef=1e30)
Sometimes the easiest way to fix this issue is to make a new branch from the place where you know the code is good. Then you can leave the errant branch history alone in case you need to cherry-pick other commits from it later. This also ensures you did not lose any commit history.
From your local errant branch:
git log
copy the commit hash that you wanted the branch to be at and exit the git log
git checkout theHashYouJustCopied
git checkout -b your_new_awesome_branch
Now you have a new branch just the way you want it.
If you also needed to keep a specific commit from the errant branch that is not on your new branch, you can just cherry-pick that specific commit you need:
git checkout the_errant_branch
git log
Copy the commit hash of the one commit you need to pull into the good branch and exit the git log.
git checkout your_new_awesome_branch
git cherry-pick theHashYouJustCopied
Pat yourself on the back.
Those look much like Bonjour / mDNS requests to me. Those packets use multicast IP address 224.0.0.251 and port 5353.
The most likely source for this is Apple iTunes, which comes pre-installed on Mac computers (and is a popular install on Windows machines as well). Apple iTunes uses it to discover other iTunes-compatible devices in the same WiFi network.
mDNS is also used (primarily by Apple's Mac and iOS devices) to discover mDNS-compatible devices such as printers on the same network.
If this is a Linux box instead, it's probably the Avahi daemon then. Avahi is ZeroConf/Bonjour compatible and installed by default, but if you don't use DNS-SD or mDNS, it can be disabled.
It is probably worth adding that an insert iterator of any kind (std::back_insert_iterator
, std::front_insert_iterator
, std::insert_iterator
) is guaranteed to remain valid as long as all insertions are performed through this iterator and no other independent iterator-invalidating event occurs.
For example, when you are performing a series of insertion operations into a std::vector
by using std::insert_iterator
it is quite possible that these insertions will trigger vector reallocation, which will invalidate all iterators that "point" into that vector. However, the insert iterator in question is guaranteed to remain valid, i.e. you can safely continue the sequence of insertions. There's no need to worry about triggering vector reallocation at all.
This, again, applies only to insertions performed through the insert iterator itself. If iterator-invalidating event is triggered by some independent action on the container, then the insert iterator becomes invalidated as well in accordance with the general rules.
For example, this code
std::vector<int> v(10);
std::vector<int>::iterator it = v.begin() + 5;
std::insert_iterator<std::vector<int> > it_ins(v, it);
for (unsigned n = 20; n > 0; --n)
*it_ins++ = rand();
is guaranteed to perform a valid sequence of insertions into the vector, even if the vector "decides" to reallocate somewhere in the middle of this process. Iterator it
will obviously become invalid, but it_ins
will continue to remain valid.
I usually use
<?php echo get_current_user(); ?>
I will be glad if it helped you
It should work fine, are you wrapping the code in a $(document).ready()
call? If not use that or use live
i.e.
$('#fileupload1').live('change', function(){
alert("hola");
});
Here is a jsFiddle of this working against jQuery 1.4.4
Open tsconfig.json and disable strictDomEventTypes.
"angularCompilerOptions": {
....
........
"strictDomEventTypes": false
}
In reply to James Craig Burley's answer. In order to make a clean and re-usable design, one might choose for a more object oriented approach. This way methods can be safely bound to the types of the specified map. To me this approach feels cleaner and organized.
Example:
package main
import (
"fmt"
"sort"
)
type myIntMap map[int]string
func (m myIntMap) sort() (index []int) {
for k, _ := range m {
index = append(index, k)
}
sort.Ints(index)
return
}
func main() {
m := myIntMap{
1: "one",
11: "eleven",
3: "three",
}
for _, k := range m.sort() {
fmt.Println(m[k])
}
}
Extended playground example with multiple map types.
In all cases, the map and the sorted slice are decoupled from the moment the for
loop over the map range
is finished. Meaning that, if the map gets modified after the sorting logic, but before you use it, you can get into trouble. (Not thread / Go routine safe). If there is a change of parallel Map write access, you'll need to use a mutex around the writes and the sorted for
loop.
mutex.Lock()
for _, k := range m.sort() {
fmt.Println(m[k])
}
mutex.Unlock()
If you are using the tidyverse, you can use
as_data_frame(table(myvector))
to get a tibble (i.e. a data frame with some minor variations from the base class)
Add XAttribute
in the constructor of the XElement
, like
new XElement("Conn", new XAttribute("Server", comboBox1.Text));
You can also add multiple attributes or elements via the constructor
new XElement("Conn", new XAttribute("Server", comboBox1.Text), new XAttribute("Database", combobox2.Text));
or you can use the Add-Method of the XElement
to add attributes
XElement element = new XElement("Conn");
XAttribute attribute = new XAttribute("Server", comboBox1.Text);
element.Add(attribute);
The best approach for this sort of thing is probably git rebase
. It allows you to pull changes from master into your development branch, but leave all of your development work "on top of" (later in the commit log) the stuff from master. When your new work is complete, the merge back to master is then very straightforward.
Best explanation for X = aY + b
(in fact it f(x) = ax + b
)) is provided at https://math.stackexchange.com/a/906280/357701
A Simpler one by just adjusting lightness/luma/brightness for contrast as is below:
import cv2
img = cv2.imread('test.jpg')
cv2.imshow('test', img)
cv2.waitKey(1000)
imghsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
imghsv[:,:,2] = [[max(pixel - 25, 0) if pixel < 190 else min(pixel + 25, 255) for pixel in row] for row in imghsv[:,:,2]]
cv2.imshow('contrast', cv2.cvtColor(imghsv, cv2.COLOR_HSV2BGR))
cv2.waitKey(1000)
raw_input()
You are missing table NewScores
, so it can't be found. Just join this table.
If you really want to avoid joining it directly you can replace NewScores.NetScore
with SELECT NetScore FROM NewScores WHERE {conditions on which they should be matched}
Another strange thing. You wont see the libs folder in Android Studio, unless you have at least 1 file in the folder. So, I had to go to the libs folder using File Explorer, and then place the jar file there. Then, it showed up in Android Studio.
See also Git: discover which commits ever touched a range of lines.
Since Git 1.8.4, git log
has -L
to view the evolution of a range of lines.
For example, suppose you look at git blame
's output. Here -L 150,+11
means "only look at the lines 150 to 150+11":
$ git blame -L 150,+11 -- git-web--browse.sh
a180055a git-web--browse.sh (Giuseppe Bilotta 2010-12-03 17:47:36 +0100 150) die "The browser $browser is not
a180055a git-web--browse.sh (Giuseppe Bilotta 2010-12-03 17:47:36 +0100 151) fi
5d6491c7 git-browse-help.sh (Christian Couder 2007-12-02 06:07:55 +0100 152) fi
5d6491c7 git-browse-help.sh (Christian Couder 2007-12-02 06:07:55 +0100 153)
5d6491c7 git-browse-help.sh (Christian Couder 2007-12-02 06:07:55 +0100 154) case "$browser" in
81f42f11 git-web--browse.sh (Giuseppe Bilotta 2010-12-03 17:47:38 +0100 155) firefox|iceweasel|seamonkey|iceape)
5d6491c7 git-browse-help.sh (Christian Couder 2007-12-02 06:07:55 +0100 156) # Check version because firefox < 2.0 do
5d6491c7 git-browse-help.sh (Christian Couder 2007-12-02 06:07:55 +0100 157) vers=$(expr "$($browser_path -version)"
5d6491c7 git-browse-help.sh (Christian Couder 2007-12-02 06:07:55 +0100 158) NEWTAB='-new-tab'
5d6491c7 git-browse-help.sh (Christian Couder 2007-12-02 06:07:55 +0100 159) test "$vers" -lt 2 && NEWTAB=''
a0685a4f git-web--browse.sh (Dmitry Potapov 2008-02-09 23:22:22 -0800 160) "$browser_path" $NEWTAB "$@" &
And you want to know the history of what is now line 155.
Then, use git log
. Here, -L 155,155:git-web--browse.sh
means "trace the evolution of lines 155 to 155 in the file named git-web--browse.sh
".
$ git log --pretty=short -u -L 155,155:git-web--browse.sh
commit 81f42f11496b9117273939c98d270af273c8a463
Author: Giuseppe Bilotta <[email protected]>
web--browse: support opera, seamonkey and elinks
diff --git a/git-web--browse.sh b/git-web--browse.sh
--- a/git-web--browse.sh
+++ b/git-web--browse.sh
@@ -143,1 +143,1 @@
-firefox|iceweasel)
+firefox|iceweasel|seamonkey|iceape)
commit a180055a47c6793eaaba6289f623cff32644215b
Author: Giuseppe Bilotta <[email protected]>
web--browse: coding style
diff --git a/git-web--browse.sh b/git-web--browse.sh
--- a/git-web--browse.sh
+++ b/git-web--browse.sh
@@ -142,1 +142,1 @@
- firefox|iceweasel)
+firefox|iceweasel)
commit 5884f1fe96b33d9666a78e660042b1e3e5f9f4d9
Author: Christian Couder <[email protected]>
Rename 'git-help--browse.sh' to 'git-web--browse.sh'.
diff --git a/git-web--browse.sh b/git-web--browse.sh
--- /dev/null
+++ b/git-web--browse.sh
@@ -0,0 +127,1 @@
+ firefox|iceweasel)
I would use a decimal with the proper precision for your data.
Here is a super simple way of doing it
row2dict = lambda r: dict(r.items())
Try this:
MERGE INTO table1 t1
USING
(
-- For more complicated queries you can use WITH clause here
SELECT * FROM table2
)t2
ON(t1.id = t2.id)
WHEN MATCHED THEN UPDATE SET
t1.name = t2.name,
t1.desc = t2.desc;
Since the VisualStudio has been updated now (2019). You can try on this method:
From Laravel 5.6 you can use whereDate:
$users = Users::where('status_id', 'active')
->whereDate( 'created_at', '>', now()->subDays(30))
->get();
You also have whereMonth / whereDay / whereYear / whereTime
If you have a OneToOneField
then you should do it this way:
tmp = Foo.objects.get(pk=1)
tmp.pk = None
tmp.id = None
instance = tmp
I had the same requirements to create a kind of step progress tracker so I created a JavaScript plugin for that purpose. Here is the JsFiddle for the demo for this step progress tracker. You can access its code on GitHub as well.
What it basically does is, it takes the json data(in a particular format described below) as input and creates the progress tracker based on that. Highlighted steps indicates the completed steps.
It's html will somewhat look like shown below with default CSS but you can customize it as per the theme of your application. There is an option to show tool-tip text for each steps as well.
Here is some code snippet for that:
//container div
<div id="tracker1" style="width: 700px">
</div>
//sample JSON data
var sampleJson1 = {
ToolTipPosition: "bottom",
data: [{ order: 1, Text: "Foo", ToolTipText: "Step1-Foo", highlighted: true },
{ order: 2, Text: "Bar", ToolTipText: "Step2-Bar", highlighted: true },
{ order: 3, Text: "Baz", ToolTipText: "Step3-Baz", highlighted: false },
{ order: 4, Text: "Quux", ToolTipText: "Step4-Quux", highlighted: false }]
};
//Invoking the plugin
$(document).ready(function () {
$("#tracker1").progressTracker(sampleJson1);
});
Hopefully it will be useful for somebody else as well!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input type="radio" name="radiobutton" value="A" onclick = "populateData(event)">
<input type="radio" name="radiobutton" value="B" onclick = "populateData(event)">
<div id="content"></div>
</body>
</html>
-----------------JS- code------------
var targetDiv = document.getElementById('content');
var htmlContent = '';
function populateData(event){
switch(event.target.value){
case 'A':{
htmlContent = 'Content for A';
break;
}
case 'B':{
htmlContent = "content for B";
break;
}
}
targetDiv.innerHTML = htmlContent;
}
Step1: on click of the radio button it calls function populate data, with event (an object that has event details such as name of the element, value etc..);
Step2: I extracted the value through event.target.value and then simple switch will give me freedom to add custom text.
Live Code
Eclipse had a bug which reported more cycles than necessary. This has been fixed with the 2019-12 release. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=551105
If you're experiencing this in an enum, or when initializing an array with anonymous classes, it's a known bug in Eclipse. See Eclipse content assist not working in enum constant parameter list.
NomeN has answered correctly, but this answer wouldn't be of much use for beginners like me because we will have another problem to solve and we wouldn't know how to use RegEx in there. So I am adding a bit of explanation to this. The answer is
search:
(\w+\\.someMethod\\(\\))
replace:
((TypeName)$1)
Here:
In search:
First and last (
, )
depicts a group in regex
\w
depicts words (alphanumeric + underscore)
+
depicts one or more (ie one or more of alphanumeric + underscore)
.
is a special character which depicts any character (ie .+
means
one or more of any character). Because this is a special character
to depict a .
we should give an escape character with it, ie \.
someMethod
is given as it is to be searched.
The two parenthesis (
, )
are given along with escape character
because they are special character which are used to depict a group
(we will discuss about group in next point)
In replace:
It is given ((TypeName)$1)
, here $1
depicts the
group. That is all the characters that are enclosed within the first
and last parenthesis (
, )
in the search field
Also make sure you have checked the 'Regular expression' option in find an replace box
None of the other answers were "sticking" for me in RHEL 7, even setting JAVA_HOME
and PATH
directly in /etc/profile
or ~/.bash_profile
would not work. Each time I tried to check if JAVA_HOME
was set, it would come up blank:
$ echo $JAVA_HOME
(<-- no output)
What I had to do was set up a script in /etc/profile.d/jdk_home.sh
:
#!/bin/sh
export JAVA_HOME=/opt/ibm/java-x86_64-60/
export PATH=$JAVA_HOME/bin:$PATH
I initially neglected the first line (the #!/bin/sh
), and it won't work without it.
Now it's working:
$ echo $JAVA_HOME
/opt/ibm/java-x86_64-60/
There's also SSH Key - Still asking for password and passphrase
Using ssh-add ~/.ssh/id_rsa
without a local keychain.
This avoids having to mess with tokens.
An Easier solution would be the following:
var d = new Date();
var n = d.getMilliseconds();
Just reset any content manually when modal is hidden:
$(".modal").on("hidden.bs.modal", function(){
$(".modal-body1").html("");
});
There is more events. More about them here
$(document).ready(function() {_x000D_
$(".modal").on("hidden.bs.modal", function() {_x000D_
$(".modal-body1").html("Where did he go?!?!?!");_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>_x000D_
_x000D_
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">_x000D_
Launch modal_x000D_
</button>_x000D_
_x000D_
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">_x000D_
<div class="modal-dialog">_x000D_
<div class="modal-content">_x000D_
<div class="modal-header">_x000D_
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span>_x000D_
</button>_x000D_
<h4 class="modal-title" id="myModalLabel">Modal title</h4>_x000D_
</div>_x000D_
<div class="modal-body">_x000D_
<div class='modal-body1'>_x000D_
<h3>Close and open, I will be gone!</h3>_x000D_
</div>_x000D_
</div>_x000D_
<div class="modal-footer">_x000D_
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
one way, works also for negative values
declare @1 decimal(4,3)
select @1 = 2.938
select PARSENAME(@1,1)
It seems the answer to your question is no, however one hack you can use is to assign a dummy column to separate each new table. This works especially well if you're looping through a result set for a list of columns in a scripting language such as Python or PHP.
SELECT '' as table1_dummy, table1.*, '' as table2_dummy, table2.*, '' as table3_dummy, table3.* FROM table1
JOIN table2 ON table2.table1id = table1.id
JOIN table3 ON table3.table1id = table1.id
I realize this doesn't answer your question exactly, but if you're a coder this is a great way to separate tables with duplicate column names. Hope this helps somebody.
If the strings are the same length, then I would go for '%x' % ()
of the built-in xor (^
).
Examples -
>>>a = '290b6e3a'
>>>b = 'd6f491c5'
>>>'%x' % (int(a,16)^int(b,16))
'ffffffff'
>>>c = 'abcd'
>>>d = '12ef'
>>>'%x' % (int(a,16)^int(b,16))
'b922'
If the strings are not the same length, truncate the longer string to the length of the shorter using a slice longer = longer[:len(shorter)]
Try the following parameter:
-nc
,--no-clobber
: skip downloads that would download to existing files.
Sample usage:
wget -nc http://example.com/pic.png
There's a better solution if you don't really need the memory address but rather some means of uniquely identifying a managed object:
using System.Runtime.CompilerServices;
public static class Extensions
{
private static readonly ConditionalWeakTable<object, RefId> _ids = new ConditionalWeakTable<object, RefId>();
public static Guid GetRefId<T>(this T obj) where T: class
{
if (obj == null)
return default(Guid);
return _ids.GetOrCreateValue(obj).Id;
}
private class RefId
{
public Guid Id { get; } = Guid.NewGuid();
}
}
This is thread safe and uses weak references internally, so you won't have memory leaks.
You can use any key generation means that you like. I'm using Guid.NewGuid()
here because it's simple and thread safe.
I went ahead and created a Nuget package Overby.Extensions.Attachments that contains some extension methods for attaching objects to other objects. There's an extension called GetReferenceId()
that effectively does what the code in this answer shows.