Only way to dynamically attach a property is to create a new class and its instance with your new property.
class Holder: p = property(lambda x: vs[i], self.fn_readonly)
setattr(self, k, Holder().p)
What is monkey patching? Monkey patching is a technique used to dynamically update the behavior of a piece of code at run-time.
Why use monkey patching? It allows us to modify or extend the behavior of libraries, modules, classes or methods at runtime without actually modifying the source code
Conclusion Monkey patching is a cool technique and now we have learned how to do that in Python. However, as we discussed, it has its own drawbacks and should be used carefully.
For more info Please refer [1]: https://medium.com/@nagillavenkatesh1234/monkey-patching-in-python-explained-with-examples-25eed0aea505
I think that the above answers missed the key point.
Let's have a class with a method:
class A(object):
def m(self):
pass
Now, let's play with it in ipython:
In [2]: A.m
Out[2]: <unbound method A.m>
Ok, so m() somehow becomes an unbound method of A. But is it really like that?
In [5]: A.__dict__['m']
Out[5]: <function m at 0xa66b8b4>
It turns out that m() is just a function, reference to which is added to A class dictionary - there's no magic. Then why A.m gives us an unbound method? It's because the dot is not translated to a simple dictionary lookup. It's de facto a call of A.__class__.__getattribute__(A, 'm'):
In [11]: class MetaA(type):
....: def __getattribute__(self, attr_name):
....: print str(self), '-', attr_name
In [12]: class A(object):
....: __metaclass__ = MetaA
In [23]: A.m
<class '__main__.A'> - m
<class '__main__.A'> - m
Now, I'm not sure out of the top of my head why the last line is printed twice, but still it's clear what's going on there.
Now, what the default __getattribute__ does is that it checks if the attribute is a so-called descriptor or not, i.e. if it implements a special __get__ method. If it implements that method, then what is returned is the result of calling that __get__ method. Going back to the first version of our A class, this is what we have:
In [28]: A.__dict__['m'].__get__(None, A)
Out[28]: <unbound method A.m>
And because Python functions implement the descriptor protocol, if they are called on behalf of an object, they bind themselves to that object in their __get__ method.
Ok, so how to add a method to an existing object? Assuming you don't mind patching class, it's as simple as:
B.m = m
Then B.m "becomes" an unbound method, thanks to the descriptor magic.
And if you want to add a method just to a single object, then you have to emulate the machinery yourself, by using types.MethodType:
b.m = types.MethodType(m, b)
By the way:
In [2]: A.m
Out[2]: <unbound method A.m>
In [59]: type(A.m)
Out[59]: <type 'instancemethod'>
In [60]: type(b.m)
Out[60]: <type 'instancemethod'>
In [61]: types.MethodType
Out[61]: <type 'instancemethod'>
Do this it will definitely work
"scripts": {
"start": "SET NODE_ENV=production && node server"
}
SELECT * FROM TABLENAME ORDER BY random() LIMIT 5;
Either way works, but many places have coding standards in place that will guide the developer one way or the other. If such a policy is not in place, just follow your heart. One thing, though, it REALLY helps the readability of the code if you do use it. especially if you are not following a naming convention on class-level variable names.
Let us consider table name as tblperson
and column name as city
. I want to retrieve the most repeated city from the city column:
select city,count(*) as nor from tblperson
group by city
having count(*) =(select max(nor) from
(select city,count(*) as nor from tblperson group by city) tblperson)
Here nor
is an alias name.
I asume you have connected to your database already.
$sql = "SELECT * FROM my_table";
$result = mysql_query($sql);
$row = 1; // 1-based index
while($row_data = mysql_fetch_assoc($result)) {
$col = 0;
foreach($row_data as $key=>$value) {
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
$col++;
}
$row++;
}
Three important steps - How to Task Schedule an excel.xls(m) file
simply:
IN MORE DETAIL...
`
' a .vbs file is just a text file containing visual basic code that has the extension renamed from .txt to .vbs
'Write Excel.xls Sheet's full path here
strPath = "C:\RodsData.xlsm"
'Write the macro name - could try including module name
strMacro = "Update" ' "Sheet1.Macro2"
'Create an Excel instance and set visibility of the instance
Set objApp = CreateObject("Excel.Application")
objApp.Visible = True ' or False
'Open workbook; Run Macro; Save Workbook with changes; Close; Quit Excel
Set wbToRun = objApp.Workbooks.Open(strPath)
objApp.Run strMacro ' wbToRun.Name & "!" & strMacro
wbToRun.Save
wbToRun.Close
objApp.Quit
'Leaves an onscreen message!
MsgBox strPath & " " & strMacro & " macro and .vbs successfully completed!", vbInformation
'
`
set Program/script: = C:\Windows\System32\cscript.exe
set Add arguments (optional): = C:\MyVbsFile.vbs
That should work.
Let me know!
Rod Bowen
Late answer, but hopefully worthwhile: The Poor Man's T-SQL Formatter is an open-source (free) T-SQL formatter with complete T-SQL batch/script support (any DDL, any DML), SSMS Plugin, command-line bulk formatter, and other options.
It's available for immediate/online use at http://poorsql.com, and just today graduated to "version 1.0" (it was in beta version for a few months), having just acquired support for MERGE
statements, OUTPUT
clauses, and other finicky stuff.
The SSMS Add-in allows you to set your own hotkey (default is Ctrl-K, Ctrl-F, to match Visual Studio), and formats the entire script or just the code you have selected/highlighted, if any. Output formatting is customizable.
In SSMS 2008 it combines nicely with the built-in intelli-sense, effectively providing more-or-less the same base functionality as Red Gate's SQL Prompt (SQL Prompt does, of course, have extra stuff, like snippets, quick object scripting, etc).
Feedback/feature requests are more than welcome, please give it a whirl if you get the chance!
Disclosure: This is probably obvious already but I wrote this library/tool/site, so this answer is also shameless self-promotion :)
This is a really old question, and thus, has many outdated answers. As of 2020 all major browsers have adhered to the standard.
Answer for 2020:
document.body.scrollHeight
Edit: the above doesn't take margins on the <body>
tag into account. If your body has margins, use:
document.documentElement.scrollHeight
You need the public key in your gpg key ring. To import the public key into your public keyring, place the public key block in a text file with a .gpg extension, and then issue the following command:
gpg --import <your-file>.gpg
The entity that encrypted the file should provide you with such a block. For example, ftp://ftp.gnu.org/gnu/gnu-keyring.gpg has the block for gnu.org.
For an even more in-depth explanation see Verifying files with GPG, without a .sig or .asc file?
It is a C extension from the GCC compiler , see http://gcc.gnu.org/onlinedocs/gcc/Typeof.html
Every answer refering to SuppressWarningsFilter is missing an important detail. You can only use the all-lowercase id if it's defined as such in your checkstyle-config.xml. If not you must use the original module name.
For instance, if in my checkstyle-config.xml I have:
<module name="NoWhitespaceBefore"/>
I cannot use:
@SuppressWarnings({"nowhitespacebefore"})
I must, however, use:
@SuppressWarnings({"NoWhitespaceBefore"})
In order for the first syntax to work, the checkstyle-config.xml should have:
<module name="NoWhitespaceBefore">
<property name="id" value="nowhitespacebefore"/>
</module>
This is what worked for me, at least in the CheckStyle version 6.17.
You can do something like:
Directory directory = new DirectoryInfo(path);
List<FileInfo> fileInfos = directory.EnumerateFiles("*.*", SearchOption.AllDirectories).ToList();
foreach (FileInfo f in fileInfos)
File.Delete(f.FullName);
Add simple style to your button
.btn {
background: none;
color: inherit;
border: none;
padding: 0;
font: inherit;
cursor: pointer;
outline: inherit;
}
It happens when $ret
hasn't been defined. The solution is simple. Right above $tags = get_tags();
, add the following line:
$ret = array();
I obtained much better results with wxPython than tkinter, as suggested in this answer to a later duplicate question:
https://stackoverflow.com/a/9319832
The wxPython version produced the file dialog that looked the same as the open file dialog from just about any other application on my OpenSUSE Tumbleweed installation with the xfce desktop, whereas tkinter produced something cramped and hard to read with an unfamiliar side-scrolling interface.
You can get a list of invalid characters from Path.GetInvalidPathChars and GetInvalidFileNameChars as discussed in this question.
As noted by jberger, there some other characters which are not included in the response from this method. For much more details of the windows platform, take a look at Naming Files, Paths and Namespaces on MSDN,
As Micah points out, there is Directory.GetLogicalDrives to get a list of valid drives.
Right click on your project > Open Module Setting > Select "Project" in "Project Setting" section
Change the Project SDK to latest(may be API 21) and Project language level to 7+
Check it's value
property:
In jQuery (since your tag mentions it):
$('#fileInput').val()
Or in vanilla JavaScript:
document.getElementById('myFileInput').value
First you retreieve the value (given a key) and then you add a new element to it
ArrayList<String> grades = examList.get(courseId);
grades.add(aGrade);
You could write a custom template filter to do this in a half-dozen lines of code:
from django.template import Library
register = Library()
@register.filter
def is_false(arg):
return arg is False
Then in your template:
{% if myvar|is_false %}...{% endif %}
Of course, you could make that template tag much more generic... but this suits your needs specifically ;-)
You can use a byte literal in Java... sort of.
byte f = 0;
f = 0xa;
0xa
(int literal) gets automatically cast to byte. It's not a real byte literal (see JLS & comments below), but if it quacks like a duck, I call it a duck.
What you can't do is this:
void foo(byte a) {
...
}
foo( 0xa ); // will not compile
You have to cast as follows:
foo( (byte) 0xa );
But keep in mind that these will all compile, and they are using "byte literals":
void foo(byte a) {
...
}
byte f = 0;
foo( f = 0xa ); //compiles
foo( f = 'a' ); //compiles
foo( f = 1 ); //compiles
Of course this compiles too
foo( (byte) 1 ); //compiles
sudo snap install androidsdk
You can use the sdkmanager to perform the following tasks.
androidsdk --list [options]
androidsdk packages [options]
The packages argument is an SDK-style path as shown with the --list command, wrapped in quotes (for example, "build-tools;29.0.0" or "platforms;android-28"). You can pass multiple package paths, separated with a space, but they must each be wrapped in their own set of quotes.
For example, here's how to install the latest platform tools (which includes adb and fastboot) and the SDK tools for API level 28:
androidsdk "platform-tools" "platforms;android-28"
Alternatively, you can pass a text file that specifies all packages:
androidsdk --package_file=package_file [options]
The package_file argument is the location of a text file in which each line is an SDK-style path of a package to install (without quotes).
To uninstall, simply add the --uninstall flag:
androidsdk --uninstall packages [options]
androidsdk --uninstall --package_file=package_file [options]
Update all installed packages
androidsdk --update [options]
androidsdk it is snap wraper of sdkmanager all options of sdkmanager work with androidsdk
Location of installed android sdk files : /home/user/AndroidSDK
See all sdkmanager options in google documentation
Be Careful registering an order with the: X=$(Command)
This one is still executed Even before being called. To check and confirm this, you cand do:
echo test;
X=$(for ((c=0; c<=5; c++)); do
sleep 2;
done);
echo note the 5 seconds elapsed
Rather than engage in a debating club, I would apply Defensive Programming
. As a developer of an app that receives json data, I'd allow the trailing comma. When developing an app that writes json, I'd use one of the clever techniques of the other answers to only add commas between items. There are bigger problems to be solved...
You probablly have 2 different versions of hibernate-jpa-api on the classpath. To check that run:
mvn dependency:tree >dep.txt
Then search if there are hibernate-jpa-2.0-api and hibernate-jpa-2.1-api. And exclude the excess one.
Implementing exceptions in c by Eric Roberts
Chapter 4 of C Interfaces and Implementations by Hanson.
A Discipline of Error Handling by Doug Moen
Implementing Exceptions in C (details the article of E Roberts)
Same as the above answer but allows for triple click. (Delay 500) http://jsfiddle.net/luenwarneke/rV78Y/1/
var DELAY = 500,
clicks = 0,
timer = null;
$(document).ready(function() {
$("a")
.on("click", function(e){
clicks++; //count clicks
timer = setTimeout(function() {
if(clicks === 1) {
alert('Single Click'); //perform single-click action
} else if(clicks === 2) {
alert('Double Click'); //perform single-click action
} else if(clicks >= 3) {
alert('Triple Click'); //perform Triple-click action
}
clearTimeout(timer);
clicks = 0; //after action performed, reset counter
}, DELAY);
})
.on("dblclick", function(e){
e.preventDefault(); //cancel system double-click event
});
});
I'm using Mac OS and to write multiple lines in a SH Script following code worked for me
#! /bin/bash
FILE_NAME="SomeRandomFile"
touch $FILE_NAME
echo """I wrote all
the
stuff
here.
And to access a variable we can use
$FILE_NAME
""" >> $FILE_NAME
cat $FILE_NAME
Please don't forget to assign chmod as required to the script file. I have used
chmod u+x myScriptFile.sh
This is how i used to Refresh my layout
Intent intent = getIntent();
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
startActivity(intent);
This except for adding the following to sqlnet.ora
SQLNET.ALLOWED_LOGON_VERSION_CLIENT = 8
SQLNET.ALLOWED_LOGON_VERSION_SERVER = 8
If you get "ORA-01017: invalid username/password; logon denied" error, then you need to re-create your password.
The advantages of EditorFor
is that your code is not tied to an <input type="text"
. So if you decide to change something to the aspect of how your textboxes are rendered like wrapping them in a div
you could simply write a custom editor template (~/Views/Shared/EditorTemplates/string.cshtml
) and all your textboxes in your application will automatically benefit from this change whereas if you have hardcoded Html.TextBoxFor
you will have to modify it everywhere. You could also use Data Annotations to control the way this is rendered.
A simple one liner;
res.status(404).send("Oh uh, something went wrong");
Even though, the best approach for this situation is set custom CSS styles - an alternative could be:
Width
property and set the percentaje as you see more suitable for your purposes.In my desired scenario, I need set (2) radiobuttons/items as follows:
o Item 1 | o Item 2 |
Example:
<asp:RadioButtonList ID="rbtnLstOptionsGenerateCertif" runat="server"
BackColor="Transparent" BorderColor="Transparent" RepeatDirection="Horizontal"
EnableTheming="False" Width="40%">
<asp:ListItem Text="Item 1" Value="0" />
<asp:ListItem Text="Item 2" Value="1" />
</asp:RadioButtonList>
Rendered result:
<table id="ctl00_ContentPlaceHolder_rbtnLstOptionsGenerateCertif" class="chxbx2" border="0" style="background-color:Transparent;border-color:Transparent;width:40%;">
<tbody>
<tr>
<td>
<input id="ctl00_ContentPlaceHolder_rbtnLstOptionsGenerateCertif_0" type="radio" name="ctl00$ContentPlaceHolder$rbtnLstOptionsGenerateCertif" value="0" checked="checked">
<label for="ctl00_ContentPlaceHolder_rbtnLstOptionsGenerateCertif_0">Item 1</label>
</td>
<td>
<input id="ctl00_ContentPlaceHolder_rbtnLstOptionsGenerateCertif_1" type="radio" name="ctl00$ContentPlaceHolder$rbtnLstOptionsGenerateCertif" value="1">
<label for="ctl00_ContentPlaceHolder_rbtnLstOptionsGenerateCertif_1">Item 2</label>
</td>
</tr>
</tbody>
</table>
_x000D_
Do the following:
private float xAccel, yAccel, zAccel;
private float xPreviousAccel, yPreviousAccel, zPreviousAccel;
private boolean firstUpdate = true;
private final float shakeThreshold = 1.5f;
private boolean shakeInitiated = false;
SensorEventListener mySensorEventListener;
SensorManager mySensorManager;
Put this in onCreate method.
mySensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mySensorManager.registerListener(mySensorEventListener,
mySensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
And now the main part.
private boolean isAccelerationChanged() {
float deltaX = Math.abs(xPreviousAccel - xAccel);
float deltaY = Math.abs(yPreviousAccel - yAccel);
float deltaZ = Math.abs(zPreviousAccel - zAccel);
return (deltaX > shakeThreshold && deltaY > shakeThreshold)
|| (deltaX > shakeThreshold && deltaZ > shakeThreshold)
|| (deltaY > shakeThreshold && deltaZ > shakeThreshold);
}
private void updateAccelParameters(float xNewAccel, float yNewAccel, float zNewAccel) {
if (firstUpdate) {
xPreviousAccel = xNewAccel;
yPreviousAccel = yNewAccel;
zPreviousAccel = zNewAccel;
firstUpdate = false;
}else{
xPreviousAccel = xAccel;
yPreviousAccel = yAccel;
zPreviousAccel = zAccel;
}
xAccel = xNewAccel;
yAccel = yNewAccel;
zAccel = zNewAccel;
}
private void executeShakeAction() {
//this method is called when devices shakes
}
public void onSensorChanged(SensorEvent se) {
updateAccelParameters(se.values[0], se.values[1], se.values[2]);
if ((!shakeInitiated) && isAccelerationChanged()) {
shakeInitiated = true;
}else if ((shakeInitiated) && isAccelerationChanged()){
executeShakeAction();
}else if((shakeInitiated) && (!isAccelerationChanged())){
shakeInitiated = false;
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
//setting the accuracy
}
How you deal with this at the moment depends on what model you are using Linq to SQL or EntityFramework?
In L2S you can add
public partial class NWDataContext
{
partial void InsertCategory(Category instance)
{
if(Instance.Date == null)
Instance.Data = DateTime.Now;
ExecuteDynamicInsert(instance);
}
}
EF is a little more complicated see http://msdn.microsoft.com/en-us/library/cc716714.aspx for more info on EF buisiness logic.
Here is a very rushed proof of concept.
I'm sure there are at least 2 places where there can be improvements, and I'm also sure that this would not survive long in the wild. Any feedback to make it more presentable or usable is welcome.
The key is setting an id for your script element. The only catch is that this means you can only call the script once since it looks for that ID to pull the query string. This could be fixed if, instead, the script loops through all query elements to see if any of them point to it, and if so, uses the last instance of such an script element. Anyway, on with the code:
window.onload = function() {
//Notice that both possible parameters are pre-defined.
//Which is probably not required if using proper object notation
//in query string, or if variable-variables are possible in js.
var header;
var text;
//script gets the src attribute based on ID of page's script element:
var requestURL = document.getElementById("myScript").getAttribute("src");
//next use substring() to get querystring part of src
var queryString = requestURL.substring(requestURL.indexOf("?") + 1, requestURL.length);
//Next split the querystring into array
var params = queryString.split("&");
//Next loop through params
for(var i = 0; i < params.length; i++){
var name = params[i].substring(0,params[i].indexOf("="));
var value = params[i].substring(params[i].indexOf("=") + 1, params[i].length);
//Test if value is a number. If not, wrap value with quotes:
if(isNaN(parseInt(value))) {
params[i] = params[i].replace(value, "'" + value + "'");
}
// Finally, use eval to set values of pre-defined variables:
eval(params[i]);
}
//Output to test that it worked:
document.getElementById("docTitle").innerHTML = header;
document.getElementById("docText").innerHTML = text;
};
<script id="myScript" type="text/javascript"
src="test.js?header=Test Page&text=This Works"></script>
<h1 id="docTitle"></h1>
<p id="docText"></p>
JAVA8: Use LocalDateTime.now().toString()
Password must meet at least 3 out of the following 4 complexity rules,
[at least 1 uppercase character (A-Z) at least 1 lowercase character (a-z) at least 1 digit (0-9) at least 1 special character — do not forget to treat space as special characters too]
at least 10 characters
at most 128 characters
not more than 2 identical characters in a row (e.g., 111 not allowed)
'^(?!.(.)\1{2}) ((?=.[a-z])(?=.[A-Z])(?=.[0-9])|(?=.[a-z])(?=.[A-Z])(?=.[^a-zA-Z0-9])|(?=.[A-Z])(?=.[0-9])(?=.[^a-zA-Z0-9])|(?=.[a-z])(?=.[0-9])(?=.*[^a-zA-Z0-9])).{10,127}$'
(?!.*(.)\1{2})
(?=.[a-z])(?=.[A-Z])(?=.*[0-9])
(?=.[a-z])(?=.[A-Z])(?=.*[^a-zA-Z0-9])
(?=.[A-Z])(?=.[0-9])(?=.*[^a-zA-Z0-9])
(?=.[a-z])(?=.[0-9])(?=.*[^a-zA-Z0-9])
.{10.127}
Finding duplicate addresses is much more complex than it seems, especially if you require accuracy. A MySQL query is not enough in this case...
I work at SmartyStreets, where we do address validation and de-duplication and other stuff, and I've seen a lot of diverse challenges with similar problems.
There are several third-party services which will flag duplicates in a list for you. Doing this solely with a MySQL subquery will not account for differences in address formats and standards. The USPS (for US address) has certain guidelines to make these standard, but only a handful of vendors are certified to perform such operations.
So, I would recommend the best answer for you is to export the table into a CSV file, for instance, and submit it to a capable list processor. One such is LiveAddress which will have it done for you in a few seconds to a few minutes automatically. It will flag duplicate rows with a new field called "Duplicate" and a value of Y
in it.
This problem occurs because the Web site does not have the Directory Browsing
feature enabled, and the default document is not configured. To resolve this problem, use one of the following methods. To resolve this problem, I followed the steps in Method 1 as mentioned in the MS Support page and its the recommended method.
Method 1: Enable the Directory Browsing feature in IIS (Recommended)
Start IIS Manager. To do this, click Start, click Run, type inetmgr.exe, and then click OK.
In IIS Manager, expand server name, expand Web sites, and then click the website that you want to modify.
In the Features view, double-click Directory Browsing.
In the Actions pane, click Enable.
If that does not work for, you might be having different problem than just a Directory listing issue. So follow the below step,
Method 2: Add a default document
To resolve this problem, follow these steps:
Method 3: Enable the Directory Browsing feature in IIS Express
Note This method is for the web developers who experience the issue when they use IIS Express.
Follow these steps:
Open a command prompt, and then go to the IIS Express folder on your computer.
For example, go to the following folder in a command prompt:
C:\Program Files\IIS Express
Type the following command, and then press Enter:
appcmd set config /section:system.webServer/directoryBrowse /enabled:true
In MySQL, @variable
indicates a user-defined variable. You can define your own.
SET @a = 'test';
SELECT @a;
Outside of stored programs, a variable
, without @
, is a system variable, which you cannot define yourself.
The scope of this variable is the entire session. That means that while your connection with the database exists, the variable can still be used.
This is in contrast with MSSQL, where the variable will only be available in the current batch of queries (stored procedure, script, or otherwise). It will not be available in a different batch in the same session.
Here is a good guide:
FOR /F - Loop command: against a set of files.
FOR /F - Loop command: against the results of another command.
FOR - Loop command: all options Files, Directory, List.
[The whole guide (Windows XP commands):
http://www.ss64.com/nt/index.html
Edit: Sorry, didn't see that the link was already in the OP, as it appeared to me as a part of the Amazon link.
One drawback of using componentDidUpdate
, or componentDidMount
is that they are actually executed before the dom elements are done being drawn, but after they've been passed from React to the browser's DOM.
Say for example if you needed set node.scrollHeight to the rendered node.scrollTop, then React's DOM elements may not be enough. You need to wait until the elements are done being painted to get their height.
Solution:
Use requestAnimationFrame
to ensure that your code is run after the painting of your newly rendered object
scrollElement: function() {
// Store a 'this' ref, and
var _this = this;
// wait for a paint before running scrollHeight dependent code.
window.requestAnimationFrame(function() {
var node = _this.getDOMNode();
if (node !== undefined) {
node.scrollTop = node.scrollHeight;
}
});
},
componentDidMount: function() {
this.scrollElement();
},
// and or
componentDidUpdate: function() {
this.scrollElement();
},
// and or
render: function() {
this.scrollElement()
return [...]
if myProp is an object, it may not be changed in usual. so, watch will never be triggered. the reason of why myProp not be changed is that you just set some keys of myProp in most cases. the myProp itself is still the one. try to watch props of myProp, like "myProp.a",it should work.
You can find them in /var/log
within your root Magento installation
There will usually be two files by default, exception.log
and system.log
.
If the directories or files don't exist, create them and give them the correct permissions, then enable logging within Magento by going to System > Configuration > Developer > Log Settings > Enabled = Yes
You must specify your file in the copy:
xcopy C:\source\myfile.txt C:\target
Or if you want to copy all txt files for example
xcopy C:\source\*.txt C:\target
Can someone please tell me how to create a static library from a .cpp and a .hpp file? Do I need to create the .o and the the .a?
Yes.
Create the .o (as per normal):
g++ -c header.cpp
Create the archive:
ar rvs header.a header.o
Test:
g++ test.cpp header.a -o executable_name
Note that it seems a bit pointless to make an archive with just one module in it. You could just as easily have written:
g++ test.cpp header.cpp -o executable_name
Still, I'll give you the benefit of the doubt that your actual use case is a bit more complex, with more modules.
Hope this helps!
Tried different solutions to solve the problem for several weeks without success.
The problem I was facing was caused by upgrading from laravel 5.0 to 5.5 and forgot to update config/session.php
If anyone is facing the problem, try to update the config/session.php to match the version on Laravel you are running
SELECT DATEADD(day,-30,date) AS before30d
FROM...
But it is strongly recommended to keep date in datetime column, not varchar.
SELECT name,COUNT(*) as count
FROM tablename
GROUP BY name
ORDER BY count DESC;
To get the full path to the directory a Python file is contained in, write this in that file:
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
(Note that the incantation above won't work if you've already used os.chdir()
to change your current working directory, since the value of the __file__
constant is relative to the current working directory and is not changed by an os.chdir()
call.)
To get the current working directory use
import os
cwd = os.getcwd()
Documentation references for the modules, constants and functions used above:
os
and os.path
modules.__file__
constantos.path.realpath(path)
(returns "the canonical path of the specified filename, eliminating any symbolic links encountered in the path")os.path.dirname(path)
(returns "the directory name of pathname path
")os.getcwd()
(returns "a string representing the current working directory")os.chdir(path)
("change the current working directory to path
")I could use the GetBody
from Request package.
Look this comment in source code from request.go in net/http:
GetBody defines an optional func to return a new copy of Body. It is used for client requests when a redirect requires reading the body more than once. Use of GetBody still requires setting Body. For server requests it is unused."
GetBody func() (io.ReadCloser, error)
This way you can get the body request without make it empty.
Sample:
getBody := request.GetBody
copyBody, err := getBody()
if err != nil {
// Do something return err
}
http.DefaultClient.Do(request)
In a project i´m working on we have another solution doing this.
First I don´t like the ExpectedExceptionAttribute becuase it does take in consideration which method call that caused the Exception.
I do this with a helpermethod instead.
Test
[TestMethod]
public void AccountRepository_ThrowsExceptionIfFileisCorrupt()
{
var file = File.Create("Accounts.bin");
file.WriteByte(1);
file.Close();
IAccountRepository repo = new FileAccountRepository();
TestHelpers.AssertThrows<SerializationException>(()=>repo.GetAll());
}
HelperMethod
public static TException AssertThrows<TException>(Action action) where TException : Exception
{
try
{
action();
}
catch (TException ex)
{
return ex;
}
Assert.Fail("Expected exception was not thrown");
return null;
}
Neat, isn´t it;)
Inspired by the insightful answers on this page, I created a mixed approach, which I consider the simplest and more flexible one. What do you think?
First, I define the usage in a variable, which allows me to reuse it in different contexts. The format is very simple, almost WYSIWYG, without the need to add any control characters. This seems reasonably portable to me (I ran it on MacOS and Ubuntu)
__usage="
Usage: $(basename $0) [OPTIONS]
Options:
-l, --level <n> Something something something level
-n, --nnnnn <levels> Something something something n
-h, --help Something something something help
-v, --version Something something something version
"
Then I can simply use it as
echo "$__usage"
or even better, when parsing parameters, I can just echo it there in a one-liner:
levelN=${2:?"--level: n is required!""${__usage}"}
Simple example with Java 8:
import java.util.Base64;
String str = "your string";
String encodedStr = Base64.getEncoder().encodeToString(str.getBytes("utf-8"));
Drag image from your hard drive to Drawable folder in your project and in code use it like this:
ImageView image;
image = (ImageView) findViewById(R.id.yourimageviewid);
image.setImageResource(R.drawable.imagename);
The List (unlike the Set) is an ordered collection and iterating over it does preserve the order by contract. I would have expected a Stack to iterate in the reverse order but unfortunately it doesn't. So the simplest solution I can think of is this:
for (int i = stack.size() - 1; i >= 0; i--) {
System.out.println(stack.get(i));
}
I realize that this is not a "for each" loop solution. I'd rather use the for loop than introducing a new library like the Google Collections.
Collections.reverse() also does the job but it updates the list as opposed to returning a copy in reverse order.
I was looking for the same answer to this question and after much head scratching this is the answer I came up with:
#Python 3.4.3 with Pygame
import pygame
pygame.init()
pygame.display.set_caption('Crash!')
window = pygame.display.set_mode((300, 300))
# Draw Once
Rectplace = pygame.draw.rect(window, (255, 0, 0),(100, 100, 100, 100))
pygame.display.update()
# Main Loop
while True:
# Mouse position and button clicking.
pos = pygame.mouse.get_pos()
pressed1, pressed2, pressed3 = pygame.mouse.get_pressed()
# Check if the rect collided with the mouse pos
# and if the left mouse button was pressed.
if Rectplace.collidepoint(pos) and pressed1:
print("You have opened a chest!")
# Quit pygame.
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit(1)
Just a quick check as well if you keep your js files separately: make sure to reload your resources properly. Browsers will usually cache files, so just assure that i.e. a former typo is corrected in your loaded resources.
See this answer for permanent cache disabling in Chrome/Chromium. Otherwise you can generally force a full reload with Ctrl+F5 or Shift+F5 as mentioned in this answer.
# Define the types of logger and level of logging
log4j.rootLogger = DEBUG,console, FILE
# Define the File appender
log4j.appender.FILE=org.apache.log4j.FileAppender
# Define Console Appender
log4j.appender.console=org.apache.log4j.ConsoleAppender
# Define the layout for console appender. If you do not
# define it, you will get an error
log4j.appender.console.layout=org.apache.log4j.PatternLayout
# Set the name of the file
log4j.appender.FILE.File=log.out
# Set the immediate flush to true (default)
log4j.appender.FILE.ImmediateFlush=true
# Set the threshold to debug mode
log4j.appender.FILE.Threshold=debug
# Set the append to false, overwrite
log4j.appender.FILE.Append=false
# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n
You can use the struct module:
import struct
print struct.pack('>I', your_int)
'>I'
is a format string. >
means big endian and I
means unsigned int. Check the documentation for more format chars.
You can use the sys.dm_tran_locks
view, which returns information about the currently active lock manager resources.
Try this
SELECT
SessionID = s.Session_id,
resource_type,
DatabaseName = DB_NAME(resource_database_id),
request_mode,
request_type,
login_time,
host_name,
program_name,
client_interface_name,
login_name,
nt_domain,
nt_user_name,
s.status,
last_request_start_time,
last_request_end_time,
s.logical_reads,
s.reads,
request_status,
request_owner_type,
objectid,
dbid,
a.number,
a.encrypted ,
a.blocking_session_id,
a.text
FROM
sys.dm_tran_locks l
JOIN sys.dm_exec_sessions s ON l.request_session_id = s.session_id
LEFT JOIN
(
SELECT *
FROM sys.dm_exec_requests r
CROSS APPLY sys.dm_exec_sql_text(sql_handle)
) a ON s.session_id = a.session_id
WHERE
s.session_id > 50
You need to append form
itself to body
too:
$form = $("<form></form>");
$form.append('<input type="button" value="button">');
$('body').append($form);
With postgres 9.3 use -> for object access. 4 example
seed.rb
se = SmartElement.new
se.data =
{
params:
[
{
type: 1,
code: 1,
value: 2012,
description: 'year of producction'
},
{
type: 1,
code: 2,
value: 30,
description: 'length'
}
]
}
se.save
rails c
SELECT data->'params'->0 as data FROM smart_elements;
returns
data
----------------------------------------------------------------------
{"type":1,"code":1,"value":2012,"description":"year of producction"}
(1 row)
You can continue nesting
SELECT data->'params'->0->'type' as data FROM smart_elements;
return
data
------
1
(1 row)
If min = 5
, and max = 10
, and Math.random()
returns (almost) 1.0, the generated number will be (almost) 15, which is clearly more than the chosen max
.
Relatedly, this is why every random number API should let you specify min and max explicitly. You shouldn't have to write error-prone maths that are tangential to your problem domain.
Adding to exebook's response, the mathematics usage of the keyword let also encapsulates well the scoping implications of let
when used in Javascript/ES6. Specifically, just as the following ES6 code is not aware of the assignment in braces of toPrint
when it prints out the value of 'Hello World'
,
let toPrint = 'Hello World.';
{
let toPrint = 'Goodbye World.';
}
console.log(toPrint); // Prints 'Hello World'
let as used in formalized mathematics (especially the writing of proofs) indicates that the current instance of a variable exists only for the scope of that logical idea. In the following example, x immediately gains a new identity upon entering the new idea (usually these are concepts necessary to prove the main idea) and reverts immediately to the old x upon the conclusion of the sub-proof. Of course, just as in coding, this is considered somewhat confusing and so is usually avoided by choosing a different name for the other variable.
Let x be so and so...
Proof stuff
New Idea { Let x be something else ... prove something } Conclude New Idea
Prove main idea with old x
This question will get moved but you can do the following
which javac
or
cd /
find . -name 'javac'
look at sysinternals for a variety of tools to help you achieve that goal. psService for example would restart a service on a remote machine.
Another way to accomplish this is a combination of Justus Thane's and mklement0's answers. It doesn't make sense to do it this way when you look at a one liner example, but when you're trying to mass-edit a file or a bunch of filenames it comes in pretty handy:
$test = ' One for the money '
$option = [System.StringSplitOptions]::RemoveEmptyEntries
$($test.split(' ',$option)).foreach{$_}
This will come out as:
One
for
the
money
<asp:TextBox ID="TextBox1" runat="server" placeholder="mm/dd/yyyy" Textmode="Date" ReadOnly = "false"></asp:TextBox>
<asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" />
If globally installed then
"scripts": {
"start": "nodemon FileName.js(server.js)",
},
Make sure you have installed nodemon
globally:
npm install -g nodemon
Finally, if you are a Windows user, make sure that the security restriction of the Windows PowerShell is enabled.
Thanks all person who try to help in this post
I have ubuntu 13.10 and my chrome version is 34.0
For my situation this works
1.open developer tools in chrome(or use right click on your page and then select inspect element)
2.go to "Network" tab
3.find your ajax request in "Name Path" column
4.click on the specific ajax link
now you should see a new Panel in front of you request
in this panel select "Response" tab
Matching a URL in a text should not be so complex
(?:(?:(?:ftp|http)[s]*:\/\/|www\.)[^\.]+\.[^ \n]+)
You cannot directly create a table stored as a sequence file and insert text into it. You must do this:
Example:
CREATE TABLE test_txt(field1 int, field2 string)
ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t';
LOAD DATA INPATH '/path/to/file.tsv' INTO TABLE test_txt;
CREATE TABLE test STORED AS SEQUENCEFILE
AS SELECT * FROM test_txt;
DROP TABLE test_txt;
what about using the official API?
According to the API doc:
DESTROY: Removes the datepicker functionality completely. This will return the element back to its pre-init state.
Use:
$("#txtSearch").datepicker("destroy");
to restore the input to its normal behaviour and
$("#txtSearch").datepicker(/*options*/);
again to show the datapicker again.
The facade pattern provides a unified interface to the subsystem interface group. The facade defines a high-level interface, which simplifies the work with the subsystem.
It works for me for opening small text file... I didn't try in other file
protected void viewhelper(Intent intent) {
Uri a = intent.getData();
if (!a.toString().startsWith("content:")) {
return;
}
//Ok Let's do it
String content = readUri(a);
//do something with this content
}
here is the readUri(Uri uri) method
private String readUri(Uri uri) {
InputStream inputStream = null;
try {
inputStream = getContentResolver().openInputStream(uri);
if (inputStream != null) {
byte[] buffer = new byte[1024];
int result;
String content = "";
while ((result = inputStream.read(buffer)) != -1) {
content = content.concat(new String(buffer, 0, result));
}
return content;
}
} catch (IOException e) {
Log.e("receiver", "IOException when reading uri", e);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
Log.e("receiver", "IOException when closing stream", e);
}
}
}
return null;
}
I got it from this repository https://github.com/zhutq/android-file-provider-demo/blob/master/FileReceiver/app/src/main/java/com/demo/filereceiver/MainActivity.java
I modified some code so that it work.
Manifest file:
<activity android:name=".MainActivity">
<intent-filter >
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="*/*" />
</intent-filter>
</activity>
You need to add
@Override
protected void onCreate(Bundle savedInstanceState) {
/*
* Your OnCreate
*/
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
//VIEW"
if (Intent.ACTION_VIEW.equals(action) && type != null) {
viewhelper(intent); // Handle text being sent
}
}
map.at("key") throws exception if missing key
If k does not match the key of any element in the container, the function throws an out_of_range exception.
I think I just found a way to read MAC addresses without LOCATION permission: Run ip link
and parse its output. (you could probably do the similar by looking at this binary's source code)
Try this:
KeyValuePair<string,int> current = this.recent.SingleOrDefault(r => r.Key.Equals(dialog.FileName) == true);
if (current.Key == null)
this.recent.Add(new KeyValuePair<string,int>(dialog.FileName,0));
Intervention Image is an open source PHP image handling and manipulation library http://image.intervention.io/
This library provides a lot of useful features:
Basic Examples
// open an image file
$img = Image::make('public/foo.jpg');
// now you are able to resize the instance
$img->resize(320, 240);
// and insert a watermark for example
$img->insert('public/watermark.png');
// finally we save the image as a new file
$img->save('public/bar.jpg');
Method chaining:
$img = Image::make('public/foo.jpg')->resize(320, 240)->insert('public/watermark.png');
Tips: (In your case) https://laracasts.com/discuss/channels/laravel/file-upload-isvalid-returns-false
Tips 1:
// Tell the validator input file should be an image & check this validation
$rules = array(
'image' => 'mimes:jpeg,jpg,png,gif,svg // allowed type
|required // is required field
|max:2048' // max 2MB
|min:1024 // min 1MB
);
// validator Rules
$validator = Validator::make($request->only('image'), $rules);
// Check validation (fail or pass)
if ($validator->fails())
{
//Error do your staff
} else
{
//Success do your staff
};
Tips 2:
$this->validate($request, [
'input_img' =>
'required
|image
|mimes:jpeg,png,jpg,gif,svg
|max:1024',
]);
Function:
function imageUpload(Request $request) {
if ($request->hasFile('input_img')) { //check the file present or not
$image = $request->file('input_img'); //get the file
$name = "//what every you want concatenate".'.'.$image->getClientOriginalExtension(); //get the file extention
$destinationPath = public_path('/images'); //public path folder dir
$image->move($destinationPath, $name); //mve to destination you mentioned
$image->save(); //
}
}
Just use it like it was an object you defined. i.e.
$trends = $json_output->trends;
If you want to pass global variables into new scripts, you can create a python file that is only meant for holding global variables (e.g. globals.py). When you import this file at the top of the child script, it should have access to all of those variables.
If you are writing to these variables, then that is a different story. That involves concurrency and locking the variables, which I'm not going to get into unless you want.
How about this. using the modulo operator
if(a%b==0)
{
System.out.println("b is a factor of a. i.e. the result of a/b is going to be an integer");
}
else
{
System.out.println("b is NOT a factor of a");
}
I use this function which is saved in .bash_profile and it works a treat for me.
function show_hidden () {
{ defaults write com.apple.finder AppleShowAllFiles $1; killall -HUP Finder; }
}
How to use:
show_hidden true|false
You can use the NSDecimalRound function
I suggest you use TO_CHAR()
when converting to string. In order to do that, you need to build a date first.
SELECT TO_CHAR(TO_DATE(DAY||'-'||MONTH||'-'||YEAR, 'dd-mm-yyyy'), 'dd-mm-yyyy') AS FORMATTED_DATE
FROM
(SELECT EXTRACT( DAY FROM
(SELECT TO_DATE('1/21/2000', 'mm/dd/yyyy')
FROM DUAL
)) AS DAY, TO_NUMBER(EXTRACT( MONTH FROM
(SELECT TO_DATE('1/21/2000', 'mm/dd/yyyy') FROM DUAL
)), 09) AS MONTH, EXTRACT(YEAR FROM
(SELECT TO_DATE('1/21/2000', 'mm/dd/yyyy') FROM DUAL
)) AS YEAR
FROM DUAL
);
I have never encountered a C#->Java conversion tool. The syntax would be easy enough, but the frameworks are dramatically different. Even if there were a tool, I would strongly advise against it. I have worked on several "migration" projects, and can't say emphatically enough that while conversion seems like a good choice, conversion projects always always always turn in to money pits. It's not a shortcut, what you end up with is code that is not readable, and doesn't take advantage of the target language. speaking from personal experience, assume that a rewrite is the cheaper option.
EXPLAIN PLAN FOR
In SQL Developer, you don't have to use EXPLAIN PLAN FOR
statement. Press F10
or click the Explain Plan icon.
It will be then displayed in the Explain Plan window.
If you are using SQL*Plus then use DBMS_XPLAN.
For example,
SQL> EXPLAIN PLAN FOR
2 SELECT * FROM DUAL;
Explained.
SQL> SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);
PLAN_TABLE_OUTPUT
--------------------------------------------------------------------------
Plan hash value: 272002086
--------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
--------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 1 | 2 | 2 (0)| 00:00:01 |
| 1 | TABLE ACCESS FULL| DUAL | 1 | 2 | 2 (0)| 00:00:01 |
--------------------------------------------------------------------------
8 rows selected.
SQL>
If you are on a windows machine, there won't be any problems with uploading or writing to the specified folder path, except the syntactical errors.
But in case of Linux users, there is a workaround to this problem, even if there are no syntactical errors visible.
First of all, I am assuming that you are using this in a Linux environment and you need to upload something to your project folder in the public directory.
Even if you are having the write and read access to the project folder, PHP is not handled by the end user. It is and can be handled by a www-data
user, or group.
So in order to make this www-data
get access
first type in;
sudo chgrp "www-data" your_project_folder
once its done, if there is no write access to the following as well;
sudo chown g+w your_project_folder
That will do the trick in Linux.
Please, not that this is done in a Linux environment, with phpmyadmin, and mysql running.
@jk1 answer is perfect, since @igor Ganapolsky asked, why can't we use Mockito.mock here? i post this answer.
For that we have provide one setter method for myobj and set the myobj value with mocked object.
class MyClass {
MyInterface myObj;
public void abc() {
myObj.myMethodToBeVerified (new String("a"), new String("b"));
}
public void setMyObj(MyInterface obj)
{
this.myObj=obj;
}
}
In our Test class, we have to write below code
class MyClassTest {
MyClass myClass = new MyClass();
@Mock
MyInterface myInterface;
@test
testAbc() {
myclass.setMyObj(myInterface); //it is good to have in @before method
myClass.abc();
verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
}
}
Look at how Runtime.getRuntime().exec()
passes the String command to the ProcessBuilder
. It uses a tokenizer and explodes the command into individual tokens, then invokes exec(String[] cmdarray, ......)
which constructs a ProcessBuilder
.
If you construct the ProcessBuilder
with an array of strings instead of a single one, you'll get to the same result.
The ProcessBuilder
constructor takes a String...
vararg, so passing the whole command as a single String has the same effect as invoking that command in quotes in a terminal:
shell$ "command with args"
I faced the same problem due to illegal spaces in my entire code.
I fixed it by selecting one of these spaces and use find and replace
to replace all matches with regular spaces.
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main (){
int pid;
int status;
printf("Parent: %d\n", getpid());
pid = fork();
if (pid == 0){
printf("Child %d\n", getpid());
sleep(2);
exit(EXIT_SUCCESS);
}
//Comment from here to...
//Parent waits process pid (child)
waitpid(pid, &status, 0);
//Option is 0 since I check it later
if (WIFSIGNALED(status)){
printf("Error\n");
}
else if (WEXITSTATUS(status)){
printf("Exited Normally\n");
}
//To Here and see the difference
printf("Parent: %d\n", getpid());
return 0;
}
We use Sphinx in a Vertical Search project with 10.000.000 + of MySql records and 10+ different database . It has got very excellent support for MySQL and high performance on indexing , research is fast but maybe a little less than Lucene. However it's the right choice if you need quickly indexing every day and use a MySQL db.
For those who came here looking for the answer and didnt type 3306 wrong...If like myself, you have wasted hours with no luck searching for this answer, then possibly this may help.
If you are seeing this: (HY000/2002): No connection could be made because the target machine actively refused it
Then my understanding is that it cant connect for one of the following below. Now which..
1) is your wamp, mamp, etc icon GREEN? Either way, right-click the icon --> click tools --> test both the port used for Apache (typically 80) and for Mariadb (3307?). Should say 'It is correct' for both.
2) Error comes from a .php file. So, check your dbconnect.php.
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_pw";
$dbname = "your_dbname";
$port = "3307";
?>
Is your setup correct? Does your user exist? Do they have rights? Does port match the tested port in 1)? Doesn't have to be 3307 and user can be root. You can also left click the green icon --> click MariaDB and view used port as shown in the image below. All good? Positive? ok!
3) Error comes when you login to phpmyadmin. So, check your my.ini.
Open my.ini by left clicking the green icon --> click MariaDB -->
; The following options will be passed to all MariaDB clients
[client]
;password = your_password
port = 3307
socket = /tmp/mariadb.sock
; Here follows entries for some specific programs
; The MariaDB server
[wampmariadb64]
;skip-grant-tables
port = 3307
socket = /tmp/mariadb.sock
Make sure the ports match the port MariaDB is being testing on. Then finally..
[mysqld]
port = 3307
At the bottom of my.ini, make sure this port matches as well.
4) 1-3 done? restart your WAMP and cross your fingers!
struct TIME {
static var ti = mach_timebase_info()
static var k: Double = 1
static var mach_stamp: Double {
if ti.denom == 0 {
mach_timebase_info(&ti)
k = Double(ti.numer) / Double(ti.denom) * 1e-6
}
return Double(mach_absolute_time()) * k
}
static var stamp: Double { return NSDate.timeIntervalSinceReferenceDate() * 1000 }
}
do {
let mach_start = TIME.mach_stamp
usleep(200000)
let mach_diff = TIME.mach_stamp - mach_start
let start = TIME.stamp
usleep(200000)
let diff = TIME.stamp - start
print(mach_diff, diff)
}
In general, a developer should never throw a NullPointerException. This exception is thrown by the runtime when code attempts to dereference a variable who's value is null. Therefore, if your method wants to explicitly disallow null, as opposed to just happening to have a null value raise a NullPointerException, you should throw an IllegalArgumentException.
As everyone else said, be careful of naive Quicksort - that can have O(N^2) performance on sorted or nearly sorted data. Nevertheless, with an appropriate algorithm for choice of pivot (either random or median-of-three - see Choosing a Pivot for Quicksort), Quicksort will still work sanely.
In general, the difficulty with choosing algorithms such as insert sort is in deciding when the data is sufficiently out of order that Quicksort really would be quicker.
By using the Nuget Package Manager UI as mentioned above it helps to uninstall the nuget package first. I always have problems when going back on a nuget package version if I don't uninstall first. Some references are not cleaned properly. So I suggest the following workflow when installing an old nuget package through the Nuget Package Manager:
Good Luck :)
if (nfile.eof()) // Prompt data from the Priming read:
nfile >> CODE >> QTY >> PRICE;
else
{
/*used to check that the file is not empty*/
ofile << "empty file!!" << endl;
return 1;
}
.headerDivider {
border-left:1px solid #38546d;
border-right:1px solid #16222c;
height:80px;
position:absolute;
right:249px;
top:10px;
}
<div class="headerDivider"></div>
My problem was similar. I got a payload
POST request when a user clicked a button
from my slackbot. The Content-Type
was application/x-www-form-urlencoded
. I used Flask, Python3.
I tried this solution and it didn't work
@app.route('/process_data', methods=['POST'])
def process_data():
req_data = request.get_json(force=True)
language = req_data['language']
return 'The language value is: {}'.format(language)
My solution 1 was:
from urllib.parse import parse_qs
# Some code
@ app.route('/slack/request_handler', methods=['POST'])
def request_handler():
# request.get_data() returned a bytestring
# parse_qs() returned a dict from a bytestring. This dict has 1 pair
# I tried payload_dict.keys() to see what keys in the dict and it had one key only
payload_dict = parse_qs(request.get_data())
# Get the value of the key from payload_dict
# Value of the key from payload_dict is an array, length = 1
payload_dict_value_arr = payload_dict[b'payload']
# Get data from the index[0] of the array payload_dict_value_arr
data = payload_dict_value_arr[0]
# convert a string (representation of a Dict)) to a Dict
# Note that if you have single quotes as a part of your keys or values this will
# fail due to improper character replacement.
# This solution is only recommended if you have a strong aversion
# to the eval solution.
datajson = json.loads(data)
# get value of key "channel"
channel = datajson["channel"]
print(channel) {'id': 'D01ACC2E8S3', 'name': 'directmessage'}
My solution 2, a bit shorter:
@ app.route('/slack/request_handler', methods=['POST'])
def request_handler():
payload = request.form # return an ImmutableMultiDict with 1 pair
a1 = payload['payload'] # get value of key 'payload'
# Note that if you have single quotes as a part of your keys or values this will
# fail due to improper character replacement.
# convert a string (representation of a Dict)) to a Dict
a2 = json.loads(a1)
# get value of key "channel"
channel = a2["channel"]
print(channel) # {'id': 'D01ACC2E8S3', 'name': 'directmessage'}
If you can access boost library, maybe type_id_with_cvr() function is what you need, which can provide data type without removing const, volatile, & and && modifiers. Here is an simple example in C++11:
#include <iostream>
#include <boost/type_index.hpp>
int a;
int& ff()
{
return a;
}
int main() {
ff() = 10;
using boost::typeindex::type_id_with_cvr;
std::cout << type_id_with_cvr<int&>().pretty_name() << std::endl;
std::cout << type_id_with_cvr<decltype(ff())>().pretty_name() << std::endl;
std::cout << typeid(ff()).name() << std::endl;
}
Hope this is useful.
You can write DateTime? newdate = null;
I found a very basic example of List comparison at List Compare This example verifies the size first and then checks the availability of the particular element of one list in another.
An interface can never be dereferenced statically, e.g. ISomething.member
. An interface is always dereferenced via a variable that refers to an instance of a subclass of the interface. Thus, an interface reference can never know which subclass it refers to without an instance of its subclass.
Thus the closest approximation to a static method in an interface would be a non-static method that ignores "this", i.e. does not access any non-static members of the instance. At the low-level abstraction, every non-static method (after lookup in any vtable) is really just a function with class scope that takes "this" as an implicit formal parameter. See Scala's singleton object and interoperability with Java as evidence of that concept. And thus every static method is a function with class scope that does not take a "this" parameter. Thus normally a static method can be called statically, but as previously stated, an interface has no implementation (is abstract).
Thus to get closest approximation to a static method in an interface, is to use a non-static method, then don't access any of the non-static instance members. There would be no possible performance benefit any other way, because there is no way to statically link (at compile-time) a ISomething.member()
. The only benefit I see of a static method in an interface is that it would not input (i.e. ignore) an implicit "this" and thus disallow access to any of the non-static instance members. This would declare implicitly that the function that doesn't access "this", is immutate and not even readonly with respect to its containing class. But a declaration of "static" in an interface ISomething
would also confuse people who tried to access it with ISomething.member()
which would cause a compiler error. I suppose if the compiler error was sufficiently explanatory, it would be better than trying to educate people about using a non-static method to accomplish what they want (apparently mostly factory methods), as we are doing here (and has been repeated for 3 Q&A times on this site), so it is obviously an issue that is not intuitive for many people. I had to think about it for a while to get the correct understanding.
The way to get a mutable static field in an interface is use non-static getter and setter methods in an interface, to access that static field that in the subclass. Sidenote, apparently immutable statics can be declared in a Java interface with static final
.
You just need to initialize your NSMutableArray
NSMutableArray *myArray = [[NSMutableArray alloc] init];
The error you have is because -credential
without -computername
can't exist.
You can try this way:
Invoke-Command -Credential $migratorCreds -ScriptBlock ${function:Get-LocalUsers} -ArgumentList $xmlPRE,$migratorCreds -computername YOURCOMPUTERNAME
There's the NUMBERFORMATTER jQuery plugin, details below:
https://code.google.com/p/jquery-numberformatter/
From the above link:
This plugin is a NumberFormatter plugin. Number formatting is likely familiar to anyone who's worked with server-side code like Java or PHP and who has worked with internationalization.
EDIT: Replaced the link with a more direct one.
Eclipse can't work out what you want to run and since you've not run anything before, it can't try re-running that either.
Instead of clicking the green 'run' button, click the dropdown next to it and chose Run Configurations. On the Android tab, make sure it's set to your project. In the Target tab, set the tick box and options as appropriate to target your device. Then click Run. Keep an eye on your Console tab in Eclipse - that'll let you know what's going on. Once you've got your run configuration set, you can just hit the green 'run' button next time.
Sometimes getting everything to talk to your device can be problematic to begin with. Consider using an AVD (i.e. an emulator) as alternative, at least to begin with if you have problems. You can easily create one from the menu Window -> Android Virtual Device Manager within Eclipse.
To view the progress of your project being installed and started on your device, check the console. It's a panel within Eclipse with the tabs Problems/Javadoc/Declaration/Console/LogCat etc. It may be minimised - check the tray in the bottom right. Or just use Window/Show View/Console from the menu to make it come to the front. There are two consoles, Android and DDMS - there is a dropdown by its icon where you can switch.
I had to create a Function.
Use it as:
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
set "TextString= Purple Cows are flying in the Air Tonight "
echo REM ^^Notice there is whitespace at the start and end of the TextString
echo "!TextString!"
CALL:trimWhiteSpace "!TextString!" OutPutString
echo Resulting Trimmed Text: "!OutPutString!"
echo REM ^^Now there should be no White space at the start or end.
Exit /B
Add this to the bottom of your batch file:
:FUNCTIONS
@REM FUNCTIONS AREA
GOTO:EOF
EXIT /B
::TRIM FUNCTIONS AREA::
:: USAGE:
:: trimWhiteSpace "!InputText!" OutputText
:: Remember to use the "! on the input text, but NOT on the Output text.
:: The Following is Wrong: trimWhiteSpace "!InputText!" !OutputText!
:: ^^Because it has a ! around the OutPutText
:: Make Sure to add " around the InputText when running the call.
:: If you don't add the " then it will only accept the first word before a space.
::Example:
:: set "TextString= Purple Cows are flying in the Air Tonight "
:: echo REM ^^Notice there is whitespace at the start and end of the TextString
:: echo "!TextString!"
:: CALL:trimWhiteSpace "!TextString!" OutPutString
:: echo Resulting Trimmed Text: "!OutPutString!"
:: echo REM ^^Now there should be no White space at the start or end.
:trimWhiteSpace
set textToTrim=%~1
CALL:trimWhiteSpaceOnTheRight "!textToTrim!" OutPutString
SET textToTrim=!OutPutString!
CALL:trimWhiteSpaceOnTheLeft "!textToTrim!" OutPutString
SET %2=!OutPutString!
GOTO:EOF
:trimWhiteSpaceOnTheRight
set str=%~1
for /l %%a in (1,1,31) do if "!str:~-1!"==" " set str=!str:~0,-1!
SET %2=%str%
GOTO:EOF
:trimWhiteSpaceOnTheLeft
set str=%~1
for /f "tokens=* delims= " %%a in ("%str%") do set str=%%a
SET %2=%str%
GOTO:EOF
And remember you MUST add "SETLOCAL ENABLEDELAYEDEXPANSION" to the top of your batch file or else none of this will work properly.
SETLOCAL ENABLEDELAYEDEXPANSION
@REM # Remember to add this to the top of your batch file.
This is a start, I don't think it works exactly as you intend, but it at least produces a consistent result.
import java.io.File;
public class Main
{
public static void main(final String[] argv)
throws Exception
{
System.out.println(pathJoin());
System.out.println(pathJoin(""));
System.out.println(pathJoin("a"));
System.out.println(pathJoin("a", "b"));
System.out.println(pathJoin("a", "b", "c"));
System.out.println(pathJoin("a", "b", "", "def"));
}
public static String pathJoin(final String ... pathElements)
{
final String path;
if(pathElements == null || pathElements.length == 0)
{
path = File.separator;
}
else
{
final StringBuilder builder;
builder = new StringBuilder();
for(final String pathElement : pathElements)
{
final String sanitizedPathElement;
// the "\\" is for Windows... you will need to come up with the
// appropriate regex for this to be portable
sanitizedPathElement = pathElement.replaceAll("\\" + File.separator, "");
if(sanitizedPathElement.length() > 0)
{
builder.append(sanitizedPathElement);
builder.append(File.separator);
}
}
path = builder.toString();
}
return (path);
}
}
This is no more .NET Core vs. Mono. It's unified.
Update as of November 2020 - .NET 5 released that unifies .NET Framework and .NET Core
.NET and Mono will be unified under .NET 6 that would be released in November 2021
net6.0-ios
and net6.0-android
.net6.0-ios14
.Check below articles:
I was not allowed to install URL Rewrite in my environment, so, I found another path.
Adding this to my web.config added the error rewrite and worked on IIS 7.5:
<system.webServer>
<httpErrors errorMode="Custom" defaultResponseMode="File" defaultPath="C:\WebSites\yoursite\" >
<remove statusCode="403" subStatusCode="4" />
<error statusCode="403" subStatusCode="4" responseMode="File" path="redirectToHttps.html" />
</httpErrors>
Then, following the advice here: https://www.sslshopper.com/iis7-redirect-http-to-https.html
I configured the IIS website to require SSL and created the html file that does the redirect (redirectToHttps.html) upon the 403 (Forbidden) error:
<html>
<head><title>Redirecting...</title></head>
<script language="JavaScript">
function redirectHttpToHttps()
{
var httpURL= window.location.hostname + window.location.pathname + window.location.search;
var httpsURL= "https://" + httpURL;
window.location = httpsURL;
}
redirectHttpToHttps();
</script>
<body>
</body>
</html>
I hope someone finds this useful as I could not find all of the pieces in one place anywhere else.
Try adding this:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-resource.min.js"></script>
This stuff comes from ES file explorer
Just go into this app > settings
Then there is an option that says logging floating window, you just need to disable that and you will get rid of this infernal bubble for good
$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark`
ADD COLUMN `ping_status` INT(1) NOT NULL
AFTER `<TABLE COLUMN BEFORE THIS COLUMN>`";
I believe you need to have ADD COLUMN
and use AFTER
, not BEFORE
.
In case you want to place column at the beginning of a table, use the FIRST
statement:
$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark`
ADD COLUMN `ping_status` INT(1) NOT NULL
FIRST";
The problem is caused by the fact that the Model
's toArray()
method ignores any accessors which do not directly relate to a column in the underlying table.
As Taylor Otwell mentioned here, "This is intentional and for performance reasons." However there is an easy way to achieve this:
class EventSession extends Eloquent {
protected $table = 'sessions';
protected $appends = array('availability');
public function getAvailabilityAttribute()
{
return $this->calculateAvailability();
}
}
Any attributes listed in the $appends property will automatically be included in the array or JSON form of the model, provided that you've added the appropriate accessor.
Old answer (for Laravel versions < 4.08):
The best solution that I've found is to override the toArray()
method and either explicity set the attribute:
class Book extends Eloquent {
protected $table = 'books';
public function toArray()
{
$array = parent::toArray();
$array['upper'] = $this->upper;
return $array;
}
public function getUpperAttribute()
{
return strtoupper($this->title);
}
}
or, if you have lots of custom accessors, loop through them all and apply them:
class Book extends Eloquent {
protected $table = 'books';
public function toArray()
{
$array = parent::toArray();
foreach ($this->getMutatedAttributes() as $key)
{
if ( ! array_key_exists($key, $array)) {
$array[$key] = $this->{$key};
}
}
return $array;
}
public function getUpperAttribute()
{
return strtoupper($this->title);
}
}
You don't have to implement your own FIFO Queue, just look at the interface java.util.Queue and its implementations
To use Google Maps/Places APIs now, you're required to use an API Key. So the API URL will change from
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
to
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>
Syntax to change column name in MySql:
alter table table_name change old_column_name new_column_name data_type(size);
Example:
alter table test change LowSal Low_Sal integer(4);
Set a default input value as per this GitHub issue.
HTML
<input type="text" id="datetimepicker-input"></input>
jQuery
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate();
var output = d.getFullYear() + '/' +
(month<10 ? '0' : '') + month + '/' +
(day<10 ? '0' : '') + day;
$("#datetimepicker-input").val(output + " 00:01:00");
jsFiddle
JavaScript date source
EDIT - setLocalDate/setDate
var d = new Date();
var month = d.getMonth();
var day = d.getDate();
var year = d.getFullYear();
$('#startdatetime-from').datetimepicker({
language: 'en',
format: 'yyyy-MM-dd hh:mm'
});
$("#startdatetime-from").data('DateTimePicker').setLocalDate(new Date(year, month, day, 00, 01));
A major thing to watch out for is whether a button is Enabled or not. You can still click them and nothing will fall over and the element is there but it is not ready to be clicked on so just doesnt do anything.
I've been using webdriver and its taken me most of the day to figure this out!
The following method seems to work reliably (in my environment for one button!)
private void TryClick(By selector)
{
var wait = WaitUpTo(TimeSpan.FromSeconds(10));
var element = wait.Until(ExpectedConditions.ElementIsVisible((selector)));
//really important bit!
WaitUpTo(TimeSpan.FromSeconds(5))
.Until(d => element.Enabled);
element.Click();
}
you use it something like
TryClick(By.XPath("//button[contains(.//*,'Some Text')]"));
<select name="select_box" multiple>
<option>123</option>
<option>456</option>
<option>789</option>
</select>
As @hanleyhansen noted in a comment, as of version 0.18.1, the display.height
option is deprecated, and says "use display.max_rows
instead". So you just have to configure it like this:
pd.set_option('display.max_rows', 500)
See the Release Notes — pandas 0.18.1 documentation:
Deprecated display.height, display.width is now only a formatting option does not control triggering of summary, similar to < 0.11.0.
You could install $ gem install foreman
, and use foreman to start your server as defined in your Procfile
like:
web: bundle exec rails -p 10524
You can check foreman
gem docs here: https://github.com/ddollar/foreman for more info
The benefit of this approach is not only can you set/change the port in the config easily and that it doesn't require much code to be added but also you can add different steps in the Procfile
that foreman will run for you so you don't have to go though them each time you want to start you application something like:
bundle: bundle install
web: bundle exec rails -p 10524
...
...
Cheers
I've used Spring.NET in the past and had great success with it. I never noticed any substantial overhead with it, though the project we used it on was fairly heavy on its own. It only took a little time reading through the documentation to get it set up.
You can go to fullscreen when user allows it :)
<button id="goFS">Go fullscreen</button>
<script>
var goFS = document.getElementById("goFS");
goFS.addEventListener("click", function() {
const elem = document.documentElement;
if (elem.requestFullscreen) {elem.requestFullscreen()}
}, false);
</script>
If you're fine with rounding the number instead of truncating it, then it's just:
ROUND(column_name,decimals)
On SQL Server 2012, you can use the following stored procedure:
sp_columns '<table name>'
For example, given a database table named users:
sp_columns 'users'
Had the same problem running PHP 7.2. I had to do the following :
sudo apt-get install php7.2-xml
Use, CollectionUtils.isEmpty(Collection coll)
method which is Null-safe check if the specified collection is empty.
for this import org.apache.commons.collections.CollectionUtils
.
Maven dependency
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.0</version>
</dependency>
public class TestModels
{
public Dictionary<int, dynamic> sp = new Dictionary<int, dynamic>();
public TestModels()
{
sp.Add(0, new {name="Test One", age=5});
sp.Add(1, new {name="Test Two", age=7});
}
}
You can get that error if you have an object with the same name as the schema. For example:
create sequence s2;
begin
s2.a;
end;
/
ORA-06550: line 2, column 6:
PLS-00302: component 'A' must be declared
ORA-06550: line 2, column 3:
PL/SQL: Statement ignored
When you refer to S2.MY_FUNC2
the object name is being resolved so it doesn't try to evaluate S2 as a schema name. When you just call it as MY_FUNC2
there is no confusion, so it works.
The documentation explains name resolution. The first piece of the qualified object name - S2 here - is evaluated as an object on the current schema before it is evaluated as a different schema.
It might not be a sequence; other objects can cause the same error. You can check for the existence of objects with the same name by querying the data dictionary.
select owner, object_type, object_name
from all_objects
where object_name = 'S2';
for installing multiple packages, i am using a setup.py file with following code:
import sys
import subprocess
import pkg_resources
required = {'numpy','pandas','<etc>'}
installed = {pkg.key for pkg in pkg_resources.working_set}
missing = required - installed
if missing:
# implement pip as a subprocess:
subprocess.check_call([sys.executable, '-m', 'pip', 'install',*missing])
ALTER TABLE person ALTER COLUMN phone DROP NOT NULL;
More details in the manual: http://www.postgresql.org/docs/9.1/static/sql-altertable.html
By using a simple pattern based in ES6 WeakMaps is possible to obtain private member variables, reachable from the prototype functions.
Note : The usage of WeakMaps guarantees safety against memory leaks, by letting the Garbage Collector identify and discard unused instances.
// Create a private scope using an Immediately _x000D_
// Invoked Function Expression..._x000D_
let Person = (function() {_x000D_
_x000D_
// Create the WeakMap that will hold each _x000D_
// Instance collection's of private data_x000D_
let privateData = new WeakMap();_x000D_
_x000D_
// Declare the Constructor :_x000D_
function Person(name) {_x000D_
// Insert the private data in the WeakMap,_x000D_
// using 'this' as a unique acces Key_x000D_
privateData.set(this, { name: name });_x000D_
}_x000D_
_x000D_
// Declare a prototype method _x000D_
Person.prototype.getName = function() {_x000D_
// Because 'privateData' is in the same _x000D_
// scope, it's contents can be retrieved..._x000D_
// by using again 'this' , as the acces key _x000D_
return privateData.get(this).name;_x000D_
};_x000D_
_x000D_
// return the Constructor_x000D_
return Person;_x000D_
}());
_x000D_
A more detailed explanation of this pattern can be found here
Since Jackson v2.0, you can use @JsonFormat annotation directly on Object members;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm a z")
private Date date;
I've just wasted an hour on this. I tried everything - it turned out (and I can hardly believe this) that giving my cancel button and element id of cancel meant that any attempt to prevent event propagation would fail! I guess an HTML page must treat this as someone pressing ESC?
Try Using this query for searching special character records
SELECT *
FROM tableName
WHERE fieldName REGEXP '[^a-zA-Z0-9@:. \'\-`,\&]'
The answer I'd previously accepted didn't work. It still waited for responses. This does work though, taken from How do I make an asynchronous GET request in PHP?
function post_without_wait($url, $params)
{
foreach ($params as $key => &$val) {
if (is_array($val)) $val = implode(',', $val);
$post_params[] = $key.'='.urlencode($val);
}
$post_string = implode('&', $post_params);
$parts=parse_url($url);
$fp = fsockopen($parts['host'],
isset($parts['port'])?$parts['port']:80,
$errno, $errstr, 30);
$out = "POST ".$parts['path']." HTTP/1.1\r\n";
$out.= "Host: ".$parts['host']."\r\n";
$out.= "Content-Type: application/x-www-form-urlencoded\r\n";
$out.= "Content-Length: ".strlen($post_string)."\r\n";
$out.= "Connection: Close\r\n\r\n";
if (isset($post_string)) $out.= $post_string;
fwrite($fp, $out);
fclose($fp);
}
For future visitors.
As of now Android 4.2.2 platform includes Google Play services. Just use an emulator running Jelly Bean. Details can be found here:
Setup Google Play Services SDK
EDIT:
Another option is to use Genymotion (runs way faster)
EDIT 2:
As @gdw2 commented: "setting up the Google Play Services SDK does not install a working Google Play app -- it just enables certain services provided by the SDK"
After version 2.0 Genymotion does not come with Play Services by default, but it can be easily installed manually. Just download the right version from here and drag and drop into the virtual device (emulador).
It can be done simply using PGPASSWORD. I am using psql 9.5.10. In your case the solution would be
PGPASSWORD=password psql -U myuser < myscript.sql
"are there any issue we should expect from only storing and retreiving a money amount in a DOUBLE column ?"
It sounds like no rounding errors can be produced in your scenario and if there were, they would be truncated by the conversion to BigDecimal.
So I would say no.
However, there is no guarantee that some change in the future will not introduce a problem.
I got the Error even though i was catching the exception.
try {
bitmap = BitmapFactory.decodeStream(getAssets().open("kitten.jpg"));
} catch (IOException e) {
Log.e("blabla", "Error", e);
finish();
}
Issue was that the IOException wasn't imported
import java.io.IOException;
To install wheel packages in python 2.7x:
Install python 2.7x (i would recommend python 2.78) - download the appropriate python binary for your version of windows . You can download python 2.78 at this site https://www.python.org/download/releases/2.7.8/ -I would recommend installing the graphical Tk module, and including python 2.78 in the windows path (environment variables) during installation.
Install get-pip.py and setuptools Download the installer at https://bootstrap.pypa.io/get-pip.py Double click the above file to run it. It will install pip and setuptools [or update them, if you have an earlier version of either]
-Double click the above file and wait - it will open a black window and print will scroll across the screen as it downloads and installs [or updates] pip and setuptools --->when it finishes the window will close.
A-type cd c:\python27\scripts [or cd \scripts ]
B-type pip install -u Eg to install pyside, type pip install -u pyside
Wait - it will state 'downloading PySide or -->it will download and install the appropriate version of the python package [the one that corresponds to your version of python and windows.]
Note - if you have downloaded the .whl file and saved it locally on your hard drive, type in
pip install --no-index --find-links=localpathtowheelfile packagename
**to install a previously downloaded wheel package you need to type in the following command pip install --no-index --find-links=localpathtowheelfile packagename
I had the same issue, but I followed the following steps:-
You can add 1 to each example New = 5; old = 0;
(1+new) - (old+1) / (old +1) 5/ 1 * 100 ==> 500%
I had been working on this, and I was facing a problem using the responses provided here by different users. Problem was a white box behind my NavigationBar transparent image on iOS 13+
My solution is this one
if #available(iOS 13, *) {
navBar?.standardAppearance.backgroundColor = UIColor.clear
navBar?.standardAppearance.backgroundEffect = nil
navBar?.standardAppearance.shadowImage = UIImage()
navBar?.standardAppearance.shadowColor = .clear
navBar?.standardAppearance.backgroundImage = UIImage()
}
Hope this helps anyone with same problem
It's fine, the continue
statement relates to the enclosing loop, and your code should be equivalent to (avoiding such jump statements):
while (something = get_something()) {
if (something == A || something == B)
do_something();
}
But if you expect break
to exit the loop, as your comment suggest (it always tries again with another something, until it evaluates to false), you'll need a different structure.
For example:
do {
something = get_something();
} while (!(something == A || something == B));
do_something();
Change your configuration to this (add a slash):
RewriteCond %{HTTP_HOST} ^example.com$ [NC]
RewriteRule (.*) http://www.example.com/$1 [R=301,L]
Or the solution outlined below (proposed by @absiddiqueLive) will work for any domain:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
If you need to support http and https and preserve the protocol choice try the following:
RewriteRule ^login\$ https://www.%{HTTP_HOST}/login [R=301,L]
Where you replace login
with checkout.php
or whatever URL you need to support HTTPS on.
I'd argue this is a bad idea though. For the reasoning please read this answer.
Like this
css
body {
background-color : #484848;
margin: 0;
padding: 0;
}
h1 {
color : #000000;
text-align : center;
font-family: "SIMPSON";
}
form {
width: 300px;
margin: 0 auto;
}
Below is an example of multiple figures that I used recently in Latex. You need to call these packages
\usepackage{graphicx}
\usepackage{subfig})
\begin{figure}[H]%
\centering
\subfloat[Row1]{{\includegraphics[scale=.36]{1.png} }}%
\subfloat[Row2]{{\includegraphics[scale=.36]{2.png} }}%
\subfloat[Row3]{{\includegraphics[scale=.36]{3.png} }}%
\hfill
\subfloat[Row4]{{\includegraphics[scale=0.37]{4.png} }}%
\subfloat[Row5]{{\includegraphics[scale=0.37]{5.png} }}%
\caption{Multiple figures in latex.}%
\label{fig:MFL}%
\end{figure}
Note that the fields must be in the same order. If the Primary Key you are referencing is specified as (Application, ID) then your foreign key must reference (Application, ID) and NOT (ID, Application) as they are seen as two different keys.
Some addition to the top answer here https://stackoverflow.com/posts/13581526/revisions
.vmoptions
And you'll have something like this in the bottom right
Here's some sample code I used recently to do just that.
It opens a workbook, goes down the rows, if a condition is met it writes some data in the row. Finally it saves the modified file.
from xlutils.copy import copy # http://pypi.python.org/pypi/xlutils
from xlrd import open_workbook # http://pypi.python.org/pypi/xlrd
START_ROW = 297 # 0 based (subtract 1 from excel row number)
col_age_november = 1
col_summer1 = 2
col_fall1 = 3
rb = open_workbook(file_path,formatting_info=True)
r_sheet = rb.sheet_by_index(0) # read only copy to introspect the file
wb = copy(rb) # a writable copy (I can't read values out of this, only write to it)
w_sheet = wb.get_sheet(0) # the sheet to write to within the writable copy
for row_index in range(START_ROW, r_sheet.nrows):
age_nov = r_sheet.cell(row_index, col_age_november).value
if age_nov == 3:
#If 3, then Combo I 3-4 year old for both summer1 and fall1
w_sheet.write(row_index, col_summer1, 'Combo I 3-4 year old')
w_sheet.write(row_index, col_fall1, 'Combo I 3-4 year old')
wb.save(file_path + '.out' + os.path.splitext(file_path)[-1])
Subset sum problem can be solved in O(sum*n) using dynamic programming. Optimal substructure for subset sum is as follows:
SubsetSum(A, n, sum) = SubsetSum(A, n-1, sum) || SubsetSum(A, n-1, sum-set[n-1])
SubsetSum(A, n, sum) = 0, if sum > 0 and n == 0 SubsetSum(A, n, sum) = 1, if sum == 0
Here A is array of elements, n is the number of elements of array A and sum is the sum of elements in the subset.
Using this dp, you can solve for the number of subsets for the sum.
For getting subset elements, we can use following algorithm:
After filling dp[n][sum] by calling SubsetSum(A, n, sum), we recursively traverse it from dp[n][sum]. For cell being traversed, we store path before reaching it and consider two possibilities for the element.
1) Element is included in current path.
2) Element is not included in current path.
Whenever sum becomes 0, we stop the recursive calls and print current path.
void findAllSubsets(int dp[], int A[], int i, int sum, vector<int>& p) {
if (sum == 0) {
print(p);
return;
}
// If sum can be formed without including current element
if (dp[i-1][sum])
{
// Create a new vector to store new subset
vector<int> b = p;
findAllSubsets(dp, A, i-1, sum, b);
}
// If given sum can be formed after including
// current element.
if (sum >= A[i] && dp[i-1][sum-A[i]])
{
p.push_back(A[i]);
findAllSubsets(dp, A, i-1, sum-A[i], p);
}
}
For those using Codeigniter, add this below your sidebar menu,
<script>
$(document).ready(function () {
$(".nav li").removeClass("active");
var currentUrl = "<?php echo current_url(); ?>";
$('a[href="' + currentUrl + '"]').parents('li,ul').addClass('active');
});
</script>
If you have an java.awt.Image
, rezising it doesn't require any additional libraries. Just do:
Image newImage = yourImage.getScaledInstance(newWidth, newHeight, Image.SCALE_DEFAULT);
Ovbiously, replace newWidth
and newHeight
with the dimensions of the specified image.
Notice the last parameter: it tells to the runtime the algorithm you want to use for resizing.
There are algorithms that produce a very precise result, however these take a large time to complete.
You can use any of the following algorithms:
Image.SCALE_DEFAULT
: Use the default image-scaling algorithm.Image.SCALE_FAST
: Choose an image-scaling algorithm that gives higher priority to scaling speed than smoothness of the scaled image.Image.SCALE_SMOOTH
: Choose an image-scaling algorithm that gives higher priority to image smoothness than scaling speed.Image.SCALE_AREA_AVERAGING
: Use the Area Averaging image scaling algorithm.Image.SCALE_REPLICATE
: Use the image scaling algorithm embodied in the ReplicateScaleFilter
class.See the Javadoc for more info.
What you're doing is appending a "1" (the string) to your URL. If you want page 1.html link to page 2.html you need to take the 1 out of the string, add one to it, then reassemble the string.
Why not do something like this:
var url = 'http://mywebsite.com/1.html';
var pageNum = parseInt( url.split("/").pop(),10 );
var nextPage = 'http://mywebsite.com/'+(pageNum+1)+'.html';
nextPage will contain the url http://mywebsite.com/2.html in this case. Should be easy to put in a function if needed.
A self join is simply when you join a table with itself. There is no SELF JOIN
keyword, you just write an ordinary join where both tables involved in the join are the same table. One thing to notice is that when you are self joining it is necessary to use an alias for the table otherwise the table name would be ambiguous.
It is useful when you want to correlate pairs of rows from the same table, for example a parent - child relationship. The following query returns the names of all immediate subcategories of the category 'Kitchen'.
SELECT T2.name
FROM category T1
JOIN category T2
ON T2.parent = T1.id
WHERE T1.name = 'Kitchen'
w+
#include <stdio.h>
int main()
{
FILE *fp;
fp = fopen("test.txt", "w+"); //write and read mode
fprintf(fp, "This is testing for fprintf...\n");
rewind(fp); //rewind () function moves file pointer position to the beginning of the file.
char ch;
while((ch=getc(fp))!=EOF)
putchar(ch);
fclose(fp);
}
output
This is testing for fprintf...
test.txt
This is testing for fprintf...
w and r to form w+
#include <stdio.h>
int main()
{
FILE *fp;
fp = fopen("test.txt", "w"); //only write mode
fprintf(fp, "This is testing for fprintf...\n");
fclose(fp);
fp = fopen("test.txt", "r");
char ch;
while((ch=getc(fp))!=EOF)
putchar(ch);
fclose(fp);
}
output
This is testing for fprintf...
test.txt
This is testing for fprintf...
r+
test.txt
This is testing for fprintf...
#include<stdio.h>
int main()
{
FILE *fp;
fp = fopen("test.txt", "r+"); //read and write mode
char ch;
while((ch=getc(fp))!=EOF)
putchar(ch);
rewind(fp); //rewind () function moves file pointer position to the beginning of the file.
fprintf(fp, "This is testing for fprintf again...\n");
fclose(fp);
return 0;
}
output
This is testing for fprintf...
test.txt
This is testing for fprintf again...
r and w to form r+
test.txt
This is testing for fprintf...
#include<stdio.h>
int main()
{
FILE *fp;
fp = fopen("test.txt", "r");
char ch;
while((ch=getc(fp))!=EOF)
putchar(ch);
fclose(fp);
fp=fopen("test.txt","w");
fprintf(fp, "This is testing for fprintf again...\n");
fclose(fp);
return 0;
}
output
This is testing for fprintf...
test.txt
This is testing for fprintf again...
a+
test.txt
This is testing for fprintf...
#include<stdio.h>
int main()
{
FILE *fp;
fp = fopen("test.txt", "a+"); //append and read mode
char ch;
while((ch=getc(fp))!=EOF)
putchar(ch);
rewind(fp); //rewind () function moves file pointer position to the beginning of the file.
fprintf(fp, "This is testing for fprintf again...\n");
fclose(fp);
return 0;
}
output
This is testing for fprintf...
test.txt
This is testing for fprintf...
This is testing for fprintf again...
a and r to form a+
test.txt
This is testing for fprintf...
#include<stdio.h>
int main()
{
FILE *fp;
fp = fopen("test.txt", "a"); //append and read mode
char ch;
while((ch=getc(fp))!=EOF)
putchar(ch);
fclose(fp);
fp=fopen("test.txt","r");
fprintf(fp, "This is testing for fprintf again...\n");
fclose(fp);
return 0;
}
output
This is testing for fprintf...
test.txt
This is testing for fprintf...
This is testing for fprintf again...
You say that the matrices are the same dimensions, and yet you are trying to perform matrix multiplication on them. Multiplication of matrices with the same dimension is only possible if they are square. In your case, you get an assertion error, because the dimensions are not square. You have to be careful when multiplying matrices, as there are two possible meanings of multiply.
Matrix multiplication is where two matrices are multiplied directly. This operation multiplies matrix A of size [a x b] with matrix B of size [b x c] to produce matrix C of size [a x c]. In OpenCV it is achieved using the simple *
operator:
C = A * B
Element-wise multiplication is where each pixel in the output matrix is formed by multiplying that pixel in matrix A by its corresponding entry in matrix B. The input matrices should be the same size, and the output will be the same size as well. This is achieved using the mul()
function:
output = A.mul(B);
import json
def is_json(myjson):
try:
json_object = json.loads(myjson)
except ValueError as e:
return False
return True
Which prints:
print is_json("{}") #prints True
print is_json("{asdf}") #prints False
print is_json('{ "age":100}') #prints True
print is_json("{'age':100 }") #prints False
print is_json("{\"age\":100 }") #prints True
print is_json('{"age":100 }') #prints True
print is_json('{"foo":[5,6.8],"foo":"bar"}') #prints True
Convert a JSON string to a Python dictionary:
import json
mydict = json.loads('{"foo":"bar"}')
print(mydict['foo']) #prints bar
mylist = json.loads("[5,6,7]")
print(mylist)
[5, 6, 7]
Convert a python object to JSON string:
foo = {}
foo['gummy'] = 'bear'
print(json.dumps(foo)) #prints {"gummy": "bear"}
If you want access to low-level parsing, don't roll your own, use an existing library: http://www.json.org/
Great tutorial on python JSON module: https://pymotw.com/2/json/
sudo cpan JSON::XS
echo '{"foo":[5,6.8],"foo":"bar" bar}' > myjson.json
json_xs -t none < myjson.json
Prints:
, or } expected while parsing object/hash, at character offset 28 (before "bar}
at /usr/local/bin/json_xs line 183, <STDIN> line 1.
json_xs
is capable of syntax checking, parsing, prittifying, encoding, decoding and more:
If you are trying to cache the tiles that Google serves, that may be a violation of Google's Terms of Service (unless, under certain circumstances, if you've purchased their enterprise Maps API Premier). That's why gmapcatcher has it crossed off their list. See http://code.google.com/p/gmapcatcher/issues/detail?id=210.
At the gmapcatcher URL above, you will also find a shell script that can download tiles (or so its author says).
There are also other projects that try to make Google Maps available offline:
http://code.google.com/p/ogmaps/
http://code.google.com/p/gmapoffline/
Lastly, if Google Earth can meet your needs, then you can use that. Offline usage of Google Earth requires a Google Earth Enterprise license according to http://www.google.com/permissions/geoguidelines.html.
Note that the preceding page also says: "You may not scrape or otherwise export Content from Google Maps or Earth or save it for offline use." So if you try to cache tiles, that will almost certainly be considered (by Google, anyway) a violation of the Terms of Service.
It should work, however http://nginx.org/en/docs/http/ngx_http_core_module.html#alias says:
When location matches the last part of the directive’s value: it is better to use the root directive instead:
which would yield:
server {
listen 8080;
server_name www.mysite.com mysite.com;
error_log /home/www-data/logs/nginx_www.error.log;
error_page 404 /404.html;
location /public/doc/ {
autoindex on;
root /home/www-data/mysite;
}
location = /404.html {
root /home/www-data/mysite/static/html;
}
}
It probably means you've got carriage returns (different operating systems use different ways of signaling the end of line).
Use dos2unix
to fix the files or set the fileformats in vim:
set ffs=unix,dos
This is more or less a summary of three answers (by Sara Inés Calderón, klaxon and Gothburz), but as they all added something important, I consider it worth joining the solutions and adding some more explanation.
Considering your example, you can do calculations in your template using:
{{ 100 * (count/total) }}
However, this may result in a whole lot of decimal places, so using filters is a good way to go:
{{ 100 * (count/total) | number }}
By default, the number filter will leave up to three fractional digits, this is where the fractionSize argument comes in quite handy
({{ 100 * (count/total) | number:fractionSize }}
), which in your case would be:
{{ 100 * (count/total) | number:0 }}
This will also round the result already:
angular.module('numberFilterExample', [])_x000D_
.controller('ExampleController', ['$scope',_x000D_
function($scope) {_x000D_
$scope.val = 1234.56789;_x000D_
}_x000D_
]);
_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
<head> _x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
</head>_x000D_
<body ng-app="numberFilterExample">_x000D_
<table ng-controller="ExampleController">_x000D_
<tr>_x000D_
<td>No formatting:</td>_x000D_
<td>_x000D_
<span>{{ val }}</span>_x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>3 Decimal places:</td>_x000D_
<td>_x000D_
<span>{{ val | number }}</span> (default)_x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>2 Decimal places:</td>_x000D_
<td><span>{{ val | number:2 }}</span></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>No fractions: </td>_x000D_
<td><span>{{ val | number:0 }}</span> (rounded)</td>_x000D_
</tr>_x000D_
</table>_x000D_
</body>_x000D_
</html>
_x000D_
Last thing to mention, if you rely on an external data source, it probably is good practise to provide a proper fallback value (otherwise you may see NaN or nothing on your site):
{{ (100 * (count/total) | number:0) || 0 }}
Sidenote: Depending on your specifications, you may even be able to be more precise with your fallbacks/define fallbacks on lower levels already (e.g. {{(100 * (count || 10)/ (total || 100) | number:2)}}
). Though, this may not not always make sense..
[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("Age")]
public int required { get; set; }
[JsonProperty("Location")]
public string type { get; set; }
and Remove a "{"..,
strFieldString = strFieldString.Remove(0, strFieldString.IndexOf('{'));
DeserializeObject..,
optionsItem objActualField = JsonConvert.DeserializeObject<optionsItem(strFieldString);
Finding all possible paths is a hard problem, since there are exponential number of simple paths. Even finding the kth shortest path [or longest path] are NP-Hard.
One possible solution to find all paths [or all paths up to a certain length] from s
to t
is BFS, without keeping a visited
set, or for the weighted version - you might want to use uniform cost search
Note that also in every graph which has cycles [it is not a DAG] there might be infinite number of paths between s
to t
.
You're right. :before and :after pseudo content is not intended to work on replaced content like img
and input
elements. Adding a wrapping element and declare a font-family is one of the possibilities, as is using a background image. Or maybe a html5 placeholder text fits your needs:
<input name="username" placeholder="">
Browsers that don’t support the placeholder attribute will simply ignore it.
The before content selector selects the input: input[type="text"]:before
. You should select the wrapper: .wrapper:before
. See http://jsfiddle.net/allcaps/gA4rx/ .
I also added the placeholder suggestion where the wrapper is redundant.
.wrapper input[type="text"] {
position: relative;
}
input { font-family: 'FontAwesome'; } /* This is for the placeholder */
.wrapper:before {
font-family: 'FontAwesome';
color:red;
position: relative;
left: -5px;
content: "\f007";
}
<p class="wrapper"><input placeholder=" Username"></p>
Font Awesome uses the Unicode Private Use Area (PUA) to store icons. Other characters are not present and fall back to the browser default. That should be the same as any other input. If you define a font on input elements, then supply the same font as fallback for situations where us use an icon. Like this:
input { font-family: 'FontAwesome', YourFont; }
color
and fill
are separate aesthetics. Since you want to modify the color you need to use the corresponding scale:
d + scale_color_manual(values=c("#CC6666", "#9999CC"))
is what you want.
You can create table variables:
DECLARE @result1 TABLE (a INT, b INT, c INT)
INSERT INTO @result1
SELECT a, b, c
FROM table1
SELECT a AS val FROM @result1
UNION
SELECT b AS val FROM @result1
UNION
SELECT c AS val FROM @result1
This should be fine for what you need.
You need a json serializer to parse your content, probably you already have it, for your initial question on how to make a request, this might be an idea:
var baseAddress = "http://www.example.com/1.0/service/action";
var http = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress));
http.Accept = "application/json";
http.ContentType = "application/json";
http.Method = "POST";
string parsedContent = <<PUT HERE YOUR JSON PARSED CONTENT>>;
ASCIIEncoding encoding = new ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(parsedContent);
Stream newStream = http.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();
var response = http.GetResponse();
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
hope it helps,
you might want to have a look at NumPy Random sampling distributions
For Android, change the app name from the Android folder. In the AndroidManifest.xml file, in folder android/app/src/main
, let the android
label refer to the name you prefer, for example,
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
<application
`android:label="myappname"`
// The rest of the code
</application>
</manifest>
XmlDocument doc = new XmlDocument();
doc.LoadXml(str);
Where str
is your XML string. See the MSDN article for more info.
This excellent answer to a similar question (that I could not find before, unfortunately) helped me solve the problem.
Copying Content from referenced answer :
SQL Developer will look in the following location in this order for a tnsnames.ora file
$HOME/.tnsnames.ora
$TNS_ADMIN/tnsnames.ora
TNS_ADMIN lookup key in the registry
/etc/tnsnames.ora ( non-windows )
$ORACLE_HOME/network/admin/tnsnames.ora
LocalMachine\SOFTWARE\ORACLE\ORACLE_HOME_KEY
LocalMachine\SOFTWARE\ORACLE\ORACLE_HOMEIf your tnsnames.ora file is not getting recognized, use the following procedure:
Define an environmental variable called TNS_ADMIN to point to the folder that contains your tnsnames.ora file.
In Windows, this is done by navigating to Control Panel > System > Advanced system settings > Environment Variables...
In Linux, define the TNS_ADMIN variable in the .profile file in your home directory.Confirm the os is recognizing this environmental variable
From the Windows command line: echo %TNS_ADMIN%
From linux: echo $TNS_ADMIN
Restart SQL Developer Now in SQL Developer right click on Connections and select New Connection.... Select TNS as connection type in the drop down box. Your entries from tnsnames.ora should now display here.
Use this script
<script type="text/javascript">
window.onload = function() { window.print(); }
</script>
Since you have not mentioned what needs to be copied, I have left that section empty in the code below.
Also you don't need to move the email to the folder first and then run the macro in that folder. You can run the macro on the incoming mail and then move it to the folder at the same time.
This will get you started. I have commented the code so that you will not face any problem understanding it.
First paste the below mentioned code in the outlook module.
Then
When the new email arrives not only will the email move to the folder that you specify but data from it will be exported to Excel as well.
UNTESTED
Const xlUp As Long = -4162
Sub ExportToExcel(MyMail As MailItem)
Dim strID As String, olNS As Outlook.Namespace
Dim olMail As Outlook.MailItem
Dim strFileName As String
'~~> Excel Variables
Dim oXLApp As Object, oXLwb As Object, oXLws As Object
Dim lRow As Long
strID = MyMail.EntryID
Set olNS = Application.GetNamespace("MAPI")
Set olMail = olNS.GetItemFromID(strID)
'~~> Establish an EXCEL application object
On Error Resume Next
Set oXLApp = GetObject(, "Excel.Application")
'~~> If not found then create new instance
If Err.Number <> 0 Then
Set oXLApp = CreateObject("Excel.Application")
End If
Err.Clear
On Error GoTo 0
'~~> Show Excel
oXLApp.Visible = True
'~~> Open the relevant file
Set oXLwb = oXLApp.Workbooks.Open("C:\Sample.xls")
'~~> Set the relevant output sheet. Change as applicable
Set oXLws = oXLwb.Sheets("Sheet1")
lRow = oXLws.Range("A" & oXLApp.Rows.Count).End(xlUp).Row + 1
'~~> Write to outlook
With oXLws
'
'~~> Code here to output data from email to Excel File
'~~> For example
'
.Range("A" & lRow).Value = olMail.Subject
.Range("B" & lRow).Value = olMail.SenderName
'
End With
'~~> Close and Clean up Excel
oXLwb.Close (True)
oXLApp.Quit
Set oXLws = Nothing
Set oXLwb = Nothing
Set oXLApp = Nothing
Set olMail = Nothing
Set olNS = Nothing
End Sub
FOLLOWUP
To extract the contents from your email body, you can split it using SPLIT() and then parsing out the relevant information from it. See this example
Dim MyAr() As String
MyAr = Split(olMail.body, vbCrLf)
For i = LBound(MyAr) To UBound(MyAr)
'~~> This will give you the contents of your email
'~~> on separate lines
Debug.Print MyAr(i)
Next i
you can set Timeout in connection string (time for Establish connection between client and sql). commandTimeout is set per command but its default time is 30 secend
In my opinion the number one benefit of an IoC is the ability to centralize the configuration of your dependencies.
If you're currently using Dependency injection your code might look like this
public class CustomerPresenter
{
public CustomerPresenter() : this(new CustomerView(), new CustomerService())
{}
public CustomerPresenter(ICustomerView view, ICustomerService service)
{
// init view/service fields
}
// readonly view/service fields
}
If you used a static IoC class, as opposed to the, IMHO the more confusing, configuration files, you could have something like this:
public class CustomerPresenter
{
public CustomerPresenter() : this(IoC.Resolve<ICustomerView>(), IoC.Resolve<ICustomerService>())
{}
public CustomerPresenter(ICustomerView view, ICustomerService service)
{
// init view/service fields
}
// readonly view/service fields
}
Then, your Static IoC class would look like this, I'm using Unity here.
public static IoC
{
private static readonly IUnityContainer _container;
static IoC()
{
InitializeIoC();
}
static void InitializeIoC()
{
_container = new UnityContainer();
_container.RegisterType<ICustomerView, CustomerView>();
_container.RegisterType<ICustomerService, CustomerService>();
// all other RegisterTypes and RegisterInstances can go here in one file.
// one place to change dependencies is good.
}
}
With Xcode 6 the location of the simulator has changed to:
/Applications/Xcode.app/Contents/Developer/Applications/iOS Simulator.app
It can no longer be found here:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/iPhone Simulator.app
I hope this helps someone since I sometimes want to start the simulator from terminal.
You can chain class selectors without a space between them:
.a.b {
color: #666;
}
Note that, if it matters to you, IE6 treats .a.b
as .b
, so in that browser both div.a.b
and div.b
will have gray text. See this answer for a comparison between proper browsers and IE6.
To be more international (and not only US colored ;-) ) just replace in the code above by
-(NSNumber *) getNumber
{
NSString* localeIdentifier = [[NSLocale autoupdatingCurrentLocale] localeIdentifier];
NSLocale *l_en = [[NSLocale alloc] initWithLocaleIdentifier: localeIdentifier] ;
return [self getNumberWithLocale: [l_en autorelease] ];
}
You allocate a new Array (double the capacity, for instance), and move all elements to it.
Basically you need to check if the wordCount
is about to hit the wordList.size()
, when it does, create a new array with twice the length of the previous one, and copy all elements to it (create an auxiliary method to do this), and assign wordList
to your new array.
To copy the contents over, you could use System.arraycopy
, but I'm not sure that's allowed with your restrictions, so you can simply copy the elements one by one:
public String[] createNewArray(String[] oldArray){
String[] newArray = new String[oldArray.length * 2];
for(int i = 0; i < oldArray.length; i++) {
newArray[i] = oldArray[i];
}
return newArray;
}
Proceed.
In PostgreSQL, to get the average of multiple (2 to 8) columns in one row just define a set of seven functions called average(). Will produce the average of the non-null columns.
And then just
select *,(r1+r2+r3+r4+r5)/5.0,average(r1,r2,r3,r4,r5) from request;
req_id | r1 | r2 | r3 | r4 | r5 | ?column? | average
--------+----+----+----+----+----+--------------------+--------------------
R12673 | 2 | 5 | 3 | 7 | 10 | 5.4000000000000000 | 5.4000000000000000
R34721 | 3 | 5 | 2 | 1 | 8 | 3.8000000000000000 | 3.8000000000000000
R27835 | 1 | 3 | 8 | 5 | 6 | 4.6000000000000000 | 4.6000000000000000
(3 rows)
update request set r4=NULL where req_id='R34721';
UPDATE 1
select *,(r1+r2+r3+r4+r5)/5.0,average(r1,r2,r3,r4,r5) from request;
req_id | r1 | r2 | r3 | r4 | r5 | ?column? | average
--------+----+----+----+----+----+--------------------+--------------------
R12673 | 2 | 5 | 3 | 7 | 10 | 5.4000000000000000 | 5.4000000000000000
R34721 | 3 | 5 | 2 | | 8 | | 4.5000000000000000
R27835 | 1 | 3 | 8 | 5 | 6 | 4.6000000000000000 | 4.6000000000000000
(3 rows)
select *,(r3+r4+r5)/3.0,average(r3,r4,r5) from request;
req_id | r1 | r2 | r3 | r4 | r5 | ?column? | average
--------+----+----+----+----+----+--------------------+--------------------
R12673 | 2 | 5 | 3 | 7 | 10 | 6.6666666666666667 | 6.6666666666666667
R34721 | 3 | 5 | 2 | | 8 | | 5.0000000000000000
R27835 | 1 | 3 | 8 | 5 | 6 | 6.3333333333333333 | 6.3333333333333333
(3 rows)
Like this:
CREATE OR REPLACE FUNCTION AVERAGE (
V1 NUMERIC,
V2 NUMERIC)
RETURNS NUMERIC
AS $FUNCTION$
DECLARE
COUNT NUMERIC;
TOTAL NUMERIC;
BEGIN
COUNT=0;
TOTAL=0;
IF V1 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V1; END IF;
IF V2 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V2; END IF;
RETURN TOTAL/COUNT;
EXCEPTION WHEN DIVISION_BY_ZERO THEN RETURN NULL;
END
$FUNCTION$ LANGUAGE PLPGSQL;
CREATE OR REPLACE FUNCTION AVERAGE (
V1 NUMERIC,
V2 NUMERIC,
V3 NUMERIC)
RETURNS NUMERIC
AS $FUNCTION$
DECLARE
COUNT NUMERIC;
TOTAL NUMERIC;
BEGIN
COUNT=0;
TOTAL=0;
IF V1 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V1; END IF;
IF V2 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V2; END IF;
IF V3 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V3; END IF;
RETURN TOTAL/COUNT;
EXCEPTION WHEN DIVISION_BY_ZERO THEN RETURN NULL;
END
$FUNCTION$ LANGUAGE PLPGSQL;
CREATE OR REPLACE FUNCTION AVERAGE (
V1 NUMERIC,
V2 NUMERIC,
V3 NUMERIC,
V4 NUMERIC)
RETURNS NUMERIC
AS $FUNCTION$
DECLARE
COUNT NUMERIC;
TOTAL NUMERIC;
BEGIN
COUNT=0;
TOTAL=0;
IF V1 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V1; END IF;
IF V2 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V2; END IF;
IF V3 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V3; END IF;
IF V4 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V4; END IF;
RETURN TOTAL/COUNT;
EXCEPTION WHEN DIVISION_BY_ZERO THEN RETURN NULL;
END
$FUNCTION$ LANGUAGE PLPGSQL;
CREATE OR REPLACE FUNCTION AVERAGE (
V1 NUMERIC,
V2 NUMERIC,
V3 NUMERIC,
V4 NUMERIC,
V5 NUMERIC)
RETURNS NUMERIC
AS $FUNCTION$
DECLARE
COUNT NUMERIC;
TOTAL NUMERIC;
BEGIN
COUNT=0;
TOTAL=0;
IF V1 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V1; END IF;
IF V2 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V2; END IF;
IF V3 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V3; END IF;
IF V4 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V4; END IF;
IF V5 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V5; END IF;
RETURN TOTAL/COUNT;
EXCEPTION WHEN DIVISION_BY_ZERO THEN RETURN NULL;
END
$FUNCTION$ LANGUAGE PLPGSQL;
CREATE OR REPLACE FUNCTION AVERAGE (
V1 NUMERIC,
V2 NUMERIC,
V3 NUMERIC,
V4 NUMERIC,
V5 NUMERIC,
V6 NUMERIC)
RETURNS NUMERIC
AS $FUNCTION$
DECLARE
COUNT NUMERIC;
TOTAL NUMERIC;
BEGIN
COUNT=0;
TOTAL=0;
IF V1 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V1; END IF;
IF V2 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V2; END IF;
IF V3 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V3; END IF;
IF V4 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V4; END IF;
IF V5 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V5; END IF;
IF V6 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V6; END IF;
RETURN TOTAL/COUNT;
EXCEPTION WHEN DIVISION_BY_ZERO THEN RETURN NULL;
END
$FUNCTION$ LANGUAGE PLPGSQL;
CREATE OR REPLACE FUNCTION AVERAGE (
V1 NUMERIC,
V2 NUMERIC,
V3 NUMERIC,
V4 NUMERIC,
V5 NUMERIC,
V6 NUMERIC,
V7 NUMERIC)
RETURNS NUMERIC
AS $FUNCTION$
DECLARE
COUNT NUMERIC;
TOTAL NUMERIC;
BEGIN
COUNT=0;
TOTAL=0;
IF V1 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V1; END IF;
IF V2 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V2; END IF;
IF V3 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V3; END IF;
IF V4 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V4; END IF;
IF V5 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V5; END IF;
IF V6 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V6; END IF;
IF V7 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V7; END IF;
RETURN TOTAL/COUNT;
EXCEPTION WHEN DIVISION_BY_ZERO THEN RETURN NULL;
END
$FUNCTION$ LANGUAGE PLPGSQL;
CREATE OR REPLACE FUNCTION AVERAGE (
V1 NUMERIC,
V2 NUMERIC,
V3 NUMERIC,
V4 NUMERIC,
V5 NUMERIC,
V6 NUMERIC,
V7 NUMERIC,
V8 NUMERIC)
RETURNS NUMERIC
AS $FUNCTION$
DECLARE
COUNT NUMERIC;
TOTAL NUMERIC;
BEGIN
COUNT=0;
TOTAL=0;
IF V1 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V1; END IF;
IF V2 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V2; END IF;
IF V3 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V3; END IF;
IF V4 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V4; END IF;
IF V5 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V5; END IF;
IF V6 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V6; END IF;
IF V7 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V7; END IF;
IF V8 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V8; END IF;
RETURN TOTAL/COUNT;
EXCEPTION WHEN DIVISION_BY_ZERO THEN RETURN NULL;
END
$FUNCTION$ LANGUAGE PLPGSQL;
var
is optional. var
puts a variable in local scope. If a variable is defined without var
, it is in global scope and not deletable.
I thought that the non-deletable part was true at some point in time with a certain environment. I must have dreamed it.
Depending on your PHP configuration, this may be a easy as using:
$jsonData = json_decode(file_get_contents('https://chart.googleapis.com/chart?cht=p3&chs=250x100&chd=t:60,40&chl=Hello|World&chof=json'));
However, if allow_url_fopen
isn't enabled on your system, you could read the data via CURL as follows:
<?php
$curlSession = curl_init();
curl_setopt($curlSession, CURLOPT_URL, 'https://chart.googleapis.com/chart?cht=p3&chs=250x100&chd=t:60,40&chl=Hello|World&chof=json');
curl_setopt($curlSession, CURLOPT_BINARYTRANSFER, true);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, true);
$jsonData = json_decode(curl_exec($curlSession));
curl_close($curlSession);
?>
Incidentally, if you just want the raw JSON data, then simply remove the json_decode
.
In swift 4 and autoLayout, you can use sectionInset like this:
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
layout.itemSize = CGSize(width: (view.frame.width-40)/2, height: (view.frame.width40)/2) // item size
layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10) // here you can add space to 4 side of item
collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) // set layout to item
collectionView?.register(ProductCategoryCell.self, forCellWithReuseIdentifier: cellIdentifier) // registerCell
collectionView?.backgroundColor = .white // background color of UICollectionView
view.addSubview(collectionView!) // add UICollectionView to view
The follows is often used:
select field_SQ.nextval from dual;
select field_SQ.currval from DUAL;
However the following is able to change the sequence to what you expected. The 1
can be an integer (negative or positive)
alter sequence field_SQ increment by 1 minvalue 0
After creating virtual environment copy the activate.bat file from Script folder of python and paste to it your environment and open cmd from your virtual environment and run activate.bat file.enter image description here
It is even funnier when you are doing it with inputs, because they should be bound. If you are interested in how to do it in Vue2 with options to insert and delete, please see an example:
please have a look an js fiddle
new Vue({_x000D_
el: '#app',_x000D_
data: {_x000D_
finds: [] _x000D_
},_x000D_
methods: {_x000D_
addFind: function () {_x000D_
this.finds.push({ value: 'def' });_x000D_
},_x000D_
deleteFind: function (index) {_x000D_
console.log(index);_x000D_
console.log(this.finds);_x000D_
this.finds.splice(index, 1);_x000D_
}_x000D_
}_x000D_
});
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>_x000D_
<div id="app">_x000D_
<h1>Finds</h1>_x000D_
<div v-for="(find, index) in finds">_x000D_
<input v-model="find.value">_x000D_
<button @click="deleteFind(index)">_x000D_
delete_x000D_
</button>_x000D_
</div>_x000D_
_x000D_
<button @click="addFind">_x000D_
New Find_x000D_
</button>_x000D_
_x000D_
<pre>{{ $data }}</pre>_x000D_
</div>
_x000D_
Just use "justify-content-center" in the row's class attribute.
<div class="container">
<div class="row justify-content-center">
<h1>This is a header</h1>
</div>
</div>
import serial
ser = serial.Serial(0) # open first serial port
print ser.portstr # check which port was really used
ser.write("hello") # write a string
ser.close() # close port
use https://pythonhosted.org/pyserial/ for more examples
Numpy will be suitable for most people, but you can also do matrices in Sympy
Try running these commands at http://live.sympy.org/
M = Matrix([[1, 3], [-2, 3]])
M
M**-1
For fun, try M**(1/2)
>>> mask = df['ids'].str.contains('ball')
>>> mask
0 True
1 True
2 False
3 True
Name: ids, dtype: bool
>>> df[mask]
ids vals
0 aball 1
1 bball 2
3 fball 4