Yes, you can!
$str = 'One';
$class = 'Class'.$str;
$object = new $class();
When using namespaces, supply the fully qualified name:
$class = '\Foo\Bar\MyClass';
$instance = new $class();
Other cool stuff you can do in php are:
Variable variables:
$personCount = 123;
$varname = 'personCount';
echo $$varname; // echo's 123
And variable functions & methods.
$func = 'my_function';
$func('param1'); // calls my_function('param1');
$method = 'doStuff';
$object = new MyClass();
$object->$method(); // calls the MyClass->doStuff() method.
Working on Mac I followed the answer of Sean Patrick Floyd placing a settings.xml like above in my user folder /Users/user/.m2/
But this did not help. So I opened a Terminal and did a ls -la on the folder. This was showing
-rw-r--r--@
thus staff and everone can at least read the file. So I wondered if the message isn't wrong and if the real cause is the lack of write permissions. I set the file to:
-rw-r--rw-@
This did it. The message disappeared.
Use JSON.stringify
:
> JSON.stringify({ asd: 'bla' });
'{"asd":"bla"}'
Thanks for the great example @Jacek Ciolek. For angular 1.3.x this solution breaks when updates are made to the reference input value. Building on this example for angular 1.3.x, this solution works just as well with Angular 1.3.x. It binds and watches for changes to the reference value.
angular.module('app', []).directive('sameAs', function() {
return {
restrict: 'A',
require: 'ngModel',
scope: {
sameAs: '='
},
link: function(scope, elm, attr, ngModel) {
if (!ngModel) return;
attr.$observe('ngModel', function(value) {
// observes changes to this ngModel
ngModel.$validate();
});
scope.$watch('sameAs', function(sameAs) {
// watches for changes from sameAs binding
ngModel.$validate();
});
ngModel.$validators.sameAs = function(value) {
return scope.sameAs == value;
};
}
};
});
Here is my pen: http://codepen.io/kvangrae/pen/BjxMWR
Use repr
>>> string = "abcd\n"
>>> print(repr(string))
'abcd\n'
Since this is the top result on Google:
If your connection works initially, but you begin seeing this error after many successful connections, it may be this issue.
In summary: if you open and close a connection, Windows reserves the TCP port for future use for some stupid reason. After doing this many times, it runs out of available ports.
The article gives a registry hack to fix the issue...
Here are my registry settings on XP/2003:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\MaxUserPort 0xFFFF (DWORD) HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\MaxUserPort\TcpTimedWaitDelay 60 (DWORD)
You need to create them. By default they don't exists.
On Vista/2008 you can use netsh to change it to something like:
netsh int ipv4 set dynamicport tcp start=10000 num=50000
...but the real solution is to use connection pooling, so that "opening" a connection really reuses an existing connection. Most frameworks do this automatically, but in my case the application was handling connections manually for some reason.
git shelve
doesn't exist in Git.
Only git stash
:
You had a 2008 old project git shelve to isolate modifications in a branch, but that wouldn't be very useful nowadays.
As documented in Intellij IDEA shelve dialog, the feature "shelving and unshelving" is not linked to a VCS (Version Control System tool) but to the IDE itself, to temporarily storing pending changes you have not committed yet in changelist.
Note that since Git 2.13 (Q2 2017), you now can stash individual files too.
Did you include
#!/usr/bin/python
as your first line?
Assuming you use LinearLayoutManager
in your RecyclerView, then you can pass true
as third argument in the LinearLayoutManager constructor.
For example:
mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, true));
If you are using the StaggeredGridLayoutManager
, then you can use the setReverseLayout
method it provides.
The formatter option '%x' % seems to work in assignment statements as well for me. (Assuming Python 3.0 and later)
Example
a = int('0x100', 16)
print(a) #256
print('%x' % a) #100
b = a
print(b) #256
c = '%x' % a
print(c) #100
<TextView
android:id="@+id/layone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Previous Page"
android:textColor="#000000"
android:textSize="16dp"
android:paddingLeft="10dp"
android:layout_marginTop="10dp"
android:visibility="gone" />
layone is a TextView.
You got your id wrong.
LinearLayout layone= (LinearLayout) view.findViewById(R.id.laytwo);// change id here
layone.setVisibility(View.VISIBLE);
should do the job.
or change like this to show the TextView:
TextView layone= (TextView) view.findViewById(R.id.layone);
layone.setVisibility(View.VISIBLE);
you can do
strings test.log | grep -i
this will convert give output as a readable string to grep.
I was wondering why I was getting that big warning message on Ubuntu 16.04 (which comes with Git 2.7.4), but not on Arch Linux. The reason is that the warning was removed in Git 2.8 (March 2016):
Across the transition at around Git version 2.0, the user used to get a pretty loud warning when running "git push" without setting push.default configuration variable. We no longer warn because the transition was completed a long time ago.
So you won't see the warning if you have Git 2.8 and later and don't need to set push.default
unless you want to change the default 'simple'
behavior.
You need to multi value check. Try using the following code :
<?php
$illstack=array(...............);
$val=array('uk','bn','in');
if(count(array_intersect($illstack,$val))===count($val)){ // all of $val is in $illstack}
?>
There's a bit of confusion in your question:
Date
datatype doesn't save the time zone component. This piece of information is truncated and lost forever when you insert a TIMESTAMP WITH TIME ZONE
into a Date
.TO_CHAR
function. In Oracle, a Date
has no format: it is a point in time.TO_TIMESTAMP_TZ
to convert a VARCHAR2
to a TIMESTAMP
, but this won't convert a Date
to a TIMESTAMP
.FROM_TZ
to add the time zone information to a TIMESTAMP
(or a Date
).CST
is a time zone but CDT
is not. CDT
is a daylight saving information.CST/CDT
(-05:00
) and CST/CST
(-06:00
) will have different values obviously, but the time zone CST
will inherit the daylight saving information depending upon the date by default.So your conversion may not be as simple as it looks.
Assuming that you want to convert a Date
d
that you know is valid at time zone CST/CST
to the equivalent at time zone CST/CDT
, you would use:
SQL> SELECT from_tz(d, '-06:00') initial_ts,
2 from_tz(d, '-06:00') at time zone ('-05:00') converted_ts
3 FROM (SELECT cast(to_date('2012-10-09 01:10:21',
4 'yyyy-mm-dd hh24:mi:ss') as timestamp) d
5 FROM dual);
INITIAL_TS CONVERTED_TS
------------------------------- -------------------------------
09/10/12 01:10:21,000000 -06:00 09/10/12 02:10:21,000000 -05:00
My default timestamp format has been used here. I can specify a format explicitely:
SQL> SELECT to_char(from_tz(d, '-06:00'),'yyyy-mm-dd hh24:mi:ss TZR') initial_ts,
2 to_char(from_tz(d, '-06:00') at time zone ('-05:00'),
3 'yyyy-mm-dd hh24:mi:ss TZR') converted_ts
4 FROM (SELECT cast(to_date('2012-10-09 01:10:21',
5 'yyyy-mm-dd hh24:mi:ss') as timestamp) d
6 FROM dual);
INITIAL_TS CONVERTED_TS
------------------------------- -------------------------------
2012-10-09 01:10:21 -06:00 2012-10-09 02:10:21 -05:00
I got it working using FileStream, get help from these
http://alperguc.blogspot.in/2008/11/c-generic-error-occurred-in-gdi.html
http://csharpdotnetfreak.blogspot.com/2010/02/resize-image-upload-ms-sql-database.html
System.Drawing.Image imageToBeResized = System.Drawing.Image.FromStream(fuImage.PostedFile.InputStream);
int imageHeight = imageToBeResized.Height;
int imageWidth = imageToBeResized.Width;
int maxHeight = 240;
int maxWidth = 320;
imageHeight = (imageHeight * maxWidth) / imageWidth;
imageWidth = maxWidth;
if (imageHeight > maxHeight)
{
imageWidth = (imageWidth * maxHeight) / imageHeight;
imageHeight = maxHeight;
}
Bitmap bitmap = new Bitmap(imageToBeResized, imageWidth, imageHeight);
System.IO.MemoryStream stream = new MemoryStream();
bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
stream.Position = 0;
byte[] image = new byte[stream.Length + 1];
stream.Read(image, 0, image.Length);
System.IO.FileStream fs
= new System.IO.FileStream(Server.MapPath("~/image/a.jpg"), System.IO.FileMode.Create
, System.IO.FileAccess.ReadWrite);
fs.Write(image, 0, image.Length);
instead of receiving the json string a model binding is better. For example:
[HttpPost]
public ActionResult AddUser(UserAddModel model)
{
if (ModelState.IsValid) {
return Json(new { Response = "Success" });
}
return Json(new { Response = "Error" });
}
<script>
function submitForm() {
$.ajax({
type: 'POST',
url: "@Url.Action("AddUser")",
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: $("form[name=UserAddForm]").serialize(),
success: function (data) {
console.log(data);
}
});
}
</script>
In the opening tag of your form, set an action attribute like so:
<form id="contactForm" action="#">
According to http://msdn.microsoft.com/en-us/library/cc288472(VS.85).aspx#html, IE8 will have "strong" HTML 5 support. I haven't seen anything discussing exactly what "strong support" entails, but I can say that yes, some HTML5 stuff is going to make it into IE8.
I tried to implement the result of Nick which is:
$('.selectorUsedToCreateTheDialog').dialog('option', 'title', 'My New title');
But that didn't work for me because i had multiple dialogs on 1 page. In such a situation it will only set the title correct the first time. Trying to staple commands did not work:
$("#modal_popup").html(data);
$("#modal_popup").dialog('option', 'title', 'My New Title');
$("#modal_popup").dialog({ width: 950, height: 550);
I fixed this by adding the title to the javascript function arguments of each dialog on the page:
function show_popup1() {
$("#modal_popup").html(data);
$("#modal_popup").dialog({ width: 950, height: 550, title: 'Popup Title of my First Dialog'});
}
function show_popup2() {
$("#modal_popup").html(data);
$("#modal_popup").dialog({ width: 950, height: 550, title: 'Popup Title of my Other Dialog'});
}
I assume you are loading the XML from an external file. With $.ajax()
, it's quite simple actually:
$.ajax({
url: 'xmlfile.xml',
dataType: 'xml',
success: function(data){
// Extract relevant data from XML
var xml_node = $('Pages',data);
console.log( xml_node.find('Page[Name="test"] > controls > test').text() );
},
error: function(data){
console.log('Error loading XML data');
}
});
Also, you should be consistent about the XML node naming. You have both lowercase and capitalized node names (<Page>
versus <page>
) which can be confusing when you try to use XML tree selectors.
To hide arrows and cross in a "time" input :
#inputId::-webkit-outer-spin-button,
#inputId::-webkit-inner-spin-button,
#inputId::-webkit-clear-button{
-webkit-appearance: none;
margin: 0;
}
<form name="frmChkForm" id="frmChkForm">
<input type="checkbox" name="chkcc9" id="chkAll">Check Me
<input type="checkbox" name="chk9[120]" class="chkGroup">
<input type="checkbox" name="chk9[140]" class="chkGroup">
<input type="checkbox" name="chk9[150]" class="chkGroup">
</form>
$("#chkAll").click(function() {
$(".chkGroup").attr("checked", this.checked);
});
With added functionality to ensure the check all checkbox gets checked/dechecked if all individual checkboxes are checked:
$(".chkGroup").click(function() {
$("#chkAll")[0].checked = $(".chkGroup:checked").length == $(".chkGroup").length;
});
Check on yourCheckBox.Value
?
Same issue on Windows 7 64bits. Run as administrator solved the problem.
in your code, just after 'do while' statement, add this line..
`Wscript.sleep 10000`
This will let your script sleep for 10 secs and let your system take rest. Else your processor will be running this script million times a second and this will definitely load your processor.
To kill it, just goto taskmanager and kill wscript.exe or if it is not found, you will find cscript.exe, kill it pressing delete button. These would be present in process tab of your taskmanager.
Once you add that line in code, I dont think you need to kill this process. It will not load your CPU.
Have a great day.
OSX User adjustments.
Following the steps of the Accepted answer worked for me with a small addition when configuring on OSX.
I put the cert.pem
file in a directory under my OSX logged in user and thus caused me to adjust the location for the trusted certificate.
Configure git to trust this certificate:
$ git config --global http.sslCAInfo $HOME/git-certs/cert.pem
I would use:
CONVERT(char(10),GETDATE(),126)
Not sure of the exact question but is this what you are looking for?
public class TestRun
{
public static void main(String [] args)
{
Map<String, Integer[]> prices = new HashMap<String, Integer[]>();
prices.put("milk", new Integer[] {1, 3, 2});
prices.put("eggs", new Integer[] {1, 1, 2});
}
}
Do not connect() and end() inside the function. This will cause problems on repeated calls to the function. Make the connection only
var connection = mysql.createConnection({
host: 'localhost',
user: 'node',
password: 'node',
database: 'node_project'
})
connection.connect(function(err) {
if (err) throw err
});
once and reuse that connection.
Inside the function
function insertData(name,id) {
connection.query('INSERT INTO members (name, id) VALUES (?, ?)', [name,id], function(err,result) {
if(err) throw err
});
}
If you are only looking to replace all occurrences of "< "
(with space) with "<"
(no space), then you can do an lapply
over the data frame, with a gsub
for replacement:
> data <- data.frame(lapply(data, function(x) {
+ gsub("< ", "<", x)
+ }))
> data
name var1 var2
1 a <2 <3
2 a <2 <3
3 a <2 <3
4 b <2 <3
5 b <2 <3
6 b <2 <3
7 c <2 <3
8 c <2 <3
9 c <2 <3
An adapted solution to modern JS of Travis' answer:
const getPageWidth = () => {
const bodyMax = document.body
? Math.max(document.body.scrollWidth, document.body.offsetWidth)
: 0;
const docElementMax = document.documentElement
? Math.max(
document.documentElement.scrollWidth,
document.documentElement.offsetWidth,
document.documentElement.clientWidth
)
: 0;
return Math.max(bodyMax, docElementMax);
};
def trunc(num, digits):
sp = str(num).split('.')
return '.'.join([sp[0], sp[1][:digits]])
This should work. It should give you the truncation you are looking for.
As mentioned already primitives can not be set to the Object type null.
What I do in such cases is just to use -1
or Long.MIN_VALUE
.
Simple as Pie. Just make sure you fetch array size before actually performing the loop.
for(int i = 0, arraySize= mySparseArray.size(); i < arraySize; i++) {
Object obj = mySparseArray.get(/* int key = */ mySparseArray.keyAt(i));
}
Hope this helps.
You can use basic regular expressions on strings to find all special characters or use pattern and matcher classes to search/modify/delete user defined strings. This link has some simple and easy to understand examples for regular expressions: http://www.vogella.de/articles/JavaRegularExpressions/article.html
Alternatively you can write the same like
{
test: /\.(svg|png|jpg|jpeg|gif)$/,
include: 'path of input image directory',
use: {
loader: 'file-loader',
options: {
name: '[path][name].[ext]',
outputPath: 'path of output image directory'
}
}
}
and then use simple import
import varName from 'relative path';
and in jsx write like
<img src={varName} ..../>
....
are for other image attributes
You can try export http_proxy=http://your_proxy:your_port
I looked and found a cross browser way:
function myFunction(){_x000D_
if(window.innerWidth !== undefined && window.innerHeight !== undefined) { _x000D_
var w = window.innerWidth;_x000D_
var h = window.innerHeight;_x000D_
} else { _x000D_
var w = document.documentElement.clientWidth;_x000D_
var h = document.documentElement.clientHeight;_x000D_
}_x000D_
var txt = "Page size: width=" + w + ", height=" + h;_x000D_
document.getElementById("demo").innerHTML = txt;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body onresize="myFunction()" onload="myFunction()">_x000D_
<p>_x000D_
Try to resize the page._x000D_
</p>_x000D_
<p id="demo">_x000D_
_x000D_
</p>_x000D_
</body>_x000D_
</html>
_x000D_
Although answers here are sufficient, I really think W3Schools example on this issue is very straightforward (it cleared up the confusion (for me) right away).
Use the
:hover
selector to change the style of a button when you move the mouse over it.Tip: Use the transition-duration property to determine the speed of the "hover" effect:
Example
.button { -webkit-transition-duration: 0.4s; /* Safari & Chrome */ transition-duration: 0.4s; } .button:hover { background-color: #4CAF50; /* Green */ color: white; }
In summary, for transitions where you want the "enter" and "exit" animations to be the same, you need to employ transitions on the main selector .button
rather than the hover selector .button:hover
. For transitions where you want the "enter" and "exit" animations to be different, you will need specify different main selector and hover selector transitions.
Solutions above are good but they require ~/.bash_profile. /usr/local/bin
is already in the $PATH and it can be confirmed by doing echo $PATH
. Download maven and run the following commands -
$ cd ~/Downloads
$ tar xvf apache-maven-3.5.3-bin.tar.gz
$ mv apache-maven-3.5.3 /usr/local/
$ cd /usr/local/bin
$ sudo ln -s ../apache-maven-3.5.3/bin/mvn mvn
$ mvn -version
$ which mvn
Note: The version of apache maven would be the one you will download.
I think this issue will help you. Standard deviation
By design it is to be done this way:
OutputStream out = ...;
try (Writer w = new OutputStreamWriter(out, "UTF-8")) {
w.write("Hello, World!");
} // or w.close(); //close will auto-flush
Problem solved.
Just drop down status bar, touch Choose input method, then change to another input method, type the password again. And everything is OK.
So weird...
Solution from a Chinese BBS. Thanks for the answer's author and all above who try to provide a solution, thanks!
With:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.7</version>
</plugin>
Was getting the following exception:
...
Caused by: org.apache.maven.plugin.MojoExecutionException: Mark invalid
at org.apache.maven.plugin.resources.ResourcesMojo.execute(ResourcesMojo.java:306)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:132)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
... 25 more
Caused by: org.apache.maven.shared.filtering.MavenFilteringException: Mark invalid
at org.apache.maven.shared.filtering.DefaultMavenFileFilter.copyFile(DefaultMavenFileFilter.java:129)
at org.apache.maven.shared.filtering.DefaultMavenResourcesFiltering.filterResources(DefaultMavenResourcesFiltering.java:264)
at org.apache.maven.plugin.resources.ResourcesMojo.execute(ResourcesMojo.java:300)
... 27 more
Caused by: java.io.IOException: Mark invalid
at java.io.BufferedReader.reset(BufferedReader.java:505)
at org.apache.maven.shared.filtering.MultiDelimiterInterpolatorFilterReaderLineEnding.read(MultiDelimiterInterpolatorFilterReaderLineEnding.java:416)
at org.apache.maven.shared.filtering.MultiDelimiterInterpolatorFilterReaderLineEnding.read(MultiDelimiterInterpolatorFilterReaderLineEnding.java:205)
at java.io.Reader.read(Reader.java:140)
at org.apache.maven.shared.utils.io.IOUtil.copy(IOUtil.java:181)
at org.apache.maven.shared.utils.io.IOUtil.copy(IOUtil.java:168)
at org.apache.maven.shared.utils.io.FileUtils.copyFile(FileUtils.java:1856)
at org.apache.maven.shared.utils.io.FileUtils.copyFile(FileUtils.java:1804)
at org.apache.maven.shared.filtering.DefaultMavenFileFilter.copyFile(DefaultMavenFileFilter.java:114)
... 29 more
Then it is gone after adding maven-filtering 1.3:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.7</version>
<dependencies>
<dependency>
<groupId>org.apache.maven.shared</groupId>
<artifactId>maven-filtering</artifactId>
<version>1.3</version>
</dependency>
</dependencies>
</plugin>
Well I have a few ideas, but I don't know if they are what your looking for.
You could use a service that holds all of the data and then just bind your activities to the service for data retrival.
Or package your data into a serializable or parcelable and attach them to a bundle and pass the bundle between activities.
This one may not be at all what your looking for, but you could also try using a SharedPreferences or a preference in general.
Either way let me know what you decide.
You can easily search for unused resources from Android Studio. Just press CtrlAltShifti and type "unused resources" (without quotes). That will execute lint. Super easy way to run lint commands (and other stuff from IDE).
OR
In Android Studio Menu > Refactor > Remove Unused Resources...
Select the resources you want to remove. You can exclude resources you want to keep by right-clicking on the resource item.
Use Do Refactor to remove all Resources at once.
Update: use ?OptionShifti for mac
It's depends on if your computer support WMI
. My computer can't run this WMI demo too.
But I successfully get the CPU temperature via Open Hardware Monitor. Add the Openhardwaremonitor reference in Visual Studio. It's easier. Try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenHardwareMonitor.Hardware;
namespace Get_CPU_Temp5
{
class Program
{
public class UpdateVisitor : IVisitor
{
public void VisitComputer(IComputer computer)
{
computer.Traverse(this);
}
public void VisitHardware(IHardware hardware)
{
hardware.Update();
foreach (IHardware subHardware in hardware.SubHardware) subHardware.Accept(this);
}
public void VisitSensor(ISensor sensor) { }
public void VisitParameter(IParameter parameter) { }
}
static void GetSystemInfo()
{
UpdateVisitor updateVisitor = new UpdateVisitor();
Computer computer = new Computer();
computer.Open();
computer.CPUEnabled = true;
computer.Accept(updateVisitor);
for (int i = 0; i < computer.Hardware.Length; i++)
{
if (computer.Hardware[i].HardwareType == HardwareType.CPU)
{
for (int j = 0; j < computer.Hardware[i].Sensors.Length; j++)
{
if (computer.Hardware[i].Sensors[j].SensorType == SensorType.Temperature)
Console.WriteLine(computer.Hardware[i].Sensors[j].Name + ":" + computer.Hardware[i].Sensors[j].Value.ToString() + "\r");
}
}
}
computer.Close();
}
static void Main(string[] args)
{
while (true)
{
GetSystemInfo();
}
}
}
}
You need to run this demo as administrator.
You can see the tutorial here: http://www.lattepanda.com/topic-f11t3004.html
I have combined both Berták and Stefano Munarini answer to creating a hybrid solution which handles both Rate this App and Show More App scenario.
/**
* This method checks if GooglePlay is installed or not on the device and accordingly handle
* Intents to view for rate App or Publisher's Profile
*
* @param showPublisherProfile pass true if you want to open Publisher Page else pass false to open APp page
* @param publisherID pass Dev ID if you have passed PublisherProfile true
*/
public void openPlayStore(boolean showPublisherProfile, String publisherID) {
//Error Handling
if (publisherID == null || !publisherID.isEmpty()) {
publisherID = "";
//Log and continue
Log.w("openPlayStore Method", "publisherID is invalid");
}
Intent openPlayStoreIntent;
boolean isGooglePlayInstalled = false;
if (showPublisherProfile) {
//Open Publishers Profile on PlayStore
openPlayStoreIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse("market://search?q=pub:" + publisherID));
} else {
//Open this App on PlayStore
openPlayStoreIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id=" + getPackageName()));
}
// find all applications who can handle openPlayStoreIntent
final List<ResolveInfo> otherApps = getPackageManager()
.queryIntentActivities(openPlayStoreIntent, 0);
for (ResolveInfo otherApp : otherApps) {
// look for Google Play application
if (otherApp.activityInfo.applicationInfo.packageName.equals("com.android.vending")) {
ActivityInfo otherAppActivity = otherApp.activityInfo;
ComponentName componentName = new ComponentName(
otherAppActivity.applicationInfo.packageName,
otherAppActivity.name
);
// make sure it does NOT open in the stack of your activity
openPlayStoreIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// task reparenting if needed
openPlayStoreIntent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
// if the Google Play was already open in a search result
// this make sure it still go to the app page you requested
openPlayStoreIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// this make sure only the Google Play app is allowed to
// intercept the intent
openPlayStoreIntent.setComponent(componentName);
startActivity(openPlayStoreIntent);
isGooglePlayInstalled = true;
break;
}
}
// if Google Play is not Installed on the device, open web browser
if (!isGooglePlayInstalled) {
Intent webIntent;
if (showPublisherProfile) {
//Open Publishers Profile on web browser
webIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/search?q=pub:" + getPackageName()));
} else {
//Open this App on web browser
webIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse("https://play.google.com/store/apps/details?id=" + getPackageName()));
}
startActivity(webIntent);
}
}
Usage
@OnClick(R.id.ll_more_apps) public void showMoreApps() { openPlayStore(true, "Hitesh Sahu"); }
@OnClick(R.id.ll_rate_this_app) public void openAppInPlayStore() { openPlayStore(false, ""); }
Thank very much, I find the answers in this website.
Here I refer to the production of a cmd file
by minimo
cd /D "%APPDATA%\Mozilla\Firefox\Profiles"
cd *.default
set ffile=%cd%
echo user_pref("network.proxy.http", "192.168.1.235 ");>>"%ffile%\prefs.js"
echo user_pref("network.proxy.http_port", 80);>>"%ffile%\prefs.js"
echo user_pref("network.proxy.type", 1);>>"%ffile%\prefs.js"
set ffile=
cd %windir%
Here is a general answer for untab :-
In Python IDLE :- Ctrl + [
In elipse :- Shitft + Tab
In Visual Studio :- Shift+ Tab
Guzzle implements PSR-7. That means that it will by default store the body of a message in a Stream that uses PHP temp streams. To retrieve all the data, you can use casting operator:
$contents = (string) $response->getBody();
You can also do it with
$contents = $response->getBody()->getContents();
The difference between the two approaches is that getContents
returns the remaining contents, so that a second call returns nothing unless you seek the position of the stream with rewind
or seek
.
$stream = $response->getBody();
$contents = $stream->getContents(); // returns all the contents
$contents = $stream->getContents(); // empty string
$stream->rewind(); // Seek to the beginning
$contents = $stream->getContents(); // returns all the contents
Instead, usings PHP's string casting operations, it will reads all the data from the stream from the beginning until the end is reached.
$contents = (string) $response->getBody(); // returns all the contents
$contents = (string) $response->getBody(); // returns all the contents
Documentation: http://docs.guzzlephp.org/en/latest/psr7.html#responses
Try putting it inside a form tag and closing the input tag:
<form>
<input type = "text" class = "txtPost" placeholder = "Post a question?" required />
<button class = "btnPost btnBlue">Post</button>
</form>
If you want to save data that is derived from a Javascript canvas.toDataURL()
function, you have to convert blanks into plusses. If you do not do that, the decoded data is corrupted:
<?php
$encodedData = str_replace(' ','+',$encodedData);
$decocedData = base64_decode($encodedData);
?>
you can render your recaptcha using following code
<div id="recapchaWidget" class="g-recaptcha"></div>
<script type="text/javascript">
var widId = "";
var onloadCallback = function ()
{
widId = grecaptcha.render('recapchaWidget', {
'sitekey':'Your Site Key'
});
};
</script>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
Then you can validate your recaptcha by using "IsRecapchaValid()" method as follows.
<script type="text/javascript">
function IsRecapchaValid()
{
var res = grecaptcha.getResponse(widId);
if (res == "" || res == undefined || res.length == 0)
{
return false;
}
return true;
}
</script>
You can pass plt.scatter
a c
argument which will allow you to select the colors. The code below defines a colors
dictionary to map your diamond colors to the plotting colors.
import matplotlib.pyplot as plt
import pandas as pd
carat = [5, 10, 20, 30, 5, 10, 20, 30, 5, 10, 20, 30]
price = [100, 100, 200, 200, 300, 300, 400, 400, 500, 500, 600, 600]
color =['D', 'D', 'D', 'E', 'E', 'E', 'F', 'F', 'F', 'G', 'G', 'G',]
df = pd.DataFrame(dict(carat=carat, price=price, color=color))
fig, ax = plt.subplots()
colors = {'D':'red', 'E':'blue', 'F':'green', 'G':'black'}
ax.scatter(df['carat'], df['price'], c=df['color'].apply(lambda x: colors[x]))
plt.show()
df['color'].apply(lambda x: colors[x])
effectively maps the colours from "diamond" to "plotting".
(Forgive me for not putting another example image up, I think 2 is enough :P)
seaborn
You can use seaborn
which is a wrapper around matplotlib
that makes it look prettier by default (rather opinion-based, I know :P) but also adds some plotting functions.
For this you could use seaborn.lmplot
with fit_reg=False
(which prevents it from automatically doing some regression).
The code below uses an example dataset. By selecting hue='color'
you tell seaborn to split your dataframe up based on your colours and then plot each one.
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
carat = [5, 10, 20, 30, 5, 10, 20, 30, 5, 10, 20, 30]
price = [100, 100, 200, 200, 300, 300, 400, 400, 500, 500, 600, 600]
color =['D', 'D', 'D', 'E', 'E', 'E', 'F', 'F', 'F', 'G', 'G', 'G',]
df = pd.DataFrame(dict(carat=carat, price=price, color=color))
sns.lmplot('carat', 'price', data=df, hue='color', fit_reg=False)
plt.show()
seaborn
using pandas.groupby
If you don't want to use seaborn then you can use pandas.groupby
to get the colors alone and then plot them using just matplotlib, but you'll have to manually assign colors as you go, I've added an example below:
fig, ax = plt.subplots()
colors = {'D':'red', 'E':'blue', 'F':'green', 'G':'black'}
grouped = df.groupby('color')
for key, group in grouped:
group.plot(ax=ax, kind='scatter', x='carat', y='price', label=key, color=colors[key])
plt.show()
This code assumes the same DataFrame as above and then groups it based on color
. It then iterates over these groups, plotting for each one. To select a color I've created a colors
dictionary which can map the diamond color (for instance D
) to a real color (for instance red
).
Try trimming the string to make sure there is no extra white space:
Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE TRIM(name) = '"+name.trim()+"'", null);
Also use c.moveToFirst()
like @thinksteep mentioned.
This is a complete code for select statements.
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT column1,column2,column3 FROM table ", null);
if (c.moveToFirst()){
do {
// Passing values
String column1 = c.getString(0);
String column2 = c.getString(1);
String column3 = c.getString(2);
// Do something Here with values
} while(c.moveToNext());
}
c.close();
db.close();
You can use the managed .Net cryptography library, then save the encrypted string into the database. When you want to verify the password you can compare the stored database string with the hashed value of the user input. See here for more info about SHA512Managed
using System.Security.Cryptography;
public static string EncryptSHA512Managed(string password)
{
UnicodeEncoding uEncode = new UnicodeEncoding();
byte[] bytPassword = uEncode.GetBytes(password);
SHA512Managed sha = new SHA512Managed();
byte[] hash = sha.ComputeHash(bytPassword);
return Convert.ToBase64String(hash);
}
For React.js, you can do this with more readable code. Hope it helps.
handleCheckboxChange(e) {
console.log('value of checkbox : ', e.target.checked);
}
render() {
return <input type="checkbox" onChange={this.handleCheckboxChange.bind(this)} />
}
<input type="text" autocomplete="off" />
replace() does not operate in-place, you need to assign its result to something. Also, for a more concise syntax, you could supplant your for loop with a one-liner: hello_no_spaces = map(lambda x: x.replace(' ', ''), hello)
I faced the same issue and got the same deprecation warning. I was using a numpy array of [23, 276] when I got the message. I tried reshaping it as per the warning and end up in nowhere. Then I select each row from the numpy array (as I was iterating over it anyway) and assigned it to a list variable. It worked then without any warning.
array = []
array.append(temp[0])
Then you can use the python list object (here 'array') as an input to sk-learn functions. Not the most efficient solution, but worked for me.
you can also use vbscript
Set objFS = CreateObject("Scripting.FileSystemObject")
strFolder = "c:\test"
strDestination = "c:\tmp\"
Set objFolder = objFS.GetFolder(strFolder)
Go(objFolder)
Sub Go(objDIR)
If objDIR <> "\System Volume Information" Then
For Each eFolder in objDIR.SubFolders
Go eFolder
Next
For Each strFile In objDIR.Files
strFileName = strFile.Name
strExtension = objFS.GetExtensionName(strFile)
If strExtension = "doc" Then
objFS.CopyFile strFile , strDestination & strFileName
End If
Next
End If
End Sub
save as mycopy.vbs and on command line
c:\test> cscript /nologo mycopy.vbs
If you want a method other than findcontrol try the following:
GridViewRow row = Gridview1.SelectedRow;
int CustomerId = int.parse(row.Cells[0].Text);// to get the column value
CheckBox checkbox1= row.Cells[0].Controls[0] as CheckBox; // you can access the controls like this
Try this:
LocalDate initial = LocalDate.of(2014, 2, 13);
LocalDate start = initial.withDayOfMonth(1);
LocalDate end = initial.withDayOfMonth(initial.getMonthOfYear().getLastDayOfMonth(false));
System.out.println(start);
System.out.println(end);
you can find the desire output but need to take care of parameter true/false for getLastDayOfMonth method
that parameter denotes leap year
To set the color of a font, you must first initialize the color by doing this:
Color maroon = new Color (128, 0, 0);
Once you've done that, you then put:
Font font = new Font ("Courier New", 1, 25); //Initializes the font
c.setColor (maroon); //Sets the color of the font
c.setFont (font); //Sets the font
c.drawString ("Your text here", locationX, locationY); //Outputs the string
Note: The 1 represents the type of font and this can be used to replace Font.PLAIN and the 25 represents the size of your font.
I had a similar issue and was able to resolve it by identifying which JDBC driver I intended to use. In my case, I was connecting to an Oracle database. I placed the following statement, prior to creating the connection variable.
DriverManager.registerDriver( new oracle.jdbc.driver.OracleDriver());
SQL> -- original . . .
SQL> select
2 to_char( sysdate, 'Day "the" Ddth "of" Month, yyyy' ) dt
3 from dual;
DT
----------------------------------------
Friday the 13th of May , 2016
SQL>
SQL> -- collapse repeated spaces . . .
SQL> select
2 regexp_replace(
3 to_char( sysdate, 'Day "the" Ddth "of" Month, yyyy' ),
4 ' * *', ' ') datesp
5 from dual;
DATESP
----------------------------------------
Friday the 13th of May , 2016
SQL>
SQL> -- and space before commma . . .
SQL> select
2 regexp_replace(
3 to_char( sysdate, 'Day "the" Ddth "of" Month, yyyy' ),
4 ' *(,*) *', '\1 ') datesp
5 from dual;
DATESP
----------------------------------------
Friday the 13th of May, 2016
SQL>
SQL> -- space before punctuation . . .
SQL> select
2 regexp_replace(
3 to_char( sysdate, 'Day "the" Ddth "of" Month, yyyy' ),
4 ' *([.,/:;]*) *', '\1 ') datesp
5 from dual;
DATESP
----------------------------------------
Friday the 13th of May, 2016
I had the same issue and solved it by closing the response at the end of the method:
try {
// make the request and get the entity
} catch(final Exception e) {
// handle the exception
} finally {
if(response != null) {
response.close();
}
}
If the method is the POST
method then:
app.post 'controller/action?parameter1=value1¶meter2=value2'
(Here parameters will be as per your applicability.)
Else if it is the GET
method then:
app.get 'controller/action'
I am talking here from a theoretical point of view; I have not tried BitLocker.
BitLocker uses AES encryption with a 128-bit key. On a Core2 machine, clocked at 2.53 GHz, encryption speed should be about 110 MB/s, using one core. The two cores could process about 220 MB/s, assuming perfect data transfer and core synchronization with no overhead, and that nothing requires the CPU in the same time (that one hell of an assumption, actually). The X25-M G2 is announced at 250 MB/s read bandwidth (that's what the specs say), so, in "ideal" conditions, BitLocker necessarily involves a bit of a slowdown.
However read bandwidth is not that important. It matters when you copy huge files, which is not something that you do very often. In everyday work, access time is much more important: as a developer, you create, write, read and delete many files, but they are all small (most of them are much smaller than one megabyte). This is what makes SSD "snappy". Encryption does not impact access time. So my guess is that any performance degradation will be negligible(*).
(*) Here I assume that Microsoft's developers did their job properly.
I set the below 3 styles to my img
tag
max-height: 500px;
height: 70%;
width: auto;
What it does that for desktop screen img doesn't grow beyond 500px
but for small mobile screens, it will shrink to 70% of the outer container. Works like a charm.
It also works width
property.
set /a countfiles-=%countfiles%
This will set countfiles to 0. I think you want to decrease it by 1, so use this instead:
set /a countfiles-=1
I'm not sure if the for loop will work, better try something like this:
:loop
cscript /nologo c:\deletefile.vbs %BACKUPDIR%
set /a countfiles-=1
if %countfiles% GTR 21 goto loop
I had this issue occurring with mailto:
and tel:
links inside an iframe (in Chrome, not a webview). Clicking the links would show the grey "page not found" page and inspecting the page showed it had a ERR_UNKNOWN_URL_SCHEME error.
Adding target="_blank"
, as suggested by this discussion of the issue fixed the problem for me.
var a= [1, 2, 3, '3'];
var b = [1, 2, 3];
var c = a.filter(function (i) { return ! ~b.indexOf(i); });
alert(c.length);
On Ubuntu (direct edit) :
$ sudo nano /etc/mysql.conf.d/mysqld.cnf
.gitattributes
- is a root-level file of your repository that defines the attributes for a subdirectory or subset of files.
You can specify the attribute to tell Git to use different merge strategies for a specific file. Here, we want to preserve the existing config.xml
for our branch.
We need to set the merge=foo
to config.xml
in .gitattributes
file.
merge=foo
tell git to use our(current branch) file, if a merge conflict occurs.
Add a .gitattributes
file at the root level of the repository
You can set up an attribute for confix.xml in the .gitattributes
file
<pattern> merge=foo
Let's take an example for config.xml
config.xml merge=foo
And then define a dummy foo
merge strategy with:
$ git config --global merge.foo.driver true
If you merge the stag
form dev
branch, instead of having the merge conflicts with the config.xml
file, the stag branch's config.xml preserves at whatever version you originally had.
for more reference: merge_strategies
This would definitely help Many!
private void axWindowsMediaPlayer1_ClickEvent(object sender, AxWMPLib._WMPOCXEvents_ClickEvent e)
{
if(e.nButton==2)
{
contextMenuStrip1.Show(MousePosition);
}
}
[ e.nbutton==2 ] is like [ e.button==MouseButtons.Right ]
try this:
//this method to check bluetooth is enable or not: true if enable, false is not enable
public static boolean isBluetoothEnabled()
{
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mBluetoothAdapter.isEnabled()) {
// Bluetooth is not enable :)
return false;
}
else{
return true;
}
}
//method to enable bluetooth
public static void enableBluetooth(){
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.enable();
}
}
//method to disable bluetooth
public static void disableBluetooth(){
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
}
}
Add these permissions in manifest
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
I think what you are trying to achieve can simply be done like this :
While you are compiling the coffeescript, use the "-b" parameter.
-b
/ --bare
Compile the JavaScript without the top-level function safety wrapper.
So something like this : coffee -b --compile somefile.coffee whatever.js
This will output your code just like in the CoffeeScript.org site.
I had the same problem and tried to change the version, sometimes is for the version of Android Studio in Project> Gradle Scripts> build.gradle(Module:app) you can change the version. For example:
android {
compileSdkVersion **23**
buildToolsVersion **"23.0.3"**
defaultConfig {
applicationId "com.example.android.myapplication"
minSdkVersion **19**
targetSdkVersion **23**
versionCode **1**
versionName **"1.0"**
}
I used this for a comment section:
.parent {_x000D_
display: flex;_x000D_
float: left;_x000D_
border-top:2px solid black;_x000D_
width:635px;_x000D_
margin:10px 0px 0px 0px;_x000D_
padding:0px 20px 0px 20px;_x000D_
background-color: rgba(255,255,255,0.5);_x000D_
}_x000D_
_x000D_
.child-left {_x000D_
align-items: stretch;_x000D_
float: left;_x000D_
width:135px;_x000D_
padding:10px 10px 10px 0px;_x000D_
height:inherit;_x000D_
border-right:2px solid black;_x000D_
}_x000D_
_x000D_
.child-right {_x000D_
align-items: stretch;_x000D_
float: left;_x000D_
width:468px;_x000D_
padding:10px;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child-left">Short</div>_x000D_
<div class="child-right">Tall<br>Tall</div>_x000D_
</div>
_x000D_
You could float the child-right to the right, but in this case I've calculated the widths of each div precisely.
Personally I use the first style only throw an exception or return from a method prematurely. Like argument Checking at the beginning of a function, because in these cases, rarely do I have have more than one thing to do, and there is never an else.
Example:
if (argument == null)
throw new ArgumentNullException("argument");
if (argument < 0)
return false;
Otherwise I use the second style.
Recommend to use LINQPad related nuget
package, then you can use exceptionInstance.Dump()
.
LINQPad.Runtime
LINQPad
Sample code:
using System;
using LINQPad;
namespace csharp_Dump_test
{
public class Program
{
public static void Main()
{
try
{
dosome();
}
catch (Exception ex)
{
ex.Dump();
}
}
private static void dosome()
{
throw new Exception("Unable.");
}
}
}
LinqPad nuget package is the most awesome tool for printing exception stack information. May it be helpful for you.
I would also highly recommend Adminer - http://www.adminer.org/
It is much faster than phpMyAdmin, does less funky iframe stuff, and supports both MySQL and PostgreSQL.
scan
can read from a web page automatically; you don't necessarily have to mess with connections.
I'm late to this party but I'll offer my approach for any passersby that might be interested in an alternative.
As noted in previous answers, the System.Net.Mail
SmtpClient
class does not support Implicit SSL. It does support Explicit SSL, which requires an insecure connection to the SMTP server over port 25 in order to negotiate the transport level security (TLS). I blogged about my travails with this subtlety here.
In short, SMTP over Implict SSL port 465 requires TLS to be negotiated before connecting to the SMTP server. Rather than write a .Net SMTPS implementation I turned to a utility named Stunnel. It's a small service that will let you redirect traffic on a local port to a remote port via SSL.
DISCLAIMER: Stunnel uses portions of the OpenSSL library, which recently had a high-profile exploit published in all major tech news media. I believe the latest version uses the patched OpenSSL but please use at your own risk.
Once the utility is installed a small addition to the configuration file:
; Example SSL client mode services
[my-smtps]
client = yes
accept = 127.0.0.1:465
connect = mymailserver.com:465
...instructs the Stunnel service to reroute local requests to port 465 to my mail server on port 465. This happens over TLS, which satisfies the SMTP server on the other end.
Using this utility, the following code will successfully transmit over port 465:
using System;
using System.Net;
using System.Net.Mail;
namespace RSS.SmtpTest
{
class Program
{
static void Main( string[] args )
{
try {
using( SmtpClient smtpClient = new SmtpClient( "localhost", 465 ) ) { // <-- note the use of localhost
NetworkCredential creds = new NetworkCredential( "username", "password" );
smtpClient.Credentials = creds;
MailMessage msg = new MailMessage( "[email protected]", "[email protected]", "Test", "This is a test" );
smtpClient.Send( msg );
}
}
catch( Exception ex ) {
Console.WriteLine( ex.Message );
}
}
}
}
So the advantage here is that you can use Implict SSL and port 465 as the security protocol while still using the send mail methods built into the framework. The disadvantage is that it requires the use of a third party service that may not be useful for anything but this specific function.
Michael.. if its just for formatting then you can format the cell to append any value.
Just right click and select Format Cell on the context menu, select custom and then specify type as you wish... for above example it would be X0. Here 'X' is the prefix and 0 is the numeric after.
Hope this helps..
Cheers...
You can use regular expressions in Javascript to do pattern matching of strings.
For example:
var s = "hello world!";
if (s.match(/hello.*/)) {
// do something
}
The match()
test is much like WHERE s LIKE 'hello%'
in SQL.
The easiest way to get the connection string is using the "Server Explorer" window in Visual Studio (menu View, Server Explorer) and connect to the server from that window.
Then you can see the connection string in the properties of the connected server (choose the connection and press F4 or Alt+Enter or choose Properties on the right click menu).
Advanced connection string settings: when creating the connection, you can modify any of the advanced connection string options, like MARS, resiliency, timeot, pooling configuration, etc. by clicking on the "Advanced..." button on the bottom of the "Add connection" dialog. You can access this dialog later by right clicking the Data Connection, and choosing "Modify connection...". The available advanced options vary by server type.
If you create the database using SQL Server Management Studio, the database will be created in a server instance, so that, to deploy your application you'll have to make a backup of the database and deploy it in the deployment SQL Server. Alternatively, you can use a data file using SQL Server Express (localDB in SQL Server 2012), that will be easily distributed with your app.
I.e. if it's an ASP.NET app, there's an App_Datafolder. If you right click it you can add a new element, which can be a SQL Server Database. This file will be on that folder, will work with SQL Express, and will be easy to deploy. You need SQL Express / localDB installed on your machine for this to work.
For a <input type='text'>
element:
input { font-size: 18px; }
or for a <textarea>
:
textarea { font-size: 18px; }
or for a <select>
:
select { font-size: 18px; }
you get the drift.
Here is the working example for Bootstrap 4.3
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>_x000D_
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">_x000D_
_x000D_
_x000D_
<div class="accordion" id="accordionExample">_x000D_
<div class="card">_x000D_
<div class="card-header" id="headingOne" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">_x000D_
<h2 class="mb-0">_x000D_
<button class="btn btn-link" type="button" >_x000D_
Collapsible Group Item #1_x000D_
</button>_x000D_
</h2>_x000D_
</div>_x000D_
_x000D_
<div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordionExample">_x000D_
<div class="card-body">_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="card">_x000D_
<div class="card-header" id="headingTwo" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">_x000D_
<h2 class="mb-0">_x000D_
<button class="btn btn-link collapsed" type="button" >_x000D_
Collapsible Group Item #2_x000D_
</button>_x000D_
</h2>_x000D_
</div>_x000D_
<div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionExample">_x000D_
<div class="card-body">_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="card">_x000D_
<div class="card-header" id="headingThree" data-toggle="collapse" data-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">_x000D_
<h2 class="mb-0">_x000D_
<button class="btn btn-link collapsed" type="button" >_x000D_
Collapsible Group Item #3_x000D_
</button>_x000D_
</h2>_x000D_
</div>_x000D_
<div id="collapseThree" class="collapse" aria-labelledby="headingThree" data-parent="#accordionExample">_x000D_
<div class="card-body">_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Instead of directly messing with innerHTML
it might be better to create a fragment and then insert that:
function create(htmlStr) {
var frag = document.createDocumentFragment(),
temp = document.createElement('div');
temp.innerHTML = htmlStr;
while (temp.firstChild) {
frag.appendChild(temp.firstChild);
}
return frag;
}
var fragment = create('<div>Hello!</div><p>...</p>');
// You can use native DOM methods to insert the fragment:
document.body.insertBefore(fragment, document.body.childNodes[0]);
Benefits:
Even though innerHTML
is used within the function, it's all happening outside of the DOM so it's much faster than you'd think...
Try this one if you want to create a virtual column "age" within a select statement:
select brand, name, "10" as age from cars...
I had the same problem, what helped we was turning of my anti virus protection for like 10 minutes while node installed and it worked like a charm.
None of this solutions worked for me. The way I fix the autofocus was:
<activity android:name=".android.InviteFriendsActivity" android:windowSoftInputMode="adjustPan">
<intent-filter >
</intent-filter>
</activity>
if 10000 <= number <= 30000:
pass
For details, see the docs.
Use its value directly:
In [79]: df[df.c > 0.5][['b', 'e']].values
Out[79]:
array([[ 0.98836259, 0.82403141],
[ 0.337358 , 0.02054435],
[ 0.29271728, 0.37813099],
[ 0.70033513, 0.69919695]])
Another background-image PRO: Background-images for <ul>
/<ol>
lists.
Use background images if they are part of the overall-design and are repeated on multiple pages. Preferably in background sprite form for optimization.
Use tags for all images that are not part of the overall design, and are most likely placed once, like specific images for articles, people, and important images that deserve to be added to google images.
** The only repeated image that I enclose in a <img>
tag is the site/company logo. Because people tend to click it to go to the homepage, thus you wrap it with an <a>
tag.
I also had this problem. I noticed that all of the subdirectories and files under /usr/local/lib/python2.7/dist-packages/ had no read or write permission for group and other, and they were owned by root. This means that only the root user could access them, and so any user that tried to run a Python script that used any of these modules got an import error:
$ python
Python 2.7.3 (default, Apr 10 2013, 06:20:15)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import selenium
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named selenium
>>>
I granted read permission on the files and search permission on the subdirectories for group and other like so:
$ sudo chmod -R go+rX /usr/local/lib/python2.7/dist-packages
And that resolved the problem for me:
$ python
Python 2.7.3 (default, Apr 10 2013, 06:20:15)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import selenium
>>>
I installed these packages with pip (run as root with sudo). I am not sure why it installed them without granting read/search permissions. This seems like a bug in pip to me, or possibly in the package configuration, but I am not very familiar with Python and its module packaging, so I don't know for sure. FWIW, all packages under dist-packages had this issue. Anyhow, hope that helps.
Regards.
Your error is happening because Object
is a module, not a class. So your inheritance is screwy.
Change your import statement to:
from Object import ClassName
and your class definition to:
class Visitor(ClassName):
or
change your class definition to:
class Visitor(Object.ClassName):
etc
Another way is using a ResourceBundle. Basically you get the bundle using its name without the '.properties'
private static final ResourceBundle resource = ResourceBundle.getBundle("config");
And you recover any value using this:
private final String prop = resource.getString("propName");
You are running your HTML from a different host than the host you are requesting. Because of this, you are getting blocked by the same origin policy.
One way around this is to use JSONP. This allows cross-site requests.
In JSON, you are returned:
{a: 5, b: 6}
In JSONP, the JSON is wrapped in a function call, so it becomes a script, and not an object.
callback({a: 5, b: 6})
You need to edit your REST service to accept a parameter called callback
, and then to use the value of that parameter as the function name. You should also change the content-type
to application/javascript
.
For example: http://localhost:8080/restws/json/product/get?callback=process
should output:
process({a: 5, b: 6})
In your JavaScript, you will need to tell jQuery to use JSONP. To do this, you need to append ?callback=?
to the URL.
$.getJSON("http://localhost:8080/restws/json/product/get?callback=?",
function(data) {
alert(data);
});
If you use $.ajax
, it will auto append the ?callback=?
if you tell it to use jsonp
.
$.ajax({
type: "GET",
dataType: "jsonp",
url: "http://localhost:8080/restws/json/product/get",
success: function(data){
alert(data);
}
});
Press ESC to first go into command mode
. Then Press Shift+D.
It's in the app.config file.
<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceDebug includeExceptionDetailInFaults="true"/>
Here is a nice way to remove the invalid characters in a Filename:
string.Join(string.Empty, filename.Split(System.IO.Path.GetInvalidFileNameChars()));
You can Try using :- git ls-files -s
Use %in%
as follows
A$C %in% B$C
Which will tell you which values of column C of A are in B.
What is returned is a logical vector. In the specific case of your example, you get:
A$C %in% B$C
# [1] TRUE FALSE TRUE TRUE
Which you can use as an index to the rows of A
or as an index to A$C
to get the actual values:
# as a row index
A[A$C %in% B$C, ] # note the comma to indicate we are indexing rows
# as an index to A$C
A$C[A$C %in% B$C]
[1] 1 3 4 # returns all values of A$C that are in B$C
We can negate it too:
A$C[!A$C %in% B$C]
[1] 2 # returns all values of A$C that are NOT in B$C
2 %in% B$C # "is the value 2 in B$C ?"
# FALSE
A$C[2] %in% B$C # "is the 2nd element of A$C in B$C ?"
# FALSE
you can use WMI in .net too but you're then dependent on the wmi service running etc. Sometimes it works locally, but then fail when the same code is run on servers. I believe that's a namespace issue, related to the "names" whose values you're reading.
Add the parameter declaration at the top of ps1 file
param(
# Our preferred encoding
[parameter(Mandatory=$false)]
[ValidateSet("UTF8","Unicode","UTF7","ASCII","UTF32","BigEndianUnicode")]
[string]$Encoding = "UTF8"
)
write ("Encoding : {0}" -f $Encoding)
C:\temp> .\test.ps1 -Encoding ASCII
Encoding : ASCII
crontab
does not work for me on CentOS x86 6.5. @reboot seems to be not working.
Finally I got this solution:
Edit: /etc/rc.local
sudo vi /etc/rc.local
Add this line to the end of the file. Change USER_NAME
and PATH_TO_PROJECT
to your own. NODE_ENV=production
means the app runs in production mode. You can add more lines if you need to run more than one node.js app.
su - USER_NAME -c "NODE_ENV=production /usr/local/bin/forever start /PATH_TO_PROJECT/app.js"
Don't set NODE_ENV
in a separate line, your app will still run in development mode, because forever does not get NODE_ENV
.
# WRONG!
su - USER_NAME -c "export NODE_ENV=production"
Save and quit vi (press ESC : w q return
). You can try rebooting your server. After your server reboots, your node.js app should run automatically, even if you don't log into any account remotely via ssh.
You'd better set NODE_ENV
environment in your shell. NODE_ENV
will be set automatically when your account USER_NAME
logs in.
echo export NODE_ENV=production >> ~/.bash_profile
So you can run commands like forever stop/start /PATH_TO_PROJECT/app.js
via ssh without setting NODE_ENV
again.
What worked for me (in ubuntu):
sudo su
cd /etc/apache2/mods-enabled
ln ../mods-available/rewrite.load rewrite.load
Also, as already mentioned, make sure AllowOverride all
is set in the relevant section of /etc/apache2/sites-available/default
We use a combination of the processor id number (ProcessorID
) from Win32_processor
and the universally unique identifier (UUID
) from Win32_ComputerSystemProduct
:
ManagementObjectCollection mbsList = null;
ManagementObjectSearcher mos = new ManagementObjectSearcher("Select ProcessorID From Win32_processor");
mbsList = mos.Get();
string processorId = string.Empty;
foreach (ManagementBaseObject mo in mbsList)
{
processorId = mo["ProcessorID"] as string;
}
mos = new ManagementObjectSearcher("SELECT UUID FROM Win32_ComputerSystemProduct");
mbsList = mos.Get();
string systemId = string.Empty;
foreach (ManagementBaseObject mo in mbsList)
{
systemId = mo["UUID"] as string;
}
var compIdStr = $"{processorId}{systemId}";
Previously, we used a combination: processor ID ("Select ProcessorID From Win32_processor"
) and the motherboard serial number ("SELECT SerialNumber FROM Win32_BaseBoard"
), but then we found out that the serial number of the motherboard may not be filled in, or it may be filled in with uniform values:
Therefore, it is worth considering this situation.
Also keep in mind that the ProcessorID
number may be the same on different computers.
Inspired by @Luisa's answer, I made a function, axes0
x = linspace(-2,2,101);
plot(x,2*x.^3-3*x+1);
axes0
You can follow the link above to download the function and get more details on usage
Try this
for(int i = 0; i != 5; ++i, ++j)
do_something(i,j);
VLC should be able to do this.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Cnt extends CI_Controller {
public function insert_view()
{
$this->load->view('insert');
}
public function insert_data(){
$name=$this->input->post('emp_name');
$salary=$this->input->post('emp_salary');
$arr=array(
'emp_name'=>$name,
'emp_salary'=>$salary
);
$resp=$this->Model->insert_data('emp1',$arr);
echo "<script>alert('$resp')</script>";
$this->insert_view();
}
}
for more detail visit: http://wheretodownloadcodeigniter.blogspot.com/2018/04/insert-using-codeigniter.html
The threading.Timer
object (documentation) can count the ten seconds, then get it to set an Event flag indicating that the loop should exit.
The documentation indicates that the timing might not be exact - you'd have to test whether it's accurate enough for your game.
The short form(a += 1
) has the option to modify a
in-place , instead of creating a new object representing the sum and rebinding it back to the same name(a = a + 1
).So,The short form(a += 1
) is much efficient as it doesn't necessarily need to make a copy of a
unlike a = a + 1
.
Also even if they are outputting the same result, notice they are different because they are separate operators: +
and +=
you have to update your node.js and angular/cli.If you update these two things then your project has angular.json file instead of angular-cli.json file.Then add css file into angular.json file.If you add css file into angular-cli.json file instead of angular.json file,then errors are occured.
Per the docs, replace
returns the new string - it does not modify the string you pass it.
var tt="88,9827";
tt = tt.replace(/,/g, '.');
^^^^
alert(tt);
If you would just like to know how much memory is being used in your JVM, and how much is free, you could try something like this:
// Get current size of heap in bytes
long heapSize = Runtime.getRuntime().totalMemory();
// Get maximum size of heap in bytes. The heap cannot grow beyond this size.
// Any attempt will result in an OutOfMemoryException.
long heapMaxSize = Runtime.getRuntime().maxMemory();
// Get amount of free memory within the heap in bytes. This size will increase
// after garbage collection and decrease as new objects are created.
long heapFreeSize = Runtime.getRuntime().freeMemory();
edit: I thought this might be helpful as the question author also stated he would like to have logic that handles "read as many rows as possible until I've used 32MB of memory."
The most important difference is that gzip is only capable to compress a single file while zip compresses multiple files one by one and archives them into one single file afterwards. Thus, gzip comes along with tar most of the time (there are other possibilities, though). This comes along with some (dis)advantages.
If you have a big archive and you only need one single file out of it, you have to decompress the whole gzip file to get to that file. This is not required if you have a zip file.
On the other hand, if you compress 10 similiar or even identical files, the zip archive will be much bigger because each file is compressed individually, whereas in gzip in combination with tar a single file is compressed which is much more effective if the files are similiar (equal).
The question in the link you gave talks about naming of JavaScript variables, not about file naming, so forget about that for the context in which you ask your question.
As to file naming, it is purely a matter of preference and taste. I prefer naming files with hyphens because then I don't have to reach for the shift key, as I do when dealing with camelCase file names; and because I don't have to worry about differences between Windows and Linux file names (Windows file names are case-insensitive, at least through XP).
So the answer, like so many, is "it depends" or "it's up to you."
The one rule you should follow is to be consistent in the convention you choose.
Alternative way for Python 2, without using basestring:
isinstance(s, (str, unicode))
But still won't work in Python 3 since unicode
isn't defined (in Python 3).
And also if the input box/button has to remain disable, then simply
<button disabled>
or <input disabled>
works.
Using java.time
framework built into Java 8 and later.
The DayOfWeek
enum can generate a String of the day’s name automatically localized to the human language and cultural norms of a Locale
. Specify a TextStyle
to indicate you want long form or abbreviated name.
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.time.format.TextStyle
import java.util.Locale
import java.time.DayOfWeek;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/M/yyyy");
LocalDate date = LocalDate.parse("23/2/2010", formatter); // LocalDate = 2010-02-23
DayOfWeek dow = date.getDayOfWeek(); // Extracts a `DayOfWeek` enum object.
String output = dow.getDisplayName(TextStyle.SHORT, Locale.US); // String = Tue
SSL development libraries have to be installed
CentOS:
$ yum install openssl-devel libffi-devel
Ubuntu:
$ apt-get install libssl-dev libffi-dev
OS X (with Homebrew installed):
$ brew install openssl
You can use functools.partial
for this (as you suspected):
from functools import partial
def target(lock, iterable_item):
for item in iterable_item:
# Do cool stuff
if (... some condition here ...):
lock.acquire()
# Write to stdout or logfile, etc.
lock.release()
def main():
iterable = [1, 2, 3, 4, 5]
pool = multiprocessing.Pool()
l = multiprocessing.Lock()
func = partial(target, l)
pool.map(func, iterable)
pool.close()
pool.join()
Example:
def f(a, b, c):
print("{} {} {}".format(a, b, c))
def main():
iterable = [1, 2, 3, 4, 5]
pool = multiprocessing.Pool()
a = "hi"
b = "there"
func = partial(f, a, b)
pool.map(func, iterable)
pool.close()
pool.join()
if __name__ == "__main__":
main()
Output:
hi there 1
hi there 2
hi there 3
hi there 4
hi there 5
I have the same issue as you did. I think the problem is that you used relative import in in-package import
. There is no __init__.py
in your directory. So just import as Moses answered above.
The core issue I think is when you import with a dot:
from .p_02_paying_debt_off_in_a_year import compute_balance_after
It is equivalent to:
from __main__.p_02_paying_debt_off_in_a_year import compute_balance_after
where __main__
refers to your current module p_03_using_bisection_search.py
.
Briefly, the interpreter does not know your directory architecture.
When the interpreter get in p_03.py
, the script equals:
from p_03_using_bisection_search.p_02_paying_debt_off_in_a_year import compute_balance_after
and p_03_using_bisection_search
does not contain any modules or instances called p_02_paying_debt_off_in_a_year
.
So I came up with a cleaner solution without changing python environment valuables (after looking up how requests do in relative import):
The main architecture of the directory is:
main.py
setup.py
problem_set_02/
__init__.py
p01.py
p02.py
p03.py
Then write in __init__.py
:
from .p_02_paying_debt_off_in_a_year import compute_balance_after
Here __main__
is __init__
, it exactly refers to the module problem_set_02
.
Then go to main.py
:
import problem_set_02
You can also write a setup.py
to add specific module to the environment.
var str = 'asd-0.testing';
var regex = /(asd-)\d(\.\w+)/;
str = str.replace(regex, "$11$2");
console.log(str);
Or if you're sure there won't be any other digits in the string:
var str = 'asd-0.testing';
var regex = /\d/;
str = str.replace(regex, "1");
console.log(str);
In Laravel 5.1, I used: File: app\Providers\AppServiceProvider.php
public function boot()
{
if ($this->isSecure()) {
\URL::forceSchema('https');
}
}
public function isSecure()
{
$isSecure = false;
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
$isSecure = true;
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') {
$isSecure = true;
}
return $isSecure;
}
NOTE: use forceSchema
, NOT forceScheme
Just use:
<?php
include("/path/to/file.html");
?>
That will echo it as well. This also has the benefit of executing any PHP in the file.
If you need to do anything with the contents, use file_get_contents(),
For example,
<?php
$pagecontents = file_get_contents("/path/to/file.html");
echo str_replace("Banana", "Pineapple", $pagecontents);
?>
This doesn't execute code in that file, so be careful if you expect that to work.
I usually use:
include($_SERVER['DOCUMENT_ROOT']."/path/to/file/as/in/url.html");
as then I can move files without breaking the includes.
Another way to do it could be by creating an alias. For example in terminal write:
alias printhello='python /home/hello_world.py'
Writing printhello
will run hello_world.py, but this is only temporary.
To make aliases permanent, you have to add them to bashrc, you can edit it by writing this in the terminal:
gedit ~/.bashrc
Mitch is right. It depends on resources (memory).
Although Raymond's article is dedicated to Windows threads, not to C# threads, the logic applies the same (C# threads are mapped to Windows threads).
However, as we are in C#, if we want to be completely precise, we need to distinguish between "started" and "non started" threads. Only started threads actually reserve stack space (as we could expect). Non started threads only allocate the information required by a thread object (you can use reflector if interested in the actual members).
You can actually test it for yourself, compare:
static void DummyCall()
{
Thread.Sleep(1000000000);
}
static void Main(string[] args)
{
int count = 0;
var threadList = new List<Thread>();
try
{
while (true)
{
Thread newThread = new Thread(new ThreadStart(DummyCall), 1024);
newThread.Start();
threadList.Add(newThread);
count++;
}
}
catch (Exception ex)
{
}
}
with:
static void DummyCall()
{
Thread.Sleep(1000000000);
}
static void Main(string[] args)
{
int count = 0;
var threadList = new List<Thread>();
try
{
while (true)
{
Thread newThread = new Thread(new ThreadStart(DummyCall), 1024);
threadList.Add(newThread);
count++;
}
}
catch (Exception ex)
{
}
}
Put a breakpoint in the exception (out of memory, of course) in VS to see the value of counter. There is a very significant difference, of course.
You should use a callback parameter:
function Typer(callback)
{
var srcText = 'EXAMPLE ';
var i = 0;
var result = srcText[i];
var interval = setInterval(function() {
if(i == srcText.length - 1) {
clearInterval(interval);
callback();
return;
}
i++;
result += srcText[i].replace("\n", "<br />");
$("#message").html(result);
},
100);
return true;
}
function playBGM () {
alert("Play BGM function");
$('#bgm').get(0).play();
}
Typer(function () {
playBGM();
});
// or one-liner: Typer(playBGM);
So, you pass a function as parameter (callback
) that will be called in that if
before return
.
Also, this is a good article about callbacks.
function Typer(callback)_x000D_
{_x000D_
var srcText = 'EXAMPLE ';_x000D_
var i = 0;_x000D_
var result = srcText[i];_x000D_
var interval = setInterval(function() {_x000D_
if(i == srcText.length - 1) {_x000D_
clearInterval(interval);_x000D_
callback();_x000D_
return;_x000D_
}_x000D_
i++;_x000D_
result += srcText[i].replace("\n", "<br />");_x000D_
$("#message").html(result);_x000D_
},_x000D_
100);_x000D_
return true;_x000D_
_x000D_
_x000D_
}_x000D_
_x000D_
function playBGM () {_x000D_
alert("Play BGM function");_x000D_
$('#bgm').get(0).play();_x000D_
}_x000D_
_x000D_
Typer(function () {_x000D_
playBGM();_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>_x000D_
<div id="message">_x000D_
</div>_x000D_
<audio id="bgm" src="http://www.freesfx.co.uk/rx2/mp3s/9/10780_1381246351.mp3">_x000D_
</audio>
_x000D_
The CSS :active
state means the active state of the clicked link - the moment when you clicked on it, but not released the mouse button yet, for example. It doesn't know which page you're on and can't apply any styles to the menu items.
To fix your problem you have to create a class and add it manually to the current page's menu:
a.active { color: #f00 }
<ul>
<li><a href="index.php" class="active">HOME</a></li>
<li><a href="two.php">PORTFOLIO</a></li>
<li><a href="three.php">ABOUT</a></li>
<li><a href="four.php">CONTACT</a></li>
<li><a href="five.php">SHOP</a></li>
</ul>
Not trying to be smart about it, but if you use Sublime Text for your editor, the steps are:
I'd imagine that other editors have similar functionality too. Which one are you using? I'd be happy to do some digging.
Steps to install Spark in local mode:
Install Java 7 or later.
To test java installation is complete, open command prompt type java
and hit enter.
If you receive a message 'Java' is not recognized as an internal or external command.
You need to configure your environment variables, JAVA_HOME
and PATH
to point to the path of jdk.
Set SCALA_HOME
in Control Panel\System and Security\System
goto "Adv System settings" and add %SCALA_HOME%\bin
in PATH variable in environment variables.
Install Python 2.6 or later from Python Download link.
Download SBT. Install it and set SBT_HOME
as an environment variable with value as <<SBT PATH>>
.
Download winutils.exe
from HortonWorks repo or git repo. Since we don't have a local Hadoop installation on Windows we have to download winutils.exe
and place it in a bin
directory under a created Hadoop
home directory.
Set HADOOP_HOME = <<Hadoop home directory>>
in environment variable.
We will be using a pre-built Spark package, so choose a Spark pre-built package for Hadoop Spark download. Download and extract it.
Set SPARK_HOME
and add %SPARK_HOME%\bin
in PATH variable in environment variables.
Run command: spark-shell
Open http://localhost:4040/
in a browser to see the SparkContext web UI.
To use DHCP, you'd have to run a DHCP server on the primary and a client on the secondary; the primary could then query the server to find out what address it handed out. Probably overkill.
I can't help you with Windows directly. On Unix, the "arp" command will tell you what IP addresses are known to be attached to the local ethernet segment. Windows will have this same information (since it's a core part of the IP/Ethernet interface) but I don't know how you get at it.
Of course, the networking stack will only know about the other host if it has previously seen traffic from it. You may have to first send a broadcast packet on the interface to elicit some sort of response and thus populate the local ARP table.
Based on the previous answers and personnal experience, here is the code I use to monitor CPU use. The code of this class is written in pure Java.
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* Utilities available only on Linux Operating System.
*
* <p>
* A typical use is to assign a thread to CPU monitoring:
* </p>
*
* <pre>
* @Override
* public void run() {
* while (CpuUtil.monitorCpu) {
*
* LinuxUtils linuxUtils = new LinuxUtils();
*
* int pid = android.os.Process.myPid();
* String cpuStat1 = linuxUtils.readSystemStat();
* String pidStat1 = linuxUtils.readProcessStat(pid);
*
* try {
* Thread.sleep(CPU_WINDOW);
* } catch (Exception e) {
* }
*
* String cpuStat2 = linuxUtils.readSystemStat();
* String pidStat2 = linuxUtils.readProcessStat(pid);
*
* float cpu = linuxUtils.getSystemCpuUsage(cpuStat1, cpuStat2);
* if (cpu >= 0.0f) {
* _printLine(mOutput, "total", Float.toString(cpu));
* }
*
* String[] toks = cpuStat1.split(" ");
* long cpu1 = linuxUtils.getSystemUptime(toks);
*
* toks = cpuStat2.split(" ");
* long cpu2 = linuxUtils.getSystemUptime(toks);
*
* cpu = linuxUtils.getProcessCpuUsage(pidStat1, pidStat2, cpu2 - cpu1);
* if (cpu >= 0.0f) {
* _printLine(mOutput, "" + pid, Float.toString(cpu));
* }
*
* try {
* synchronized (this) {
* wait(CPU_REFRESH_RATE);
* }
* } catch (InterruptedException e) {
* e.printStackTrace();
* return;
* }
* }
*
* Log.i("THREAD CPU", "Finishing");
* }
* </pre>
*/
public final class LinuxUtils {
// Warning: there appears to be an issue with the column index with android linux:
// it was observed that on most present devices there are actually
// two spaces between the 'cpu' of the first column and the value of
// the next column with data. The thing is the index of the idle
// column should have been 4 and the first column with data should have index 1.
// The indexes defined below are coping with the double space situation.
// If your file contains only one space then use index 1 and 4 instead of 2 and 5.
// A better way to deal with this problem may be to use a split method
// not preserving blanks or compute an offset and add it to the indexes 1 and 4.
private static final int FIRST_SYS_CPU_COLUMN_INDEX = 2;
private static final int IDLE_SYS_CPU_COLUMN_INDEX = 5;
/** Return the first line of /proc/stat or null if failed. */
public String readSystemStat() {
RandomAccessFile reader = null;
String load = null;
try {
reader = new RandomAccessFile("/proc/stat", "r");
load = reader.readLine();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
Streams.close(reader);
}
return load;
}
/**
* Compute and return the total CPU usage, in percent.
*
* @param start
* first content of /proc/stat. Not null.
* @param end
* second content of /proc/stat. Not null.
* @return 12.7 for a CPU usage of 12.7% or -1 if the value is not
* available.
* @see {@link #readSystemStat()}
*/
public float getSystemCpuUsage(String start, String end) {
String[] stat = start.split("\\s");
long idle1 = getSystemIdleTime(stat);
long up1 = getSystemUptime(stat);
stat = end.split("\\s");
long idle2 = getSystemIdleTime(stat);
long up2 = getSystemUptime(stat);
// don't know how it is possible but we should care about zero and
// negative values.
float cpu = -1f;
if (idle1 >= 0 && up1 >= 0 && idle2 >= 0 && up2 >= 0) {
if ((up2 + idle2) > (up1 + idle1) && up2 >= up1) {
cpu = (up2 - up1) / (float) ((up2 + idle2) - (up1 + idle1));
cpu *= 100.0f;
}
}
return cpu;
}
/**
* Return the sum of uptimes read from /proc/stat.
*
* @param stat
* see {@link #readSystemStat()}
*/
public long getSystemUptime(String[] stat) {
/*
* (from man/5/proc) /proc/stat kernel/system statistics. Varies with
* architecture. Common entries include: cpu 3357 0 4313 1362393
*
* The amount of time, measured in units of USER_HZ (1/100ths of a
* second on most architectures, use sysconf(_SC_CLK_TCK) to obtain the
* right value), that the system spent in user mode, user mode with low
* priority (nice), system mode, and the idle task, respectively. The
* last value should be USER_HZ times the second entry in the uptime
* pseudo-file.
*
* In Linux 2.6 this line includes three additional columns: iowait -
* time waiting for I/O to complete (since 2.5.41); irq - time servicing
* interrupts (since 2.6.0-test4); softirq - time servicing softirqs
* (since 2.6.0-test4).
*
* Since Linux 2.6.11, there is an eighth column, steal - stolen time,
* which is the time spent in other operating systems when running in a
* virtualized environment
*
* Since Linux 2.6.24, there is a ninth column, guest, which is the time
* spent running a virtual CPU for guest operating systems under the
* control of the Linux kernel.
*/
// with the following algorithm, we should cope with all versions and
// probably new ones.
long l = 0L;
for (int i = FIRST_SYS_CPU_COLUMN_INDEX; i < stat.length; i++) {
if (i != IDLE_SYS_CPU_COLUMN_INDEX ) { // bypass any idle mode. There is currently only one.
try {
l += Long.parseLong(stat[i]);
} catch (NumberFormatException ex) {
ex.printStackTrace();
return -1L;
}
}
}
return l;
}
/**
* Return the sum of idle times read from /proc/stat.
*
* @param stat
* see {@link #readSystemStat()}
*/
public long getSystemIdleTime(String[] stat) {
try {
return Long.parseLong(stat[IDLE_SYS_CPU_COLUMN_INDEX]);
} catch (NumberFormatException ex) {
ex.printStackTrace();
}
return -1L;
}
/** Return the first line of /proc/pid/stat or null if failed. */
public String readProcessStat(int pid) {
RandomAccessFile reader = null;
String line = null;
try {
reader = new RandomAccessFile("/proc/" + pid + "/stat", "r");
line = reader.readLine();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
Streams.close(reader);
}
return line;
}
/**
* Compute and return the CPU usage for a process, in percent.
*
* <p>
* The parameters {@code totalCpuTime} is to be the one for the same period
* of time delimited by {@code statStart} and {@code statEnd}.
* </p>
*
* @param start
* first content of /proc/pid/stat. Not null.
* @param end
* second content of /proc/pid/stat. Not null.
* @return the CPU use in percent or -1f if the stats are inverted or on
* error
* @param uptime
* sum of user and kernel times for the entire system for the
* same period of time.
* @return 12.7 for a cpu usage of 12.7% or -1 if the value is not available
* or an error occurred.
* @see {@link #readProcessStat(int)}
*/
public float getProcessCpuUsage(String start, String end, long uptime) {
String[] stat = start.split("\\s");
long up1 = getProcessUptime(stat);
stat = end.split("\\s");
long up2 = getProcessUptime(stat);
float ret = -1f;
if (up1 >= 0 && up2 >= up1 && uptime > 0.) {
ret = 100.f * (up2 - up1) / (float) uptime;
}
return ret;
}
/**
* Decode the fields of the file {@code /proc/pid/stat} and return (utime +
* stime)
*
* @param stat
* obtained with {@link #readProcessStat(int)}
*/
public long getProcessUptime(String[] stat) {
return Long.parseLong(stat[14]) + Long.parseLong(stat[15]);
}
/**
* Decode the fields of the file {@code /proc/pid/stat} and return (cutime +
* cstime)
*
* @param stat
* obtained with {@link #readProcessStat(int)}
*/
public long getProcessIdleTime(String[] stat) {
return Long.parseLong(stat[16]) + Long.parseLong(stat[17]);
}
/**
* Return the total CPU usage, in percent.
* <p>
* The call is blocking for the time specified by elapse.
* </p>
*
* @param elapse
* the time in milliseconds between reads.
* @return 12.7 for a CPU usage of 12.7% or -1 if the value is not
* available.
*/
public float syncGetSystemCpuUsage(long elapse) {
String stat1 = readSystemStat();
if (stat1 == null) {
return -1.f;
}
try {
Thread.sleep(elapse);
} catch (Exception e) {
}
String stat2 = readSystemStat();
if (stat2 == null) {
return -1.f;
}
return getSystemCpuUsage(stat1, stat2);
}
/**
* Return the CPU usage of a process, in percent.
* <p>
* The call is blocking for the time specified by elapse.
* </p>
*
* @param pid
* @param elapse
* the time in milliseconds between reads.
* @return 6.32 for a CPU usage of 6.32% or -1 if the value is not
* available.
*/
public float syncGetProcessCpuUsage(int pid, long elapse) {
String pidStat1 = readProcessStat(pid);
String totalStat1 = readSystemStat();
if (pidStat1 == null || totalStat1 == null) {
return -1.f;
}
try {
Thread.sleep(elapse);
} catch (Exception e) {
e.printStackTrace();
return -1.f;
}
String pidStat2 = readProcessStat(pid);
String totalStat2 = readSystemStat();
if (pidStat2 == null || totalStat2 == null) {
return -1.f;
}
String[] toks = totalStat1.split("\\s");
long cpu1 = getSystemUptime(toks);
toks = totalStat2.split("\\s");
long cpu2 = getSystemUptime(toks);
return getProcessCpuUsage(pidStat1, pidStat2, cpu2 - cpu1);
}
}
There are several ways of exploiting this class. You can call either syncGetSystemCpuUsage
or syncGetProcessCpuUsage
but each is blocking the calling thread. Since a common issue is to monitor the total CPU usage and the CPU use of the current process at the same time, I have designed a class computing both of them. That class contains a dedicated thread. The output management is implementation specific and you need to code your own.
The class can be customized by a few means. The constant CPU_WINDOW
defines the depth of a read, i.e. the number of milliseconds between readings and computing of the corresponding CPU load. CPU_REFRESH_RATE
is the time between each CPU load measurement. Do not set CPU_REFRESH_RATE
to 0 because it will suspend the thread after the first read.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import android.app.Application;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;
import my.app.LinuxUtils;
import my.app.Streams;
import my.app.TestReport;
import my.app.Utils;
public final class CpuUtil {
private static final int CPU_WINDOW = 1000;
private static final int CPU_REFRESH_RATE = 100; // Warning: anything but > 0
private static HandlerThread handlerThread;
private static TestReport output;
static {
output = new TestReport();
output.setDateFormat(Utils.getDateFormat(Utils.DATE_FORMAT_ENGLISH));
}
private static boolean monitorCpu;
/**
* Construct the class singleton. This method should be called in
* {@link Application#onCreate()}
*
* @param dir
* the parent directory
* @param append
* mode
*/
public static void setOutput(File dir, boolean append) {
try {
File file = new File(dir, "cpu.txt");
output.setOutputStream(new FileOutputStream(file, append));
if (!append) {
output.println(file.getAbsolutePath());
output.newLine(1);
// print header
_printLine(output, "Process", "CPU%");
output.flush();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/** Start CPU monitoring */
public static boolean startCpuMonitoring() {
CpuUtil.monitorCpu = true;
handlerThread = new HandlerThread("CPU monitoring"); //$NON-NLS-1$
handlerThread.start();
Handler handler = new Handler(handlerThread.getLooper());
handler.post(new Runnable() {
@Override
public void run() {
while (CpuUtil.monitorCpu) {
LinuxUtils linuxUtils = new LinuxUtils();
int pid = android.os.Process.myPid();
String cpuStat1 = linuxUtils.readSystemStat();
String pidStat1 = linuxUtils.readProcessStat(pid);
try {
Thread.sleep(CPU_WINDOW);
} catch (Exception e) {
}
String cpuStat2 = linuxUtils.readSystemStat();
String pidStat2 = linuxUtils.readProcessStat(pid);
float cpu = linuxUtils
.getSystemCpuUsage(cpuStat1, cpuStat2);
if (cpu >= 0.0f) {
_printLine(output, "total", Float.toString(cpu));
}
String[] toks = cpuStat1.split(" ");
long cpu1 = linuxUtils.getSystemUptime(toks);
toks = cpuStat2.split(" ");
long cpu2 = linuxUtils.getSystemUptime(toks);
cpu = linuxUtils.getProcessCpuUsage(pidStat1, pidStat2,
cpu2 - cpu1);
if (cpu >= 0.0f) {
_printLine(output, "" + pid, Float.toString(cpu));
}
try {
synchronized (this) {
wait(CPU_REFRESH_RATE);
}
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
}
Log.i("THREAD CPU", "Finishing");
}
});
return CpuUtil.monitorCpu;
}
/** Stop CPU monitoring */
public static void stopCpuMonitoring() {
if (handlerThread != null) {
monitorCpu = false;
handlerThread.quit();
handlerThread = null;
}
}
/** Dispose of the object and release the resources allocated for it */
public void dispose() {
monitorCpu = false;
if (output != null) {
OutputStream os = output.getOutputStream();
if (os != null) {
Streams.close(os);
output.setOutputStream(null);
}
output = null;
}
}
private static void _printLine(TestReport output, String process, String cpu) {
output.stampln(process + ";" + cpu);
}
}
if exist yourfilename (
echo Yes
) else (
echo No
)
Replace yourfilename with the name of your file.
if exist yourfoldername\ (
echo Yes
) else (
echo No
)
Replace yourfoldername with the name of your folder.
A trailing backslash (\
) seems to be enough to distinguish between directories and ordinary files.
I'm pretty mixed up on this. I am also running Excel 2010. I tried saving two sheets as a single PDF using:
ThisWorkbook.Sheets(Array(1,2)).Select
**Selection**.ExportAsFixedFormat xlTypePDF, FileName & ".pdf", , , False
but I got nothing but blank pages. It saved both sheets, but nothing on them. It wasn't until I used:
ThisWorkbook.Sheets(Array(1,2)).Select
**ActiveSheet**.ExportAsFixedFormat xlTypePDF, FileName & ".pdf", , , False
that I got a single PDF file with both sheets.
I tried manually saving these two pages using Selection in the Options dialog to save the two sheets I had selected, but got blank pages. When I tried the Active Sheet(s) option, I got what I wanted. When I recorded this as a macro, Excel used ActiveSheet when it successfully published the PDF. What gives?
The feature is called "code templates" in Eclipse. You can add templates with:
Window->Preferences->Java->Editor->Templates.
Two good articles:
Also, this SO question:
System.out.println()
is already mapped to sysout
, so you may save time by learning a few of the existing templates first.
You can use position:absolute;
to absolutely position an element within a parent div.
When using position:absolute;
the element will be positioned absolutely from the first positioned parent div, if it can't find one it will position absolutely from the window so you will need to make sure the content div is positioned.
To make the content div positioned, all position
values that aren't static will work, but relative
is the easiest since it doesn't change the divs positioning by itself.
So add position:relative;
to the content div, remove the float from the button and add the following css to the button:
position: absolute;
right: 0;
bottom: 0;
Use the universal one-liner in terminal in the project directory:
touch .gitignore && echo "node_modules/" >> .gitignore && git rm -r --cached node_modules ; git status
It works no matter if you've created a .gitignore
or not, no matter if you've added node_modules
to git tracking or not.
Then commit and push the .gitignore
changes.
Explanation
touch
will generate the .gitignore
file if it doesn't already exist.
echo
and >>
will append node_modules/
at the end of .gitignore
, causing the node_modules
folder and all subfolders to be ignored.
git rm -r --cached
removes the node_modules
folder from git control if it was added before. Otherwise, this will show a warning pathspec 'node_modules' did not match any files
, which has no side effects and you can safely ignore. The flags cause the removal to be recursive and include the cache.
git status
displays the new changes. A change to .gitignore
will appear, while node_modules
will not appear as it is no longer being tracked by git.
Action Definition
const selectSlice = () => {
return {
type: 'SELECT_SLICE'
}
};
Action Dispatch
store.dispatch({
type:'SELECT_SLICE'
});
Make sure the object structure of action defined is same as action dispatched. In my case, while dispatching action, type was not assigned to property type
.
Make sure your AndroidManifest file contains a package name in the manifest node. Setting a package name fixed this problem for me.
You are passing hello()
as a string, also hello()
means execute hello
immediately.
try
onClick={hello}
The syntax for creating a new table is
CREATE TABLE new_table
AS
SELECT *
FROM old_table
This will create a new table named new_table
with whatever columns are in old_table
and copy the data over. It will not replicate the constraints on the table, it won't replicate the storage attributes, and it won't replicate any triggers defined on the table.
SELECT INTO
is used in PL/SQL when you want to fetch data from a table into a local variable in your PL/SQL block.
You can have a javascript variable which stores the number of checkboxes that are emitted, i.e in the <head>
of the page:
<script type="text/javascript">
var num_cboxes=<?php echo $number_of_checkboxes;?>;
</script>
So if there are 10 checkboxes, starting from user_group-1
to user_group-10
, in the javascript code you would get their value in this way:
var values=new Array();
for (x=1; x<=num_cboxes; x++)
{
values[x]=$("#user_group-" + x).val();
}
For anyone else having the same problem, I figured it out myself.
<html>_x000D_
<body>_x000D_
<form target="_blank" action="https://website.com/action.php" method="POST">_x000D_
<input type="hidden" name="fullname" value="Sam" />_x000D_
<input type="hidden" name="city" value="Dubai " />_x000D_
<input onclick="window.location.href = 'https://website.com/my-account';" type="submit" value="Submit request" />_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
All I had to do was add the target="_blank" attribute to inline on form to open the response in a new page and redirect the other page using onclick on the submit button.
If your table is separated by others than tabs, you should specify it like...
LOAD DATA LOCAL
INFILE '/tmp/mydata.txt' INTO TABLE PerformanceReport
COLUMNS TERMINATED BY '\t' ## This should be your delimiter
OPTIONALLY ENCLOSED BY '"'; ## ...and if text is enclosed, specify here
(update: 2018)
Note that pd.Timegrouper
is depreciated and will be removed. Use instead:
df.groupby(pd.Grouper(freq='M'))
rows = int(input())
cols = int(input())
matrix = []
for i in range(rows):
row = []
for j in range(cols):
row.append(0)
matrix.append(row)
print(matrix)
Why such a long code, that too in Python
you ask?
Long back when I was not comfortable with Python, I saw the single line answers for writing 2D matrix and told myself I am not going to use 2-D matrix in Python again. (Those single lines were pretty scary and It didn't give me any information on what Python was doing. Also note that I am not aware of these shorthands.)
Anyways, here's the code for a beginner whose coming from C, CPP and Java background
Note to Python Lovers and Experts: Please do not down vote just because I wrote a detailed code.
If you are using this other path a lot of the time you can fix this permanently without having to specify the path all of the time. By default, it is checking for partial views in the View folder and in the Shared folder. But say you want to add one.
Add a class to your Models folder:
public class NewViewEngine : RazorViewEngine {
private static readonly string[] NEW_PARTIAL_VIEW_FORMATS = new[] {
"~/Views/Foo/{0}.cshtml",
"~/Views/Shared/Bar/{0}.cshtml"
};
public NewViewEngine() {
// Keep existing locations in sync
base.PartialViewLocationFormats = base.PartialViewLocationFormats.Union(NEW_PARTIAL_VIEW_FORMATS).ToArray();
}
}
Then in your Global.asax.cs file, add the following line:
ViewEngines.Engines.Add(new NewViewEngine());
Did you write
String guid = System.Guid.NewGuid().ToString;
or
String guid = System.Guid.NewGuid().ToString();
notice the paranthesis
To resume the working solutions in VisualStudio 2013 and 2015 too:
In Solution Explorer (a palette-window of the VisualStudio-mainwindow), open the shortcut menu for the project and choose Properties, and then in the left pane of the Property Pages dialog box, expand Configuration Properties and select VC++ Directories. Additional include- or lib-paths are specifyable there.
Its the what Stackunderflow and user1741137 say in the answers above. Its the what Microsoft explains in MSDN too.
Its the question, what Jay Elston is asking in a comment above and what is a very obvious and burning question in my eyes, what seems to be nonanswered here yet.
There exist regular ways to do it in VisualStudio (see CurlyBrace.com), what in my experience are not working properly. In the sense, that it works only once, and thereafter, it is no more expandable and nomore removable. The approach of Steve Wilkinson in another close related thread of StackOverflow, editing the Microsoft-Factory-XML-file in the ‘program files’ - directory is probably a risky hack, as it isnt expected by Microsoft to meet there something foreign. The effect is potentally unpredictable. Well, I like rather to judge it risky not much, but anyway the best way to make VisualStudio work incomprehensible at least for someone else.
The what is working fine compared to, is the editing the corresponding User-XML-file:
C:\Users\UserName\AppData\Local\Microsoft\MSBuild\v4.0\Microsoft.Cpp.Win32.user.props
or/and
C:\Users\UserName\AppData\Local\Microsoft\MSBuild\v4.0\Microsoft.Cpp.x64.user.props
For example:
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ImportGroup Label="PropertySheets">
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<IncludePath>C:\any-name\include;$(IncludePath)</IncludePath>
<LibraryPath>C:\any-name\lib;$(LibraryPath)</LibraryPath>
</PropertyGroup>
<ItemDefinitionGroup />
<ItemGroup />
</Project>
Where the directory ‘C:\any-name\include’ will get prepended to the present include-path and the directory ‘C:\any-name\lib’ to the library-path. Here, we can edit it ago in an extending and removing sense and remove it all, removing thewhole content of the tag .
Its the what makes VisualStudio itself, doing it in the regular way what CurlyBrace describes. As said, it isnt editable in the CurlyBrace-way thereafter nomore, but in the XML-editing-way it is.
For more insight, see Brian Tyler@MSDN-Blog 2009, what is admittedly not very fresh, but always the what Microsoft is linking to.
Guava's CharMatcher provides a concise solution:
output = CharMatcher.javaLetterOrDigit().retainFrom(input);
Here are the steps you need. Step5 is important if you want the data. Step 2 is where you can select individual tables.
EDIT stack's version isn't quite readable... here's a full-size image http://i.imgur.com/y6ZCL.jpg
This is what I use in Linux to avoid starting a script if already running:
import os
import sys
script_name = os.path.basename(__file__)
pidfile = os.path.join("/tmp", os.path.splitext(script_name)[0]) + ".pid"
def create_pidfile():
if os.path.exists(pidfile):
with open(pidfile, "r") as _file:
last_pid = int(_file.read())
# Checking if process is still running
last_process_cmdline = "/proc/%d/cmdline" % last_pid
if os.path.exists(last_process_cmdline):
with open(last_process_cmdline, "r") as _file:
cmdline = _file.read()
if script_name in cmdline:
raise Exception("Script already running...")
with open(pidfile, "w") as _file:
pid = str(os.getpid())
_file.write(pid)
def main():
"""Your application logic goes here"""
if __name__ == "__main__":
create_pidfile()
main()
This approach works good without any dependency on an external module.
You Could do something like this .....
Your Table
CREATE TABLE TestTable
(
ID INT,
Data NVARCHAR(50)
)
GO
INSERT INTO TestTable
VALUES (1,'AABBCC'),
(2,'FFDD'),
(3,'TTHHJJKKLL')
GO
SELECT * FROM TestTable
My Suggestion
CREATE TABLE #DestinationTable
(
ID INT,
Data NVARCHAR(50)
)
GO
SELECT * INTO #Temp FROM TestTable
DECLARE @String NVARCHAR(2)
DECLARE @Data NVARCHAR(50)
DECLARE @ID INT
WHILE EXISTS (SELECT * FROM #Temp)
BEGIN
SELECT TOP 1 @Data = DATA, @ID = ID FROM #Temp
WHILE LEN(@Data) > 0
BEGIN
SET @String = LEFT(@Data, 2)
INSERT INTO #DestinationTable (ID, Data)
VALUES (@ID, @String)
SET @Data = RIGHT(@Data, LEN(@Data) -2)
END
DELETE FROM #Temp WHERE ID = @ID
END
SELECT * FROM #DestinationTable
Result Set
ID Data
1 AA
1 BB
1 CC
2 FF
2 DD
3 TT
3 HH
3 JJ
3 KK
3 LL
DROP Temp Tables
DROP TABLE #Temp
DROP TABLE #DestinationTable
With Jquery... You can add class to html elements like this:
$(".divclass").find("p,h1,h2,h3,figure,span,a").addClass('nameclassorid');
nameclassorid no point or # at the beginning
For those whose bat files are still not working in Windows 8+ Task Scheduler , one thing I would like to add to Ghazi's answer - after much suffering:
1) Under Actions, Choose "Create BASIC task", not "Create Task"
That did it for me, plus the other issues not to forget:
This worked without any need to trigger a command prompt.
(Sorry my rep is too low to add my Basic Task tip to Ghazi's comments)
If you actually do want your proxy configurations and plugin installations to be in your Vagrantfile, for example if you're making a Vagrantfile just for your corporate environment and can't have users editing environment variables, this was the answer for me:
ENV['http_proxy'] = 'http://proxyhost:proxyport'
ENV['https_proxy'] = 'http://proxyhost:proxyport'
# Plugin installation procedure from http://stackoverflow.com/a/28801317
required_plugins = %w(vagrant-proxyconf)
plugins_to_install = required_plugins.select { |plugin| not Vagrant.has_plugin? plugin }
if not plugins_to_install.empty?
puts "Installing plugins: #{plugins_to_install.join(' ')}"
if system "vagrant plugin install #{plugins_to_install.join(' ')}"
exec "vagrant #{ARGV.join(' ')}"
else
abort "Installation of one or more plugins has failed. Aborting."
end
end
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.proxy.http = "#{ENV['http_proxy']}"
config.proxy.https = "#{ENV['https_proxy']}"
config.proxy.no_proxy = "localhost,127.0.0.1"
# and so on
(If you don't, just set them as environment variables like the other answers say and refer to them from env in config.proxy.http(s) directives.)
if you want to change color by hovering in the element, try this:
path:hover{
fill:red;
}
export default class Order {
static fromCart(cart) {
var newOrder = new Order();
newOrder.items = cart.items;
newOrder.sum = cart.sum;
return newOrder;
}
static fromOrder(id, order) {
var newOrder = new Order();
newOrder.id = id;
newOrder.items = order.items;
newOrder.sum = order.sum;
return newOrder;
}
}
Useges:
var newOrder = Order.fromCart(cart)
var newOrder = Order.fromOrder(id, oldOrder)
If these worksheets reside in the same workbook, a simple solution would be to name the range, and have the formula refer to the named range. To name a range, select it, right click, and provide it with a meaningful name with Workbook scope.
For example =Sheet1!$A$1:$F$1
could be named: theNamedRange
. Then your formula on Sheet2!
could refer to it in your formula like this: =SUM(theNamedRange)
.
Incidentally, it is not clear from your question how you meant to use the range. If you put what you had in a formula (e.g., =SUM(Sheet1!A1:F1)
) it will work, you simply need to insert that range argument in a formula. Excel does not resolve the range reference without a related formula because it does not know what you want to do with it.
Of the two methods, I find the named range convention is easier to work with.
To add to craig_h's comment above (I currently don't have enough rep to add this as a comment to his answer, sorry), if your primary key is not an integer, you'll also want to tell your model what data type it is, by setting keyType at the top of the model definition.
public $keyType = 'string'
Eloquent understands any of the types defined in the castAttribute()
function, which as of Laravel 5.4 are: int, float, string, bool, object, array, collection, date and timestamp.
This will ensure that your primary key is correctly cast into the equivalent PHP data type.
On many popular devices the market name of the device is not available. For example, on the Samsung Galaxy S6 the value of Build.MODEL
could be "SM-G920F"
, "SM-G920I"
, or "SM-G920W8"
.
I created a small library that gets the market (consumer friendly) name of a device. It gets the correct name for over 10,000 devices and is constantly updated. If you wish to use my library click the link below:
If you do not want to use the library above, then this is the best solution for getting a consumer friendly device name:
/** Returns the consumer friendly device name */
public static String getDeviceName() {
String manufacturer = Build.MANUFACTURER;
String model = Build.MODEL;
if (model.startsWith(manufacturer)) {
return capitalize(model);
}
return capitalize(manufacturer) + " " + model;
}
private static String capitalize(String str) {
if (TextUtils.isEmpty(str)) {
return str;
}
char[] arr = str.toCharArray();
boolean capitalizeNext = true;
String phrase = "";
for (char c : arr) {
if (capitalizeNext && Character.isLetter(c)) {
phrase += Character.toUpperCase(c);
capitalizeNext = false;
continue;
} else if (Character.isWhitespace(c)) {
capitalizeNext = true;
}
phrase += c;
}
return phrase;
}
Example from my Verizon HTC One M8:
// using method from above
System.out.println(getDeviceName());
// Using https://github.com/jaredrummler/AndroidDeviceNames
System.out.println(DeviceName.getDeviceName());
Result:
HTC6525LVW
HTC One (M8)
Drop the semicolon after the function definition.
(function (msg){alert(msg)})
('SO');
Above should work.
DEMO Page: https://jsfiddle.net/e7ooeq6m/
I have discussed this kind of pattern in this post:
EDIT:
If you look at ECMA script specification, there are 3 ways you can define a function. (Page 98, Section 13 Function Definition)
var sum = new Function('a','b', 'return a + b;');
alert(sum(10, 20)); //alerts 30
function sum(a, b)
{
return a + b;
}
alert(sum(10, 10)); //Alerts 20;
var sum = function(a, b) { return a + b; }
alert(sum(5, 5)); // alerts 10
So you may ask, what's the difference between declaration and expression?
From ECMA Script specification:
FunctionDeclaration : function Identifier ( FormalParameterListopt ){ FunctionBody }
FunctionExpression : function Identifieropt ( FormalParameterListopt ){ FunctionBody }
If you notice, 'identifier' is optional for function expression. And when you don't give an identifier, you create an anonymous function. It doesn't mean that you can't specify an identifier.
This means following is valid.
var sum = function mySum(a, b) { return a + b; }
Important point to note is that you can use 'mySum' only inside the mySum function body, not outside. See following example:
var test1 = function test2() { alert(typeof test2); }
alert(typeof(test2)); //alerts 'undefined', surprise!
test1(); //alerts 'function' because test2 is a function.
Compare this to
function test1() { alert(typeof test1) };
alert(typeof test1); //alerts 'function'
test1(); //alerts 'function'
Armed with this knowledge, let's try to analyze your code.
When you have code like,
function(msg) { alert(msg); }
You created a function expression. And you can execute this function expression by wrapping it inside parenthesis.
(function(msg) { alert(msg); })('SO'); //alerts SO.
Sounds very much like MySQL events that are stored in system tables. You can look at the structure and figure out which columns are not needed:
EVENT_CATALOG: NULL
EVENT_SCHEMA: myschema
EVENT_NAME: e_store_ts
DEFINER: jon@ghidora
EVENT_BODY: SQL
EVENT_DEFINITION: INSERT INTO myschema.mytable VALUES (UNIX_TIMESTAMP())
EVENT_TYPE: RECURRING
EXECUTE_AT: NULL
INTERVAL_VALUE: 5
INTERVAL_FIELD: SECOND
SQL_MODE: NULL
STARTS: 0000-00-00 00:00:00
ENDS: 0000-00-00 00:00:00
STATUS: ENABLED
ON_COMPLETION: NOT PRESERVE
CREATED: 2006-02-09 22:36:06
LAST_ALTERED: 2006-02-09 22:36:06
LAST_EXECUTED: NULL
EVENT_COMMENT:
if you are using tortoise svn client - while exporting - it displays ..export / checkout , it is confusing , it is just export only. only view/read use export , to commit use - "checkout"
If you aren't comfortable with using negative margins, check this out.
div {
position: fixed;
left: 50%;
bottom: 20px;
transform: translate(-50%, -50%);
margin: 0 auto;
}
<div>
Your Text
</div>
Especially useful when you don't know the width of the div.
align="center"
has no effect.
Since you have position:absolute
, I would recommend positioning it 50% from the left and then subtracting half of its width from its left margin.
#manipulate {
position:absolute;
width:300px;
height:300px;
background:#063;
bottom:0px;
right:25%;
left:50%;
margin-left:-150px;
}
Adding a class to Html.EditorFor
doesn't make sense as inside its template you could have many different tags. So you need to assign the class inside the editor template:
@Html.EditorFor(x => x.Created)
and in the custom template:
<div>
@Html.TextBoxForModel(x => x.Created, new { @class = "date" })
</div>
This error occurs when there are some non ASCII characters in our string and we are performing any operations on that string without proper decoding. This helped me solve my problem. I am reading a CSV file with columns ID,Text and decoding characters in it as below:
train_df = pd.read_csv("Example.csv")
train_data = train_df.values
for i in train_data:
print("ID :" + i[0])
text = i[1].decode("utf-8",errors="ignore").strip().lower()
print("Text: " + text)
Use this code to pass arraylist<customobj>
to anthother Activity
firstly serialize our contact bean
public class ContactBean implements Serializable {
//do intialization here
}
Now pass your arraylist
Intent intent = new Intent(this,name of activity.class);
contactBean=(ConactBean)_arraylist.get(position);
intent.putExtra("contactBeanObj",conactBean);
_activity.startActivity(intent);
The new Grid CSS specification provides a far more elegant solution. Using position: absolute
may lead to overlaps or scaling issues while Grid will save you from dirty CSS hacks.
Most minimal Grid Overlay example:
HTML
<div class="container">
<div class="content">This is the content</div>
<div class="overlay">Overlay - must be placed under content in the HTML</div>
</div>
CSS
.container {
display: grid;
}
.content, .overlay {
grid-area: 1 / 1;
}
That's it. If you don't build for Internet Explorer, your code will most probably work.
Edit: I misunderstood your question, I thought you were asking how to pad with spaces.
What you are asking is not possible using the string.Format
alignment component; string.Format
always pads with whitespace. See the Alignment Component section of MSDN: Composite Formatting.
According to Reflector, this is the code that runs inside StringBuilder.AppendFormat(IFormatProvider, string, object[])
which is called by string.Format
:
int repeatCount = num6 - str2.Length;
if (!flag && (repeatCount > 0))
{
this.Append(' ', repeatCount);
}
this.Append(str2);
if (flag && (repeatCount > 0))
{
this.Append(' ', repeatCount);
}
As you can see, blanks are hard coded to be filled with whitespace.
It is important to highlight that the Property (MaximumErrorCount) that needs to be changed must be set as more than 0 (which is the default) in the Package level and not in the specific control that is showing the error (I tried this and it does not work!)
Be sure that in the Properties Window, the Pull down menu is set to "Package", then look for the property MaximumErrorCount to change it.
slicing operator. http://docs.python.org/tutorial/introduction.html#strings and scroll down a bit
You can use js fetch
async function send(url,data) {_x000D_
let r= await fetch(url, {_x000D_
method: "POST", _x000D_
headers: {_x000D_
"My-header": "abc" _x000D_
},_x000D_
body: JSON.stringify(data), _x000D_
})_x000D_
return await r.json()_x000D_
}_x000D_
_x000D_
// Example usage_x000D_
_x000D_
let url='https://server.test-cors.org/server?enable=true&status=200&methods=POST&headers=my-header';_x000D_
_x000D_
async function run() _x000D_
{_x000D_
let jsonObj = await send(url,{ some: 'testdata' });_x000D_
console.log(jsonObj[0].request.httpMethod + ' was send - open chrome console > network to see it');_x000D_
}_x000D_
_x000D_
run();
_x000D_
My solution in Python with sqlite3:
import sqlite3
import re
def match(expr, item):
return re.match(expr, item) is not None
conn = sqlite3.connect(':memory:')
conn.create_function("MATCHES", 2, match)
cursor = conn.cursor()
cursor.execute("SELECT MATCHES('^b', 'busy');")
print cursor.fetchone()[0]
cursor.close()
conn.close()
If regex matches, the output would be 1, otherwise 0.
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.
The return type of a procedure is int.
You can also return result sets (as your code currently does) (okay, you can also send messages, which are strings)
Those are the only "returns" you can make. Whilst you can add table-valued parameters to a procedure (see BOL), they're input only.
Edit:
(Or as another poster mentioned, you could also use a Table Valued Function, rather than a procedure)
If you use maven try to add in the pom.xml
<properties>
...
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
...
</properties>
Otherwise try to change the compiler version.
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
public class MyServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException
{
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<b><centre>Redirecting to Google<br>");
response.setHeader("refresh,"5;https://www.google.com/"); // redirects to url after 5 seconds
pw.close();
}
}
This does an in-memory copy that you can mutate independently.
original = CheckoutItem(title="test", ...)
copy = CheckoutItem()
for f in CheckoutItem._meta.fields:
setattr(copy, f.attname, getattr(original, f.attname))
Or, as a method:
def clone(self):
"""Returns a clone of this instance."""
clone = self.__class__()
for f in self.__class__._meta.fields:
setattr(clone, f.attname, getattr(self, f.attname))
return clone
You can use tandem of MemoryStream
and StreamReader
classes:
void Main()
{
string myString;
using (var stream = new MemoryStream())
{
Print(stream);
stream.Position = 0;
using (var reader = new StreamReader(stream))
{
myString = reader.ReadToEnd();
}
}
}
ImageIO.write()
will compress the image by default - the compressed image has a smaller size but looks strange sometimes. I use BufferedOutputStream
to save the byte array data - this will keep the original image size.
Here is the code:
import javax.xml.bind.DatatypeConverter;
import java.io.*;
public class ImageTest {
public static void main(String[] args) {
String base64String = "data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAAHkAAAB5C...";
String[] strings = base64String.split(",");
String extension;
switch (strings[0]) {//check image's extension
case "data:image/jpeg;base64":
extension = "jpeg";
break;
case "data:image/png;base64":
extension = "png";
break;
default://should write cases for more images types
extension = "jpg";
break;
}
//convert base64 string to binary data
byte[] data = DatatypeConverter.parseBase64Binary(strings[1]);
String path = "C:\\Users\\Ene\\Desktop\\test_image." + extension;
File file = new File(path);
try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file))) {
outputStream.write(data);
} catch (IOException e) {
e.printStackTrace();
}
}
}
You have to use execute immediate (dynamic sql).
DECLARE
v_owner varchar2(40);
v_table_name varchar2(40);
cursor get_tables is
select distinct table_name,user
from user_tables
where lower(user) = 'schema_name';
begin
open get_tables;
loop
fetch get_tables into v_table_name,v_owner;
EXIT WHEN get_tables%NOTFOUND;
execute immediate 'INSERT INTO STATS_TABLE(TABLE_NAME,SCHEMA_NAME,RECORD_COUNT,CREATED)
SELECT ''' || v_table_name || ''' , ''' || v_owner ||''',COUNT(*),TO_DATE(SYSDATE,''DD-MON-YY'') FROM ' || v_table_name;
end loop;
CLOSE get_tables;
END;
Just move the extra condition into the JOIN ON criteria, this way the existence of b is not required to return a result
SELECT a.* FROM a
LEFT JOIN b ON a.group_id=b.group_id AND b.user_id!=$_SESSION{['user_id']}
WHERE a.keyword LIKE '%".$keyword."%'
GROUP BY group_id
get current activity from parent, then using this code
getActivity().getSupportFragmentManager()
I have used this query in our production code for nearly 10 years:
SELECT FLOOR((CAST (GetDate() AS INTEGER) - CAST(Date_of_birth AS INTEGER)) / 365.25) AS Age
It doesn't work if you use Function, but works if you Sub. However, you cannot call a sub from a cell using formula.