I Solved in this way
@Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onBackPressed(){
Intent backMainTest = new Intent(this,MainTest.class);
startActivity(backMainTest);
finish();
}
Instead of importing the logout_view
function, you should provide a string in your urls.py
file:
So not (r'^login/', login_view),
but (r'^login/', 'login.views.login_view'),
That is the standard way of doing things. Then you can access the URL in your templates using:
{% url login.views.login_view %}
I find the existing answers a little confusing, because they only indirectly indicate the essential mystifying thing in the code example: both* the "print i" and the "next(a)" are causing their results to be printed.
Since they're printing alternating elements of the original sequence, and it's unexpected that the "next(a)" statement is printing, it appears as if the "print i" statement is printing all the values.
In that light, it becomes more clear that assigning the result of "next(a)" to a variable inhibits the printing of its' result, so that just the alternate values that the "i" loop variable are printed. Similarly, making the "print" statement emit something more distinctive disambiguates it, as well.
(One of the existing answers refutes the others because that answer is having the example code evaluated as a block, so that the interpreter is not reporting the intermediate values for "next(a)".)
The beguiling thing in answering questions, in general, is being explicit about what is obvious once you know the answer. It can be elusive. Likewise critiquing answers once you understand them. It's interesting...
There is a distinction between the conditional operators && and || and the boolean operators & and |. Mainly it is a difference of precendence (which operators get evaluated first) and also the && and || are 'escaping'. This means that is a sequence such as...
cond1 && cond2 && cond3
If cond1 is false, neither cond2 or cond3 are evaluated as the code rightly assumes that no matter what their value, the expression cannot be true. Likewise...
cond1 || cond2 || cond3
If cond1 is true, neither cond2 or cond3 are evaluated as the expression must be true no matter what their value is.
The bitwise counterparts, & and | are not escaping.
Hope that helps.
For MVC developers,
This is strange but Logger.getLogger("global")
does not work in my setup (as well as Logger.getLogger(Logger.GLOBAL_LOGGER_NAME)
).
However Logger.getLogger("")
does the job well.
Hope this info also helps somebody...
You can use the simple not flag to validate that. Example
if !@objectname
This will return true if @objectname is nil. You should not use dot operator or a nil value, else it will throw
*** NoMethodError Exception: undefined method `isNil?' for nil:NilClass
An ideal nil check would be like:
!@objectname || @objectname.nil? || @objectname.empty?
It looks like you are willing to create a temporary Map
, so I'd do it like this:
Map tmp = new HashMap(patch);
tmp.keySet().removeAll(target.keySet());
target.putAll(tmp);
Here, patch
is the map that you are adding to the target
map.
Thanks to Louis Wasserman, here's a version that takes advantage of the new methods in Java 8:
patch.forEach(target::putIfAbsent);
Thanks to @Arraxas's anwser, I customized the arrow and make the input
element auto-adaptive to the select
element, and it looks good on Chrome, Firefox of my Android mobile phone (set color:transparent
for select
and some color for option
to hide text display of the select
because the input
and .combobox div:after
cannot completely cover select
).
/* https://stackoverflow.com/questions/13694271/modify-select-so-only-the-first-one-is-gray/41941056#41941056
select option:first-child, */
.combobox select, .combobox select option { color: #000000; }
.combobox select:invalid, .combobox select option[value=""] { color:grey; }
.combobox {position:absolute; left:80px; top:6px;}
.combobox>div { position:relative; font-size:1em; }
.combobox select {
font-size:inherit; color:transparent;
padding:0; -moz-appearance:none; -webkit-appearance:none; appearance:none;
border:1px solid blueviolet;
}
.combobox input {
position:absolute;top:1px;left:0px; text-overflow:ellipsis;
box-sizing:border-box; padding:0px; margin:0px; height:calc(100% - 1px); width:calc(100% - 20px);
border:1px solid blueviolet; border-right:none; border-top:none;
}
.combobox>div:after{
position:absolute; top:0px; right:0px; height:100%; width:20px;
box-sizing:border-box; content:"?"; border:1px solid blueviolet; pointer-events:none;
display:flex; flex-direction:row; align-items:center; justify-content:center;
}
.combobox select:focus, .combobox input:focus {outline:none;}
_x000D_
<!-- mandatory benefits/social security/welfare -->
<div class="combobox"><div>
<select id=MandatoryBenefits onchange="this.nextElementSibling.value=this.value" required>
<option value="" selected>Select ...</option>
<option value="Pension">Pension %</option>
<option value="Medical">Medical %</option>
<option value="Unemployment">Unemployment %</option>
<option value="Injury">Injury %</option>
<option value="Maternity">Maternity %</option>
<option value="Serious Illness">Serious Illness %</option>
<option value="Housing Fund">Housing Fund %</option>
</select>
<input type="text" value="" onchange="this.previousElementSibling.selectedIndex=0"
oninput="this.previousElementSibling.options[0].value=this.value; this.previousElementSibling.options[0].innerHTML=this.value" />
</div></div>
_x000D_
online demo (@jsbin)
This looks like a problem with line endings in your code. If you're going to be using all these other scientific packages, you may as well use Pandas for the CSV reading part, which is both more robust and more useful than just the csv
module:
import pandas
colnames = ['year', 'name', 'city', 'latitude', 'longitude']
data = pandas.read_csv('test.csv', names=colnames)
If you want your lists as in the question, you can now do:
names = data.name.tolist()
latitude = data.latitude.tolist()
longitude = data.longitude.tolist()
You'll want to use a udf as below
from pyspark.sql.types import IntegerType
from pyspark.sql.functions import udf
def func(fruit1, fruit2):
if fruit1 == None or fruit2 == None:
return 3
if fruit1 == fruit2:
return 1
return 0
func_udf = udf(func, IntegerType())
df = df.withColumn('new_column',func_udf(df['fruit1'], df['fruit2']))
Another interesting usecase for split in Hive is when, for example, a column ipname
in the table has a value "abc11.def.ghft.com" and you want to pull "abc11" out:
SELECT split(ipname,'[\.]')[0] FROM tablename;
private void button1_Click(object sender, EventArgs e)
{
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1] = "http://csharp.net-informations.com";
xlWorkBook.SaveAs("csharp-Excel.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
MessageBox.Show("Excel file created , you can find the file c:\\csharp-Excel.xls");
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
The above code is taken directly off csharp.net please take a look on the site.
Maybe this is dumb, but I think kids would intuitively grasp it -- the cartoon that started off the whole "What’s your favorite “programmer” cartoon?" at What's your favorite "programmer" cartoon?.
E.g. Jason Fox of Foxtrot writes code on the board that does a loop.
Possible point of interest: programming might help you out of trouble some time...
You can access user data directly in the twig template without requesting anything in the controller. The user is accessible like that : app.user
.
Now, you can access every property of the user. For example, you can access the username like that : app.user.username
.
Warning, if the user is not logged, the app.user
is null.
If you want to check if the user is logged, you can use the is_granted
twig function. For example, if you want to check if the user has ROLE_ADMIN
, you just have to do is_granted("ROLE_ADMIN")
.
So, in every of your pages you can do :
{% if is_granted("ROLE") %}
Hi {{ app.user.username }}
{% endif %}
I have written a .bat file to copy and paste file to a temporary folder and make it zip and transfer into a smb mount point, Hope this would help,
@echo off
if not exist "C:\Temp Backup\" mkdir "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%"
if not exist "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\ZIP" mkdir "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\ZIP"
if not exist "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\Logs" mkdir "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\Logs"
xcopy /s/e/q "C:\Source" "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%"
Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\Logs"
"C:\Program Files (x86)\WinRAR\WinRAR.exe" a "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\ZIP\ZIP_Backup_%date:~-4,4%_%date:~-10,2%_%date:~-7,2%.rar" "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\TELIUM"
"C:\Program Files (x86)\WinRAR\WinRAR.exe" a "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\ZIP\ZIP_Backup_Log_%date:~-4,4%_%date:~-10,2%_%date:~-7,2%.rar" "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\Logs"
NET USE \\IP\IPC$ /u:IP\username password
ROBOCOPY "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\ZIP" "\\IP\Backup Folder" /z /MIR /unilog+:"C:\backup_log_%date:~-4,4%%date:~-10,2%%date:~-7,2%.log"
NET USE \\172.20.10.103\IPC$ /D
RMDIR /S /Q "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%"
adding a br tag between the divs worked. add br tag between two divs that are display:table-row in a parent with display:table
To display each content, I use:
mylist = ['foo', 'bar']
indexval = 0
for i in range(len(mylist)):
print(mylist[indexval])
indexval += 1
Example of using in a function:
def showAll(listname, startat):
indexval = startat
try:
for i in range(len(mylist)):
print(mylist[indexval])
indexval = indexval + 1
except IndexError:
print('That index value you gave is out of range.')
Hope I helped.
There is no way to know that the two members of the options
array came from variables named size
and color
.
They are also not necessarily called that exclusively, any variable could also point to that array.
var notSize = size;
console.log(options[0]); // It is `size` or `notSize`?
One thing you can do is use an object there instead...
var options = {
size: size,
color: color
}
Then you could access options.size
or options.color
.
It is the difference between greedy and non-greedy quantifiers.
Consider the input 101000000000100
.
Using 1.*1
, *
is greedy - it will match all the way to the end, and then backtrack until it can match 1
, leaving you with 1010000000001
.
.*?
is non-greedy. *
will match nothing, but then will try to match extra characters until it matches 1
, eventually matching 101
.
All quantifiers have a non-greedy mode: .*?
, .+?
, .{2,6}?
, and even .??
.
In your case, a similar pattern could be <([^>]*)>
- matching anything but a greater-than sign (strictly speaking, it matches zero or more characters other than >
in-between <
and >
).
Solution A:
This combination of constraints should guarantee that TInterface
is an interface:
class example<TInterface, TStruct>
where TStruct : struct, TInterface
where TInterface : class
{ }
It requires a single struct TStruct
as a Witness to proof that TInterface
is a struct.
You can use single struct as a witness for all your non-generic types:
struct InterfaceWitness : IA, IB, IC
{
public int DoA() => throw new InvalidOperationException();
//...
}
Solution B: If you don't want to make structs as witnesses you can create an interface
interface ISInterface<T>
where T : ISInterface<T>
{ }
and use a constraint:
class example<TInterface>
where TInterface : ISInterface<TInterface>
{ }
Implementation for interfaces:
interface IA :ISInterface<IA>{ }
This solves some of the problems, but requires trust that noone implements ISInterface<T>
for non-interface types, but that is pretty hard to do accidentally.
As suggested by Guido García in their answer here:
import java.util.HashMap;
public class CaseInsensitiveMap extends HashMap<String, String> {
@Override
public String put(String key, String value) {
return super.put(key.toLowerCase(), value);
}
// not @Override because that would require the key parameter to be of type Object
public String get(String key) {
return super.get(key.toLowerCase());
}
}
Or
I believe the official way is still to go thorugh codecvt
facets (you need some sort of locale-aware translation), as in
resultCode = use_facet<codecvt<char, wchar_t, ConversionState> >(locale).
in(stateVar, scratchbuffer, scratchbufferEnd, from, to, toLimit, curPtr);
or something like that, I don't have working code lying around. But I'm not sure how many people these days use that machinery and how many simply ask for pointers to memory and let ICU or some other library handle the gory details.
If your source code name is HelloWorld.java, your compiled code will be HelloWorld.class
.
You will get that error if you call it using:
java HelloWorld.class
Instead, use this:
java HelloWorld
I think this solution is handy if you can test the value of the error field later. This is also applicable by creating a temporary table and returning a list of errors.
DROP PROCEDURE IF EXISTS $procName;
DELIMITER //
CREATE PROCEDURE $procName($params)
BEGIN
DECLARE error INT DEFAULT 0;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET error = 1;
SELECT
$fields
FROM $tables
WHERE $where
ORDER BY $sorting LIMIT 1
INTO $vars;
IF error = 0 THEN
SELECT $vars;
ELSE
SELECT 1 AS error;
SET @error = 0;
END IF;
END//
CALL $procName($effp);
The most efficient selector you can use is an attribute selector.
input[name="btnPage"]:hover {/*your css here*/}
Here's a live demo: http://tinkerbin.com/3G6B93Cb
SurfaceView
probably does not work like a regular View
in this regard.
Instead, do the following:
SurfaceView
inside of a
FrameLayout
or RelativeLayout
in
your layout XML file, since both of
those allow stacking of widgets on
the Z-axisView
classFrameLayout
or
RelativeLayout
, but have it appear
after the SurfaceView
This will cause your custom View
class to appear to float above the SurfaceView
.
See here for a sample project that layers popup panels above a SurfaceView
used for video playback.
Express 4.x
To get a URL parameter's value, use req.params
app.get('/p/:tagId', function(req, res) {
res.send("tagId is set to " + req.params.tagId);
});
// GET /p/5
// tagId is set to 5
If you want to get a query parameter ?tagId=5
, then use req.query
app.get('/p', function(req, res) {
res.send("tagId is set to " + req.query.tagId);
});
// GET /p?tagId=5
// tagId is set to 5
Express 3.x
URL parameter
app.get('/p/:tagId', function(req, res) {
res.send("tagId is set to " + req.param("tagId"));
});
// GET /p/5
// tagId is set to 5
Query parameter
app.get('/p', function(req, res) {
res.send("tagId is set to " + req.query("tagId"));
});
// GET /p?tagId=5
// tagId is set to 5
I stumbled upon this question when I ran into the same issue. The root cause of my issue was an incorrectly-configured app pool. It was set for 2.0 inadvertently, when it needed to be set to 4.0. The answer at the following link helped me uncover this issue: http://forums.iis.net/t/1160143.aspx
To reduce the required packages to install you just need
apt-get install -y \
libfreetype6-dev \
libxft-dev && \
pip install matplotlib
and you will get the following packages locally installed
Collecting matplotlib
Downloading matplotlib-2.2.0-cp35-cp35m-manylinux1_x86_64.whl (12.5MB)
Collecting pytz (from matplotlib)
Downloading pytz-2018.3-py2.py3-none-any.whl (509kB)
Collecting python-dateutil>=2.1 (from matplotlib)
Downloading python_dateutil-2.6.1-py2.py3-none-any.whl (194kB)
Collecting pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 (from matplotlib)
Downloading pyparsing-2.2.0-py2.py3-none-any.whl (56kB)
Requirement already satisfied: six>=1.10 in /opt/conda/envs/pytorch-py35/lib/python3.5/site-packages (from matplotlib)
Collecting cycler>=0.10 (from matplotlib)
Downloading cycler-0.10.0-py2.py3-none-any.whl
Collecting kiwisolver>=1.0.1 (from matplotlib)
Downloading kiwisolver-1.0.1-cp35-cp35m-manylinux1_x86_64.whl (949kB)
Requirement already satisfied: numpy>=1.7.1 in /opt/conda/envs/pytorch-py35/lib/python3.5/site-packages (from matplotlib)
Requirement already satisfied: setuptools in /opt/conda/envs/pytorch-py35/lib/python3.5/site-packages/setuptools-27.2.0-py3.5.egg (from kiwisolver>=1.0.1->matplotlib)
Installing collected packages: pytz, python-dateutil, pyparsing, cycler, kiwisolver, matplotlib
Successfully installed cycler-0.10.0 kiwisolver-1.0.1 matplotlib-2.2.0 pyparsing-2.2.0 python-dateutil-2.6.1 pytz-2018.3
virtualenvwrapper instructions
As indicated in the accepted answer, the root cause is likely a homebrew update that means your virtualenv symlinks are pointing at broken python paths - see details here.
For each virtual env, you need to reassign the symlinks to point at the correct python path (in brew cellar). Here is how to do it with virtualenvwrapper. Here I am updating a virtual env called "my-example-env".
cd ~/PYTHON_ENVS
find ./my-example-env -type l -delete
mkvirtualenv my-example-env
All done.
If you're using Express, then you can use its compress method as part of the configuration:
var express = require('express');
var app = express.createServer();
app.use(express.compress());
And you can find more on compress here: http://expressjs.com/api.html#compress
And if you're not using Express... Why not, man?! :)
NOTE: (thanks to @ankitjaininfo) This middleware should be one of the first you "use" to ensure all responses are compressed. Ensure that this is above your routes and static handler (eg. how I have it above).
NOTE: (thanks to @ciro-costa) Since express 4.0, the express.compress
middleware is deprecated. It was inherited from connect 3.0 and express no longer includes connect 3.0. Check Express Compression for getting the middleware.
The answer given by Simon works fine for me but you have to do it in the right sequence: First you have to be in the server that you want to insert data into which is [DATABASE.WINDOWS.NET].[basecampdev] in your case.
You can try to see if you can select some data out of the Invoice table to make sure you have access.
Select top 10 * from [DATABASE.WINDOWS.NET].[basecampdev].[dbo].[invoice]
Secondly, execute the query given by Simon in order to link to a different server. This time use the other server:
EXEC sp_addlinkedserver [BC1-PC]; -- this will create a link tempdb that you can access from where you are
GO
USE tempdb;
GO
CREATE SYNONYM MyInvoice FOR
[BC1-PC].testdabse.dbo.invoice; -- Make a copy of the table and data that you can use
GO
Now just do your insert statement.
INSERT INTO [DATABASE.WINDOWS.NET].[basecampdev].[dbo].[invoice]
([InvoiceNumber]
,[TotalAmount]
,[IsActive]
,[CreatedBy]
,[UpdatedBy]
,[CreatedDate]
,[UpdatedDate]
,[Remarks])
SELECT [InvoiceNumber]
,[TotalAmount]
,[IsActive]
,[CreatedBy]
,[UpdatedBy]
,[CreatedDate]
,[UpdatedDate]
,[Remarks] FROM MyInvoice
Hope this helps!
I've just run into this problem and solved it.
The source of the problem is that you have both XmlAccessType.FIELD and pairs of getters and setters. The solution is to remove setters and add a default constructor and a constructor that takes all fields.
You can use strcpy
but remember to end the array with '\0'
char array[20]; char string[100];
array[0]='1'; array[1]='7'; array[2]='8'; array[3]='.'; array[4]='9'; array[5]='\0';
strcpy(string, array);
printf("%s\n", string);
I know this is a late response but I was facing a similar issue and I managed to solve it by using notifyDataSetChanged()
in the right place.
So my situation was as follows.
I had to update a listview in an action bar tab (fragment) with contents returned from a completely different activity. Initially however, the listview would not reflect any changes. However, when I clicked another tab and then returned to the desired tab,the listview would be updated with the correct content from the other activity. So to solve this I used notifyDataSetChanged()
of the action bar adapter in the code of the activity which had to return the data.
This is the code snippet which I used in the activity.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId())
{
case R.id.action_new_forward:
FragmentTab2.mListAdapter.notifyDataSetChanged();//this updates the adapter in my action bar tab
Intent ina = new Intent(getApplicationContext(), MainActivity.class);
ina.putExtra("stra", values1);
startActivity(ina);// This is the code to start the parent activity of my action bar tab(fragment).
}
}
This activity would return some data to FragmentTab2
and it would directly update my listview in FragmentTab2
.
Hope someone finds this useful!
This worked for me within an ASP.NET site. To enable validation on some hidden fields use this code
$("form").data("validator").settings.ignore = ":hidden:not(#myitem)";
To enable validation for all elements of form use this one
$("form").data("validator").settings.ignore = "";
Note that use them within $(document).ready(function() { })
Let's fit the model:
> library(ISwR)
> fit <- lm(metabolic.rate ~ body.weight, rmr)
> summary(fit)
Call:
lm(formula = metabolic.rate ~ body.weight, data = rmr)
Residuals:
Min 1Q Median 3Q Max
-245.74 -113.99 -32.05 104.96 484.81
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 811.2267 76.9755 10.539 2.29e-13 ***
body.weight 7.0595 0.9776 7.221 7.03e-09 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 157.9 on 42 degrees of freedom
Multiple R-squared: 0.5539, Adjusted R-squared: 0.5433
F-statistic: 52.15 on 1 and 42 DF, p-value: 7.025e-09
The 95% confidence interval for the slope is the estimated coefficient (7.0595) ± two standard errors (0.9776).
This can be computed using confint
:
> confint(fit, 'body.weight', level=0.95)
2.5 % 97.5 %
body.weight 5.086656 9.0324
To read characters try
scan("/PathTo/file.csv", "")
If you're reading numeric values, then just use
scan("/PathTo/file.csv")
scan
by default will use white space as separator. The type of the second arg defines 'what' to read (defaults to double()).
just in case someone need it, in firefox for me it work like this
<iframe src="filename.pdf#zoom=FitH" style="position:absolute;right:0; top:0; bottom:0; width:100%;"></iframe>
Here is a Python 3 version using Selenium webdriver and Pillow. This program captures the screenshot of the whole page and crop the element based on its location. The element image will be available as image.png. Firefox supports saving element image directly using element.screenshot_as_png('image_name').
from selenium import webdriver
from PIL import Image
driver = webdriver.Chrome()
driver.get('https://www.google.co.in')
element = driver.find_element_by_id("lst-ib")
location = element.location
size = element.size
driver.save_screenshot("shot.png")
x = location['x']
y = location['y']
w = size['width']
h = size['height']
width = x + w
height = y + h
im = Image.open('shot.png')
im = im.crop((int(x), int(y), int(width), int(height)))
im.save('image.png')
Update
Now chrome also supports individual element screenshots. So you may directly capture the screenshot of the web element as given below.
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://www.google.co.in')
image = driver.find_element_by_id("lst-ib").screenshot_as_png
# or
# element = driver.find_element_by_id("lst-ib")
# element.screenshot_as_png("image.png")
I, too, have need for this! My situation involves comparing actuals with budget for cost centers, where expenses may have been mis-applied and therefore need to be re-allocated to the correct cost center so as to match how they were budgeted. It is very time consuming to try and scan row-by-row to see if each expense item has been correctly allocated. I decided that I should apply conditional formatting to highlight any cells where the actuals did not match the budget. I set up the conditional formatting to change the background color if the actual amount under the cost center did not match the budgeted amount.
Here's what I did:
Start in cell A1 (or the first cell you want to have the formatting). Open the Conditional Formatting dialogue box and select Apply formatting based on a formula. Then, I wrote a formula to compare one cell to another to see if they match:
=A1=A50
If the contents of cells A1 and A50 are equal, the conditional formatting will be applied. NOTICE: no $$, so the cell references are RELATIVE! Therefore, you can copy the formula from cell A1 and PasteSpecial (format). If you only click on the cells that you reference as you write your conditional formatting formula, the cells are by default locked, so then you wouldn't be able to apply them anywhere else (you would have to write out a new rule for each line- YUK!)
What is really cool about this is that if you insert rows under the conditionally formatted cell, the conditional formatting will be applied to the inserted rows as well!
Something else you could also do with this: Use ISBLANK if the amounts are not going to be exact matches, but you want to see if there are expenses showing up in columns where there are no budgeted amounts (i.e., BLANK) .
This has been a real time-saver for me. Give it a try and enjoy!
The length of the array is 7, the NUL character \0
still counts as a character and the string is still terminated with an implicit \0
See this link to see a working example
Note that had you declared str
as char str[6]= "Hello\0";
the length would be 6 because the implicit NUL is only added if it can fit (which it can't in this example.)
§ 6.7.8/p14
An array of character type may be initialized by a character string literal, optionally enclosed in braces. Sucessive characters of the character string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.
char str[] = "Hello\0"; /* sizeof == 7, Explicit + Implicit NUL */
char str[5]= "Hello\0"; /* sizeof == 5, str is "Hello" with no NUL (no longer a C-string, just an array of char). This may trigger compiler warning */
char str[6]= "Hello\0"; /* sizeof == 6, Explicit NUL only */
char str[7]= "Hello\0"; /* sizeof == 7, Explicit + Implicit NUL */
char str[8]= "Hello\0"; /* sizeof == 8, Explicit + two Implicit NUL */
To convert the byte[] to string[], simply use the below line.
byte[] fileData; // Some byte array
//Convert byte[] to string[]
var table = (Encoding.Default.GetString(
fileData,
0,
fileData.Length - 1)).Split(new string[] { "\r\n", "\r", "\n" },
StringSplitOptions.None);
As a response to your question: "i want to reset all the data and keep last 30 days inside the table."
you can create an event. Check https://dev.mysql.com/doc/refman/5.7/en/event-scheduler.html
For example:
CREATE EVENT DeleteExpiredLog
ON SCHEDULE EVERY 1 DAY
DO
DELETE FROM log WHERE date < DATE_SUB(NOW(), INTERVAL 30 DAY);
Will run a daily cleanup in your table, keeping the last 30 days data available
See to enable clustering:
pm2 start npm --name "AppName" -i 0 -- run start
What do you think?
it is different for different icons.(eg, diff sizes for action bar icons, laucnher icons, etc.) please follow this link icons handbook to learn more.
The ALL_DIRECTORIES data dictionary view will have information about all the directories that you have access to. That includes the operating system path
SELECT owner, directory_name, directory_path
FROM all_directories
readonly properties are used to create a fail-safe code. i really like the Encapsulation posts series of Mark Seemann about properties and backing fields:
http://blog.ploeh.dk/2011/05/24/PokayokeDesignFromSmellToFragrance.aspx
taken from Mark's example:
public class Fragrance : IFragrance
{
private readonly string name;
public Fragrance(string name)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
this.name = name;
}
public string Spread()
{
return this.name;
}
}
in this example you use the readonly name field to make sure the class invariant is always valid. in this case the class composer wanted to make sure the name field is set only once (immutable) and is always present.
I haven't found a better solution. You can use explode()
, preg_match_all()
, etc.
I have a static helper function like this
class Date {
public static function ausStrToTime($str) {
$dateTokens = explode('/', $str);
return strtotime($dateTokens[1] . '/' . $dateTokens[0] . '/' . $dateTokens[2]);
}
}
There is probably a better name for that, but I use ausStrToTime()
because it works with Australian dates (which I often deal with, being an Australian). A better name would probably be the standardised name, but I'm not sure what that is.
Use the .Clear
method.
Sheets("Test").Range("A1:C3").Clear
If you don't want to install anything (I assume you want to add the script into some solution/program/etc that will be run in other machines), you could try creating a vbs script (lets say, replace.vbs):
Const ForReading = 1
Const ForWriting = 2
strFileName = Wscript.Arguments(0)
strOldText = Wscript.Arguments(1)
strNewText = Wscript.Arguments(2)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(strFileName, ForReading)
strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, strOldText, strNewText)
Set objFile = objFSO.OpenTextFile(strFileName, ForWriting)
objFile.Write strNewText
objFile.Close
And you run it like this:
cscript replace.vbs "C:\One.txt" "Robert" "Rob"
Which is similar to the sed version provided by "bill weaver", but I think this one is more friendly in terms of special (' > < / ) characters.
Btw, I didn't write this, but I can't recall where I got it from.
The first answer is good for understanding how it works. But I wanted to understand how I should be using it in practice.
SUMMARY
class_weight="balanced"
works decent in the absence of you wanting to optimize manuallyclass_weight="balanced"
you capture more true events (higher TRUE recall) but also you are more likely to get false alerts (lower TRUE precision)
NB
The result might differ when using RF or GBM. sklearn does not have class_weight="balanced"
for GBM but lightgbm has LGBMClassifier(is_unbalance=False)
CODE
# scikit-learn==0.21.3
from sklearn import datasets
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score, classification_report
import numpy as np
import pandas as pd
# case: moderate imbalance
X, y = datasets.make_classification(n_samples=50*15, n_features=5, n_informative=2, n_redundant=0, random_state=1, weights=[0.8]) #,flip_y=0.1,class_sep=0.5)
np.mean(y) # 0.2
LogisticRegression(C=1e9).fit(X,y).predict(X).mean() # 0.184
(LogisticRegression(C=1e9).fit(X,y).predict_proba(X)[:,1]>0.5).mean() # 0.184 => same as first
LogisticRegression(C=1e9,class_weight={0:0.5,1:0.5}).fit(X,y).predict(X).mean() # 0.184 => same as first
LogisticRegression(C=1e9,class_weight={0:2,1:8}).fit(X,y).predict(X).mean() # 0.296 => seems to make things worse?
LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X).mean() # 0.292 => seems to make things worse?
roc_auc_score(y,LogisticRegression(C=1e9).fit(X,y).predict(X)) # 0.83
roc_auc_score(y,LogisticRegression(C=1e9,class_weight={0:2,1:8}).fit(X,y).predict(X)) # 0.86 => about the same
roc_auc_score(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X)) # 0.86 => about the same
# case: strong imbalance
X, y = datasets.make_classification(n_samples=50*15, n_features=5, n_informative=2, n_redundant=0, random_state=1, weights=[0.95])
np.mean(y) # 0.06
LogisticRegression(C=1e9).fit(X,y).predict(X).mean() # 0.02
(LogisticRegression(C=1e9).fit(X,y).predict_proba(X)[:,1]>0.5).mean() # 0.02 => same as first
LogisticRegression(C=1e9,class_weight={0:0.5,1:0.5}).fit(X,y).predict(X).mean() # 0.02 => same as first
LogisticRegression(C=1e9,class_weight={0:1,1:20}).fit(X,y).predict(X).mean() # 0.25 => huh??
LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X).mean() # 0.22 => huh??
(LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict_proba(X)[:,1]>0.5).mean() # same as last
roc_auc_score(y,LogisticRegression(C=1e9).fit(X,y).predict(X)) # 0.64
roc_auc_score(y,LogisticRegression(C=1e9,class_weight={0:1,1:20}).fit(X,y).predict(X)) # 0.84 => much better
roc_auc_score(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X)) # 0.85 => similar to manual
roc_auc_score(y,(LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict_proba(X)[:,1]>0.5).astype(int)) # same as last
print(classification_report(y,LogisticRegression(C=1e9).fit(X,y).predict(X)))
pd.crosstab(y,LogisticRegression(C=1e9).fit(X,y).predict(X),margins=True)
pd.crosstab(y,LogisticRegression(C=1e9).fit(X,y).predict(X),margins=True,normalize='index') # few prediced TRUE with only 28% TRUE recall and 86% TRUE precision so 6%*28%~=2%
print(classification_report(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X)))
pd.crosstab(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X),margins=True)
pd.crosstab(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X),margins=True,normalize='index') # 88% TRUE recall but also lot of false positives with only 23% TRUE precision, making total predicted % TRUE > actual % TRUE
An alternative solution without array formulas, possibly more robust than that of a previous answer with a (hint to a) solution without array formulas, is
=INDEX(A:A,INDEX(MAX(($A:$A<>"")*(ROW(A:A))),0))
See this answer as an example. Kudos to Brad and barry houdini, who helped solving this question.
Possible reasons for preferring a non-array formula are given in:
An official Microsoft page (look for "Disadvantages of using array formulas").
Array formulas can seem magical, but they also have some disadvantages:
This one is pretty fast :
select * from listofvalue l
inner join tbl on tbl.mycol like '%' || l.value || '%'
Login Page design using SwiftUI
import SwiftUI
struct ContentView: View {
@State var email: String = "[email protected]"
@State var password: String = ""
@State static var labelTitle: String = ""
var body: some View {
VStack(alignment: .center){
//Label
Text("Login").font(.largeTitle).foregroundColor(.yellow).bold()
//TextField
TextField("Email", text: $email)
.textContentType(.emailAddress)
.foregroundColor(.blue)
.frame(minHeight: 40)
.background(RoundedRectangle(cornerRadius: 10).foregroundColor(Color.green))
TextField("Password", text: $password) //Placeholder
.textContentType(.newPassword)
.frame(minHeight: 40)
.foregroundColor(.blue) // Text color
.background(RoundedRectangle(cornerRadius: 10).foregroundColor(Color.green))
//Button
Button(action: {
}) {
HStack {
Image(uiImage: UIImage(named: "Login")!)
.renderingMode(.original)
.font(.title)
.foregroundColor(.blue)
Text("Login")
.font(.title)
.foregroundColor(.white)
}
.font(.headline)
.frame(minWidth: 0, maxWidth: .infinity)
.background(LinearGradient(gradient: Gradient(colors: [Color("DarkGreen"), Color("LightGreen")]), startPoint: .leading, endPoint: .trailing))
.cornerRadius(40)
.padding(.horizontal, 20)
.frame(width: 200, height: 50, alignment: .center)
}
Spacer()
}.padding(10)
.frame(minWidth: 0, idealWidth: .infinity, maxWidth: .infinity, minHeight: 0, idealHeight: .infinity, maxHeight: .infinity, alignment: .top)
.background(Color.gray)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
var str = 'test343',
isNumeric = /^[-+]?(\d+|\d+\.\d*|\d*\.\d+)$/;
isNumeric.test(str);
You can use % operator to check divisiblity of a given number
The code to check whether given no. is divisible by 3 or 5 when no. less than 1000 is given below:
n=0
while n<1000:
if n%3==0 or n%5==0:
print n,'is multiple of 3 or 5'
n=n+1
Something to keep in mind when creating formatters is to try to reuse the same instance if you can, as formatters are fairly computationally expensive to create. The following is a pattern I frequently use for apps where I can share the same formatter app-wide, adapted from NSHipster.
extension DateFormatter {
static var sharedDateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
// Add your formatter configuration here
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return dateFormatter
}()
}
Usage:
let dateString = DateFormatter.sharedDateFormatter.string(from: Date())
First include the file in head tag of html , then call the function in script tags under body tags e.g.
Js file function to be called
function tryMe(arg) {
document.write(arg);
}
HTML FILE
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src='object.js'> </script>
<title>abc</title><meta charset="utf-8"/>
</head>
<body>
<script>
tryMe('This is me vishal bhasin signing in');
</script>
</body>
</html>
finish
Here is maybe a more elegant and flexible solution with 'resolve' configuration property and 'promises' enabling eventual data loading on routing and routing rules depending on data.
You specify a function in 'resolve' in routing config and in the function load and check data, do all redirects. If you need to load data, you return a promise, if you need to do redirect - reject promise before that. All details can be found on $routerProvider and $q documentation pages.
'use strict';
var app = angular.module('app', [])
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: "login.html",
controller: LoginController
})
.when('/private', {
templateUrl: "private.html",
controller: PrivateController,
resolve: {
factory: checkRouting
}
})
.when('/private/anotherpage', {
templateUrl:"another-private.html",
controller: AnotherPriveController,
resolve: {
factory: checkRouting
}
})
.otherwise({ redirectTo: '/' });
}]);
var checkRouting= function ($q, $rootScope, $location) {
if ($rootScope.userProfile) {
return true;
} else {
var deferred = $q.defer();
$http.post("/loadUserProfile", { userToken: "blah" })
.success(function (response) {
$rootScope.userProfile = response.userProfile;
deferred.resolve(true);
})
.error(function () {
deferred.reject();
$location.path("/");
});
return deferred.promise;
}
};
For russian-speaking folks there is a post on habr "??????? ????????? ???????? ? AngularJS."
From Language DDL & UDF of Hive
NVL(value, default value)
Returns default value if value is null else returns value
This means that the maximum number of simultaneously open files.
Solved:
At the end of the file /etc/security/limits.conf
you need to add the following lines:
* soft nofile 16384
* hard nofile 16384
In the current console from root (sudo does not work) to do:
ulimit -n 16384
Although this is optional, if it is possible to restart the server.
In /etc/nginx/nginx.conf
file to register the new value worker_connections
equal to 16384
divide by value worker_processes
.
If not did ulimit -n 16384
, need to reboot, then the problem will recede.
PS:
If after the repair is visible in the logs error accept() failed (24: Too many open files)
:
In the nginx configuration, propevia (for example):
worker_processes 2;
worker_rlimit_nofile 16384;
events {
worker_connections 8192;
}
JsonNode root = mapper.readTree(json);
root.at("/some-node").fields().forEachRemaining(e -> {
System.out.println(e.getKey()+"---"+ e.getValue());
});
In one line Jackson 2+
First off, you need to remove the quotes:
bashboy@host:~$ myFolder=~/Files/Scripts/Main
The quotes prevent the shell from expanding the tilde to its special meaning of being your $HOME
directory.
You could then use $myFolder
an environment a shell variable:
bashboy@host:~$ cd $myFolder
bashboy@host:~/Files/Scripts/Main$
To make an alias, you need to define the alias:
alias myfolder="cd $myFolder"
You can then treat this sort of like a command:
bashboy@host:~$ myFolder
bashboy@host:~/Files/Scripts/Main$
The other thing to be careful about, is to use the clf
(clear figure) command when you are starting a fresh plot. Otherwise you may be plotting on a pre-existing figure (not possible with the figure
command by itself, but if you do figure(2)
there may already be a figure #2), with more than one axis, or an axis that is placed kinda funny. Use clf
to ensure that you're starting from scratch:
figure(N);
clf;
plot(something);
...
Given a date object:
date.getFullYear().toString().substr(2,2);
It returns the number as string. If you want it as integer just wrap it inside the parseInt() function:
var twoDigitsYear = parseInt(date.getFullYear().toString().substr(2,2), 10);
Example with the current year in one line:
var twoDigitsCurrentYear = parseInt(new Date().getFullYear().toString().substr(2,2));
SCREEN:
NOTE: screen is actually not able to send hex, as far as I know. To do that, use echo
or printf
I was using the suggestions in this post to write to a serial port, then using the info from another post to read from the port, with mixed results. I found that using screen is an "easier" solution, since it opens a terminal session directly with that port. (I put easier in quotes, because screen has a really weird interface, IMO, and takes some further reading to figure it out.)
You can issue this command to open a screen session, then anything you type will be sent to the port, plus the return values will be printed below it:
screen /dev/ttyS0 19200,cs8
(Change the above to fit your needs for speed, parity, stop bits, etc.) I realize screen isn't the "linux command line" as the post specifically asks for, but I think it's in the same spirit. Plus, you don't have to type echo and quotes every time.
ECHO:
Follow praetorian droid's answer. HOWEVER, this didn't work for me until I also used the cat command (cat < /dev/ttyS0
) while I was sending the echo command.
PRINTF:
I found that one can also use printf's '%x' command:
c="\x"$(printf '%x' 0x12)
printf $c >> $SERIAL_COMM_PORT
Again, for printf, start cat < /dev/ttyS0
before sending the command.
I solved it by myself.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.0.7.Final</version>
</dependency>
If you're repo is available via https, you can use this command to branch ...
svn copy https://host.example.com/repos/project/trunk \
https://host.example.com/repos/project/branches/branch-name \
-m "Creating a branch of project"
#include <sstream>
....
std::stringstream ss;
ss << a_long_int; // or any other type
std::string result=ss.str(); // use .str() to get a string back
WSDL
(Web Service Description Language
) from a Web Service URL.Is possible from SOAP Web Services:
http://www.w3schools.com/xml/tempconvert.asmx
to get the WSDL we have only to add ?WSDL
, for example:
You can use skip
and take
functions as below:
$products = $art->products->skip($offset*$limit)->take($limit)->get();
// skip
should be passed param as integer value to skip the records and starting index
// take
gets an integer value to get the no. of records after starting index defined by skip
EDIT
Sorry. I was misunderstood with your question. If you want something like pagination the forPage
method will work for you. forPage method works for collections.
REf : https://laravel.com/docs/5.1/collections#method-forpage
e.g
$products = $art->products->forPage($page,$limit);
Unless you have a specific need for a dynamically compiled project, don't use a web site project.
Why? Because web site project will drive you up the wall when trying to change or understand your project. The static typing find features (e.g. find usages, refactor) in Visual Studio will all take forever on any reasonably sized project. For further information, see the Stack Overflow question Slow “Find All References” in Visual Studio.
I really can't see why they dropped web applications in Visual Studio 2005 for the pain-inducing, sanity-draining, productivity carbuncle web site project type.
use the following Code:
CGFloat screenScale = [[UIScreen mainScreen] scale];
CGRect screenBounds = [[UIScreen mainScreen] bounds];
CGSize screenSize = CGSizeMake(screenBounds.size.width * screenScale, screenBounds.size.height * screenScale);
if (screenSize.height==1136.000000)
{
// Here iPhone 5 View
// Eg: Nextview~iPhone5.Xib
} else {
// Previous Phones
// Eg : Nextview.xib
}
@DanDan's answer, using C++11 is:
using namespace std;
vector<int> keys;
transform(begin(map_in), end(map_in), back_inserter(keys),
[](decltype(map_in)::value_type const& pair) {
return pair.first;
});
and using C++14 (as noted by @ivan.ukr) we can replace decltype(map_in)::value_type
with auto
.
Check out the image-map plugin on Github. It works both with vanilla JavaScript and as a jQuery plugin.
$('img[usemap]').imageMap(); // jQuery
ImageMap('img[usemap]') // JavaScript
Check out the demo.
well, in some programming languages they are called functions others call it methods, the fact is they are the same thing. It just represents an abstractized form of reffering to a mathematical function:
f -> f(N:N).
meaning its a function with values from natural numbers (just an example). So besides the name Its exactly the same thing, representing a block of code containing instructions in resolving your purpose.
You can find/debug XPath/CSS locators in the IE as well as in different browsers with the tool called SWD Page Recorder
The only restrictions/limitations:
IEDriverServer.exe
- should be downloaded separately and placed near SwdPageRecorder.exe
<html>
<head>
<title>Pagination</title>
</head>
<body>
<?php
$conn = mysqli_connect('localhost','root','','northwind');
$data_per_page = 10;
$select = "SELECT * FROM `customers`";
$select_run = mysqli_query($conn, $select);
$records = mysqli_num_rows($select_run);
// while ($result = mysqli_fetch_array($select_run)) {
// echo $result['CompanyName'] . '<br>';
// }
// $records;
echo "<br>";
$no_of_page = ceil($records / $data_per_page);
if(!isset($_GET['page'])){
$page = 1;
}else{
$page = $_GET['page'];
}
$page_limit_data = ($page - 1) * 10;
$select = "SELECT * FROM customers LIMIT " . $page_limit_data . ',' . $data_per_page ;
$select_run = mysqli_query($conn, $select);
while ($row_select = mysqli_fetch_array($select_run)){
echo $row_select['CompanyName'] . '<br>' ;
}
for($page=1; $page<= $no_of_page; $page++){
echo "<a href='pagination.php?page=$page'> $page" . ', ';
}
?>
<br>
<h1> Testing Limit Functions Here </h1>
<?php
$limit = "SELECT CompanyName From customers LIMIT 10 OFFSET 5";
$limit_run = mysqli_query($conn , $limit);
while($limit_result = mysqli_fetch_array($limit_run)){
echo $limit_result['CompanyName'] . '<br>';
}
?>
</body>
</html>
this is the source code about wraps:
WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__doc__')
WRAPPER_UPDATES = ('__dict__',)
def update_wrapper(wrapper,
wrapped,
assigned = WRAPPER_ASSIGNMENTS,
updated = WRAPPER_UPDATES):
"""Update a wrapper function to look like the wrapped function
wrapper is the function to be updated
wrapped is the original function
assigned is a tuple naming the attributes assigned directly
from the wrapped function to the wrapper function (defaults to
functools.WRAPPER_ASSIGNMENTS)
updated is a tuple naming the attributes of the wrapper that
are updated with the corresponding attribute from the wrapped
function (defaults to functools.WRAPPER_UPDATES)
"""
for attr in assigned:
setattr(wrapper, attr, getattr(wrapped, attr))
for attr in updated:
getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
# Return the wrapper so this can be used as a decorator via partial()
return wrapper
def wraps(wrapped,
assigned = WRAPPER_ASSIGNMENTS,
updated = WRAPPER_UPDATES):
"""Decorator factory to apply update_wrapper() to a wrapper function
Returns a decorator that invokes update_wrapper() with the decorated
function as the wrapper argument and the arguments to wraps() as the
remaining arguments. Default arguments are as for update_wrapper().
This is a convenience function to simplify applying partial() to
update_wrapper().
"""
return partial(update_wrapper, wrapped=wrapped,
assigned=assigned, updated=updated)
The poster didn't ask about looking up values if exact=FALSE
, but I'm adding this as an answer for my own reference and possibly others.
If you're looking up categorical values, use the other answers.
Excel's vlookup
also allows you to match match approximately for numeric values with the 4th argument(1) match=TRUE
. I think of match=TRUE
like looking up values on a thermometer. The default value is FALSE, which is perfect for categorical values.
If you want to match approximately (perform a lookup), R has a function called findInterval
, which (as the name implies) will find the interval / bin that contains your continuous numeric value.
However, let's say that you want to findInterval
for several values. You could write a loop or use an apply function. However, I've found it more efficient to take a DIY vectorized approach.
Let's say that you have a grid of values indexed by x and y:
grid <- list(x = c(-87.727, -87.723, -87.719, -87.715, -87.711),
y = c(41.836, 41.839, 41.843, 41.847, 41.851),
z = (matrix(data = c(-3.428, -3.722, -3.061, -2.554, -2.362,
-3.034, -3.925, -3.639, -3.357, -3.283,
-0.152, -1.688, -2.765, -3.084, -2.742,
1.973, 1.193, -0.354, -1.682, -1.803,
0.998, 2.863, 3.224, 1.541, -0.044),
nrow = 5, ncol = 5)))
and you have some values you want to look up by x and y:
df <- data.frame(x = c(-87.723, -87.712, -87.726, -87.719, -87.722, -87.722),
y = c(41.84, 41.842, 41.844, 41.849, 41.838, 41.842),
id = c("a", "b", "c", "d", "e", "f")
Here is the example visualized:
contour(grid)
points(df$x, df$y, pch=df$id, col="blue", cex=1.2)
You can find the x intervals and y intervals with this type of formula:
xrng <- range(grid$x)
xbins <- length(grid$x) -1
yrng <- range(grid$y)
ybins <- length(grid$y) -1
df$ix <- trunc( (df$x - min(xrng)) / diff(xrng) * (xbins)) + 1
df$iy <- trunc( (df$y - min(yrng)) / diff(yrng) * (ybins)) + 1
You could take it one step further and perform a (simplistic) interpolation on the z values in grid
like this:
df$z <- with(df, (grid$z[cbind(ix, iy)] +
grid$z[cbind(ix + 1, iy)] +
grid$z[cbind(ix, iy + 1)] +
grid$z[cbind(ix + 1, iy + 1)]) / 4)
Which gives you these values:
contour(grid, xlim = range(c(grid$x, df$x)), ylim = range(c(grid$y, df$y)))
points(df$x, df$y, pch=df$id, col="blue", cex=1.2)
text(df$x + .001, df$y, lab=round(df$z, 2), col="blue", cex=1)
df
# x y id ix iy z
# 1 -87.723 41.840 a 2 2 -3.00425
# 2 -87.712 41.842 b 4 2 -3.11650
# 3 -87.726 41.844 c 1 3 0.33150
# 4 -87.719 41.849 d 3 4 0.68225
# 6 -87.722 41.838 e 2 1 -3.58675
# 7 -87.722 41.842 f 2 2 -3.00425
Note that ix, and iy could have also been found with a loop using findInterval
, e.g. here's one example for the second row
findInterval(df$x[2], grid$x)
# 4
findInterval(df$y[2], grid$y)
# 2
Which matches ix
and iy
in df[2]
Footnote: (1) The fourth argument of vlookup was previously called "match", but after they introduced the ribbon it was renamed to "[range_lookup]".
You can use the following 3 ways to create ArrayList from Array.
String[] array = {"a", "b", "c", "d", "e"};
//Method 1
List<String> list = Arrays.asList(array);
//Method 2
List<String> list1 = new ArrayList<String>();
Collections.addAll(list1, array);
//Method 3
List<String> list2 = new ArrayList<String>();
for(String text:array) {
list2.add(text);
}
For python 3.7 on ubuntu I had to use sudo apt-get install python3.7-tk
to make it work
Wow, I can't believe how many answers there are for this question. I can't say I've tried them all but I've tried the top 3 or 4 and none of them work for me. What did work for me was an answer located in one of the comment written by a user called doug. Since I found it so helpful, I decided to restate in an answer.
Install xcopy utility and when you're in the Terminal, input:
Copy
Thing_you_want_to_copy|xclip -selection c
Paste
myvariable=$(xclip -selection clipboard -o)
I noticed alot of answers recommended pbpaste and pbcopy. If you're into those utilities but for some reason they are not available on your repo, you can always make an alias for the xcopy commands and call them pbpaste and pbcopy.
alias pbcopy="xclip -selection c"
alias pbpaste="xclip -selection clipboard -o"
So then it would look like this:
Thing_you_want_to_copy|pbcopy
myvariable=$(pbpaste)
Android Home Key handled by the framework layer you can't able to handle this in the application layer level. Because the home button action is already defined in the below level. But If you are developing your custom ROM, then It might be possible. Google restricted the HOME BUTTON override functions because of security reasons.
Usually you would do it something like this
public class Foo implements Runnable {
private volatile int value;
@Override
public void run() {
value = 2;
}
public int getValue() {
return value;
}
}
Then you can create the thread and retrieve the value (given that the value has been set)
Foo foo = new Foo();
Thread thread = new Thread(foo);
thread.start();
thread.join();
int value = foo.getValue();
tl;dr
a thread cannot return a value (at least not without a callback mechanism). You should reference a thread like an ordinary class and ask for the value.
First, you should look for the file vcvarsall.bat in your system.
If it does not exist, I recommend you to install Microsoft Visual C++ Compiler for Python 2.7. This will create the vcvarsall.bat in "C:\Program Files (x86)\Common Files\Microsoft\Visual C++ for Python\9.0" if you install it for all users.
The problem now is in the function find_vcvarsall(version) in the C:/Python27/Lib/distutils/msvc9compiler.py module, which is looking for the vcvarsall.bat file.
Following the function calls you will see it is looking for an entry in the registry containing the path to the vcvarsall.bat file. It will never find it because this function is looking in other directories different from where the above-mentioned installation placed it, and in my case, the registry didn't exist.
The easiest way to solve this problem is to manually return the path of the vcvarsall.bat file. To do so, modify the function find_vcvarsall(version) in the msvc9compiler.py file with the absolute path to the vcvarsall.bat file like this:
def find_vcvarsall(version):
return r"C:\Program Files (x86)\Common Files\Microsoft\Visual C++ for Python\9.0\vcvarsall.bat"
This solution worked for me.
If you already have the vcvarsall.bat file you should check if you have the key productdir in the registry:
(HKEY_USERS, HKEY_CURRENT_USERS, HKEY_LOCAL_MACHINE or HKEY_CLASSES_ROOT)\Software\Wow6432Node\Microsoft\VisualStudio\version\Setup\VC
Where version = msvc9compiler.get_build_version()
If you don't have the key just do:
def find_vcvarsall(version):
return <path>\vcvarsall.bat
To understand the exact behavior check msvc9compiler.py module starting in the find_vcvarsall(version) function.
I was getting the same error when I tried to do :
cordova build ios
except mine said ** ARCHIVE FAILED ** rather than ** BUILD FAILED **.
I fixed it by opening the projectName.xcodeproj file in Xcode and then adjusting these 2 settings :
Then I quit out of Xcode and reran cordova build ios
and it worked.
No need to use any CSS or JQuery. You can do it right from the HTML input tag.
For example, In below email box, the placeholder text will disappear after clicking inside and the text will appear again if clicked outside.
<input type="email" placeholder="Type your email here..." onfocus="this.placeholder=''" onblur="this.placeholder='Type your email here...'">
When you add an object to $stateProvider.state
that object is then passed with the state. So you can add additional properties which you can read later on when needed.
Example route configuration
$stateProvider
.state('public', {
abstract: true,
module: 'public'
})
.state('public.login', {
url: '/login',
module: 'public'
})
.state('tool', {
abstract: true,
module: 'private'
})
.state('tool.suggestions', {
url: '/suggestions',
module: 'private'
});
The $stateChangeStart
event gives you acces to the toState
and fromState
objects. These state objects will contain the configuration properties.
Example check for the custom module property
$rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
if (toState.module === 'private' && !$cookies.Session) {
// If logged out and transitioning to a logged in page:
e.preventDefault();
$state.go('public.login');
} else if (toState.module === 'public' && $cookies.Session) {
// If logged in and transitioning to a logged out page:
e.preventDefault();
$state.go('tool.suggestions');
};
});
I didn't change the logic of the cookies because I think that is out of scope for your question.
You can create a Helper to get you this to work more modular.
Value publicStates
myApp.value('publicStates', function(){
return {
module: 'public',
routes: [{
name: 'login',
config: {
url: '/login'
}
}]
};
});
Value privateStates
myApp.value('privateStates', function(){
return {
module: 'private',
routes: [{
name: 'suggestions',
config: {
url: '/suggestions'
}
}]
};
});
The Helper
myApp.provider('stateshelperConfig', function () {
this.config = {
// These are the properties we need to set
// $stateProvider: undefined
process: function (stateConfigs){
var module = stateConfigs.module;
$stateProvider = this.$stateProvider;
$stateProvider.state(module, {
abstract: true,
module: module
});
angular.forEach(stateConfigs, function (route){
route.config.module = module;
$stateProvider.state(module + route.name, route.config);
});
}
};
this.$get = function () {
return {
config: this.config
};
};
});
Now you can use the helper to add the state configuration to your state configuration.
myApp.config(['$stateProvider', '$urlRouterProvider',
'stateshelperConfigProvider', 'publicStates', 'privateStates',
function ($stateProvider, $urlRouterProvider, helper, publicStates, privateStates) {
helper.config.$stateProvider = $stateProvider;
helper.process(publicStates);
helper.process(privateStates);
}]);
This way you can abstract the repeated code, and come up with a more modular solution.
Note: the code above isn't tested
Object.toparams = function ObjecttoParams(obj)
{
var p = [];
for (var key in obj)
{
p.push(key + '=' + encodeURIComponent(obj[key]));
}
return p.join('&');
};
You can specify the cookie file with a curl opt. You could use a unique file for each user.
curl_setopt( $curl_handle, CURLOPT_COOKIESESSION, true );
curl_setopt( $curl_handle, CURLOPT_COOKIEJAR, uniquefilename );
curl_setopt( $curl_handle, CURLOPT_COOKIEFILE, uniquefilename );
The best way to handle it would be to stick your request logic into a curl function and just pass the unique file name in as a parameter.
function fetch( $url, $z=null ) {
$ch = curl_init();
$useragent = isset($z['useragent']) ? $z['useragent'] : 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:10.0.2) Gecko/20100101 Firefox/10.0.2';
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $ch, CURLOPT_POST, isset($z['post']) );
if( isset($z['post']) ) curl_setopt( $ch, CURLOPT_POSTFIELDS, $z['post'] );
if( isset($z['refer']) ) curl_setopt( $ch, CURLOPT_REFERER, $z['refer'] );
curl_setopt( $ch, CURLOPT_USERAGENT, $useragent );
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, ( isset($z['timeout']) ? $z['timeout'] : 5 ) );
curl_setopt( $ch, CURLOPT_COOKIEJAR, $z['cookiefile'] );
curl_setopt( $ch, CURLOPT_COOKIEFILE, $z['cookiefile'] );
$result = curl_exec( $ch );
curl_close( $ch );
return $result;
}
I use this for quick grabs. It takes the url and an array of options.
I came across this post and found that none of the answers fully captured what I was trying to do. I have a laptop that has a 3840x2160 resolution and two monitors with 1920x1080 resolution. In order to get the correct monitor size in my WPF application I had to make the application DPI aware. Then I used the Win32 API to get the monitor size.
I did this by first moving the window to the monitor that I wanted to get the size from. Then by getting the hwnd of the application's MainWindow (doesn't have to be the main window but my application only has one window) and an IntPtr to the monitor. Then I created a new instance of the MONITORINFOEX struct and called the GetMonitorInfo method.
The MONITORINFOEX struct has both the working area and the full resolution of the screen so you can return whichever one you need. This will also allow you to leave out a reference to System.Windows.Forms (assuming you don't need it something else in your application). I used the .NET Framework Reference Source for System.Windows.Forms.Screen to come up with this solution.
public System.Drawing.Size GetMonitorSize()
{
var window = System.Windows.Application.Current.MainWindow;
var hwnd = new WindowInteropHelper(window).EnsureHandle();
var monitor = NativeMethods.MonitorFromWindow(hwnd, NativeMethods.MONITOR_DEFAULTTONEAREST);
NativeMethods.MONITORINFO info = new NativeMethods.MONITORINFO();
NativeMethods.GetMonitorInfo(new HandleRef(null, monitor), info);
return info.rcMonitor.Size;
}
internal static class NativeMethods
{
public const Int32 MONITOR_DEFAULTTONEAREST = 0x00000002;
[DllImport("user32.dll")]
public static extern IntPtr MonitorFromWindow(IntPtr handle, Int32 flags);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern bool GetMonitorInfo(HandleRef hmonitor, MONITORINFO info);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 4)]
public class MONITORINFO
{
internal int cbSize = Marshal.SizeOf(typeof(MONITORINFO));
internal RECT rcMonitor = new RECT();
internal RECT rcWork = new RECT();
internal int dwFlags = 0;
}
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
public RECT(int left, int top, int right, int bottom)
{
this.left = left;
this.top = top;
this.right = right;
this.bottom = bottom;
}
public RECT(System.Drawing.Rectangle r)
{
left = r.Left;
top = r.Top;
right = r.Right;
bottom = r.Bottom;
}
public static RECT FromXYWH(int x, int y, int width, int height) => new RECT(x, y, x + width, y + height);
public System.Drawing.Size Size => new System.Drawing.Size(right - left, bottom - top);
}
}
when you add a new data set to a geom you need to use the data=
argument. Or put the arguments in the proper order mapping=..., data=...
. Take a look at the arguments for ?geom_line
.
Thus:
p + geom_line(data=df.last, aes(HrEnd, MWh, group=factor(Date)), color="red")
Or:
p + geom_line(aes(HrEnd, MWh, group=factor(Date)), df.last, color="red")
object parsedData = se.Deserialize(reader);
System.Collections.IEnumerable stksEnum = parsedData as System.Collections.IEnumerable;
then will be able to enumerate it!
Try avoiding unnecessary loops and go for this if needed.
string SearchByColumn = "ColumnName=" + value;
DataRow[] hasRows = currentDataTable.Select(SearchByColumn);
if (hasRows.Length == 0)
{
//your logic goes here
}
else
{
//your logic goes here
}
If you want to search by specific ID then there should be a primary key in a table.
If you are looking for way to use get and set on any object (not a class) Proxy
may be usefull:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
const target = {
message1: "hello",
message2: "everyone"
};
const handler3 = {
get: function (target, prop, receiver) {
if (prop === "message2") {
return "world";
}
return Reflect.get(...arguments);
},
};
const proxy3 = new Proxy(target, handler3);
console.log(proxy3.message1); // hello
console.log(proxy3.message2); // world
Note: be aware that this is new api not supported and required polifill for older browsers
I apologize for resurrecting this question but I stumbled upon this thread and found a small issue. For anyone wanting a character limit that will remove words that would go above your given limit, the above answers work great. In my specific case, I like to display a word if the limit falls in the middle of said word. I decided to share my solution in case anyone else is looking for this functionality and needs to include words instead of trimming them out.
function str_limit($str, $len = 100, $end = '...')
{
if(strlen($str) < $len)
{
return $str;
}
$str = preg_replace("/\s+/", ' ', str_replace(array("\r\n", "\r", "\n"), ' ', $str));
if(strlen($str) <= $len)
{
return $str;
}
$out = '';
foreach(explode(' ', trim($str)) as $val)
{
$out .= $val . ' ';
if(strlen($out) >= $len)
{
$out = trim($out);
return (strlen($out) == strlen($str)) ? $out : $out . $end;
}
}
}
Examples:
echo str_limit('Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', 100, '...');
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore...
echo str_limit('Lorem ipsum', 100, '...');
Lorem ipsum
echo str_limit('Lorem ipsum', 1, '...');
Lorem...
If you happen to be an iOS developer
:
Check how many simulators that you have downloaded as they take up a lot of space:
Go to: ~/Library/Developer/Xcode/iOS DeviceSupport
Also delete old archived apps:
Go to: ~/Library/Developer/Xcode/Archives
I cleared 100GB doing this.
For all the Swift lovers out there, here is the answer by @Travis translated into SWIFT:
Do what @Travis explained before the Objective C code. Then,
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
var exampleViewController: ExampleViewController = mainStoryboard.instantiateViewControllerWithIdentifier("ExampleController") as! ExampleViewController
self.window?.rootViewController = exampleViewController
self.window?.makeKeyAndVisible()
return true
}
The ExampleViewController
would be the new initial view controller you would like to show.
The steps explained:
Enjoy and happy programming!
Let's say you have the DLLs build for both platforms, and they are in the following location:
C:\whatever\x86\whatever.dll
C:\whatever\x64\whatever.dll
You simply need to edit your .csproj file from this:
<HintPath>C:\whatever\x86\whatever.dll</HintPath>
To this:
<HintPath>C:\whatever\$(Platform)\whatever.dll</HintPath>
You should then be able to build your project targeting both platforms, and MSBuild will look in the correct directory for the chosen platform.
Source: http://fullparam.wordpress.com/2012/09/07/fck-it-i-am-going-to-search-all-tables-all-collumns/
I have a solution from a while ago that I kept improving. Also searches within XML columns if told to do so, or searches integer values if providing a integer only string.
/* Reto Egeter, fullparam.wordpress.com */
DECLARE @SearchStrTableName nvarchar(255), @SearchStrColumnName nvarchar(255), @SearchStrColumnValue nvarchar(255), @SearchStrInXML bit, @FullRowResult bit, @FullRowResultRows int
SET @SearchStrColumnValue = '%searchthis%' /* use LIKE syntax */
SET @FullRowResult = 1
SET @FullRowResultRows = 3
SET @SearchStrTableName = NULL /* NULL for all tables, uses LIKE syntax */
SET @SearchStrColumnName = NULL /* NULL for all columns, uses LIKE syntax */
SET @SearchStrInXML = 0 /* Searching XML data may be slow */
IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results
CREATE TABLE #Results (TableName nvarchar(128), ColumnName nvarchar(128), ColumnValue nvarchar(max),ColumnType nvarchar(20))
SET NOCOUNT ON
DECLARE @TableName nvarchar(256) = '',@ColumnName nvarchar(128),@ColumnType nvarchar(20), @QuotedSearchStrColumnValue nvarchar(110), @QuotedSearchStrColumnName nvarchar(110)
SET @QuotedSearchStrColumnValue = QUOTENAME(@SearchStrColumnValue,'''')
DECLARE @ColumnNameTable TABLE (COLUMN_NAME nvarchar(128),DATA_TYPE nvarchar(20))
WHILE @TableName IS NOT NULL
BEGIN
SET @TableName =
(
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND TABLE_NAME LIKE COALESCE(@SearchStrTableName,TABLE_NAME)
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
AND OBJECTPROPERTY(OBJECT_ID(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)), 'IsMSShipped') = 0
)
IF @TableName IS NOT NULL
BEGIN
DECLARE @sql VARCHAR(MAX)
SET @sql = 'SELECT QUOTENAME(COLUMN_NAME),DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(''' + @TableName + ''', 2)
AND TABLE_NAME = PARSENAME(''' + @TableName + ''', 1)
AND DATA_TYPE IN (' + CASE WHEN ISNUMERIC(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@SearchStrColumnValue,'%',''),'_',''),'[',''),']',''),'-','')) = 1 THEN '''tinyint'',''int'',''smallint'',''bigint'',''numeric'',''decimal'',''smallmoney'',''money'',' ELSE '' END + '''char'',''varchar'',''nchar'',''nvarchar'',''timestamp'',''uniqueidentifier''' + CASE @SearchStrInXML WHEN 1 THEN ',''xml''' ELSE '' END + ')
AND COLUMN_NAME LIKE COALESCE(' + CASE WHEN @SearchStrColumnName IS NULL THEN 'NULL' ELSE '''' + @SearchStrColumnName + '''' END + ',COLUMN_NAME)'
INSERT INTO @ColumnNameTable
EXEC (@sql)
WHILE EXISTS (SELECT TOP 1 COLUMN_NAME FROM @ColumnNameTable)
BEGIN
PRINT @ColumnName
SELECT TOP 1 @ColumnName = COLUMN_NAME,@ColumnType = DATA_TYPE FROM @ColumnNameTable
SET @sql = 'SELECT ''' + @TableName + ''',''' + @ColumnName + ''',' + CASE @ColumnType WHEN 'xml' THEN 'LEFT(CAST(' + @ColumnName + ' AS nvarchar(MAX)), 4096),'''
WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + '),'''
ELSE 'LEFT(' + @ColumnName + ', 4096),''' END + @ColumnType + '''
FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE ' + CASE @ColumnType WHEN 'xml' THEN 'CAST(' + @ColumnName + ' AS nvarchar(MAX))'
WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + ')'
ELSE @ColumnName END + ' LIKE ' + @QuotedSearchStrColumnValue
INSERT INTO #Results
EXEC(@sql)
IF @@ROWCOUNT > 0 IF @FullRowResult = 1
BEGIN
SET @sql = 'SELECT TOP ' + CAST(@FullRowResultRows AS VARCHAR(3)) + ' ''' + @TableName + ''' AS [TableFound],''' + @ColumnName + ''' AS [ColumnFound],''FullRow>'' AS [FullRow>],*' +
' FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE ' + CASE @ColumnType WHEN 'xml' THEN 'CAST(' + @ColumnName + ' AS nvarchar(MAX))'
WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + ')'
ELSE @ColumnName END + ' LIKE ' + @QuotedSearchStrColumnValue
EXEC(@sql)
END
DELETE FROM @ColumnNameTable WHERE COLUMN_NAME = @ColumnName
END
END
END
SET NOCOUNT OFF
SELECT TableName, ColumnName, ColumnValue, ColumnType, COUNT(*) AS Count FROM #Results
GROUP BY TableName, ColumnName, ColumnValue, ColumnType
I built this little function to automatically format anything into a nice currency format.
function formatDollars($dollars)
{
return "$".number_format(sprintf('%0.2f', preg_replace("/[^0-9.]/", "", $dollars)),2);
}
Edit
It was pointed out that this does not show negative values. I broke it into two lines so it's easier to edit the formatting. Wrap it in parenthesis if it's a negative value:
function formatDollars($dollars)
{
$formatted = "$" . number_format(sprintf('%0.2f', preg_replace("/[^0-9.]/", "", $dollars)), 2);
return $dollars < 0 ? "({$formatted})" : "{$formatted}";
}
If you're using .NET Core, you will have to .AllowCredentials() when configuring CORS in Startup.CS.
Inside of ConfigureServices
services.AddCors(o => {
o.AddPolicy("AllowSetOrigins", options =>
{
options.WithOrigins("https://localhost:xxxx");
options.AllowAnyHeader();
options.AllowAnyMethod();
options.AllowCredentials();
});
});
services.AddMvc();
Then inside of Configure:
app.UseCors("AllowSetOrigins");
app.UseMvc(routes =>
{
// Routing code here
});
For me, it was specifically just missing options.AllowCredentials() that caused the error you mentioned. As a side note in general for others having CORS issues as well, the order matters and AddCors() must be registered before AddMVC() inside of your Startup class.
You should add fstream::out to open method like this:
file.open("test.txt",fstream::out);
More information about fstream flags, check out this link: http://www.cplusplus.com/reference/fstream/fstream/open/
XML is not a format for storing images, neither binary data. I think it all depends on how you want to use those images. If you are in a web application and would want to read them from there and display them, I would store the URLs. If you need to send them to another web endpoint, I would serialize them, rather than persisting manually in XML. Please explain what is the scenario.
function function_one() {
function_two();
}
function function_two() {
//enter code here
}
There are a lot of tools mentioned, but one more called JSON Schema inferencer for the record:
https://github.com/rnd0101/json_schema_inferencer
(it's not a library or a product, but a Python script)
With the usual Full Disclosure: I am the author.
Blimey. This was a really useful thread to discover.
I still found some of these suggestions confusing. Whenever I used value
with [1]
in the string, it would only retrieved the first value. And some suggestions recommended using cross apply
which (in my tests) just brought back far too much data.
So, here's my simple example of how you'd create an xml
object, then read out its values into a table.
DECLARE @str nvarchar(2000)
SET @str = ''
SET @str = @str + '<users>'
SET @str = @str + ' <user>'
SET @str = @str + ' <firstName>Mike</firstName>'
SET @str = @str + ' <lastName>Gledhill</lastName>'
SET @str = @str + ' <age>31</age>'
SET @str = @str + ' </user>'
SET @str = @str + ' <user>'
SET @str = @str + ' <firstName>Mark</firstName>'
SET @str = @str + ' <lastName>Stevens</lastName>'
SET @str = @str + ' <age>42</age>'
SET @str = @str + ' </user>'
SET @str = @str + ' <user>'
SET @str = @str + ' <firstName>Sarah</firstName>'
SET @str = @str + ' <lastName>Brown</lastName>'
SET @str = @str + ' <age>23</age>'
SET @str = @str + ' </user>'
SET @str = @str + '</users>'
DECLARE @xml xml
SELECT @xml = CAST(CAST(@str AS VARBINARY(MAX)) AS XML)
-- Iterate through each of the "users\user" records in our XML
SELECT
x.Rec.query('./firstName').value('.', 'nvarchar(2000)') AS 'FirstName',
x.Rec.query('./lastName').value('.', 'nvarchar(2000)') AS 'LastName',
x.Rec.query('./age').value('.', 'int') AS 'Age'
FROM @xml.nodes('/users/user') as x(Rec)
And here's the output:
It's bizarre syntax, but with a decent example, it's easy enough to add to your own SQL Server functions.
Speaking of which, here's the correct answer to this question.
Assuming your have your xml data in an @xml
variable of type xml
(as demonstrated in my example above), here's how you would return the three rows of data from the xml quoted in the question:
SELECT
x.Rec.query('./firstName').value('.', 'nvarchar(2000)') AS 'FirstName',
x.Rec.query('./lastName').value('.', 'nvarchar(2000)') AS 'LastName'
FROM @xml.nodes('/person') as x(Rec)
Using the TreeMap
you can sort the map.
Map<String, String> map = new HashMap<>();
Map<String, String> treeMap = new TreeMap<>(map);
for (String str : treeMap.keySet()) {
System.out.println(str);
}
// Returns bottom offset value + or - from viewport top
function offsetBottom(el, i) { i = i || 0; return $(el)[i].getBoundingClientRect().bottom }
// Returns right offset value
function offsetRight(el, i) { i = i || 0; return $(el)[i].getBoundingClientRect().right }
var bottom = offsetBottom('#logo');
var right = offsetRight('#logo');
This will find the distance from the top and left of your viewport to your element's exact edge and nothing beyond that. So say your logo was 350px and it had a left margin of 50px, variable 'right' will hold a value of 400 because that's the actual distance in pixels it took to get to the edge of your element, no matter if you have more padding or margin to the right of it.
If your box-sizing CSS property is set to border-box it will continue to work just as if it were set as the default content-box.
Calendar.getInstance().get(Calendar.MONTH);
is zero based, 10 is November. From the javadoc;
public static final int MONTH Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year.
Calendar.getInstance().get(Calendar.JANUARY);
is not a sensible thing to do, the value for JANUARY
is 0, which is the same as ERA
, you are effectively calling;
Calendar.getInstance().get(Calendar.ERA);
Just piling on... similar to Feiyu Zhou's post. Here I'm adding the machine name.
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, builder) =>
{
var env = context.HostingEnvironment;
var hostname = Environment.MachineName;
builder.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{hostname}.json", optional: true, reloadOnChange: true);
builder.AddEnvironmentVariables();
if (args != null)
{
builder.AddCommandLine(args);
}
})
.UseStartup<Startup>();
}
I assume you want to remove rows that are all NAs. Then, you can do the following :
data <- rbind(c(1,2,3), c(1, NA, 4), c(4,6,7), c(NA, NA, NA), c(4, 8, NA)) # sample data
data
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 1 NA 4
[3,] 4 6 7
[4,] NA NA NA
[5,] 4 8 NA
data[rowSums(is.na(data)) != ncol(data),]
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 1 NA 4
[3,] 4 6 7
[4,] 4 8 NA
If you want to remove rows that have at least one NA, just change the condition :
data[rowSums(is.na(data)) == 0,]
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 6 7
First, try omitting the quotes from 12 and 24. Worth a shot.
Second, it's better to do this in CSS. See also http://www.w3schools.com/css/css_font.asp . Here is an inline style for a table tag:
<table style='font-family:"Courier New", Courier, monospace; font-size:80%' ...>...</table>
Better still, use an external style sheet or a style tag near the top of your HTML document. See also http://www.w3schools.com/css/css_howto.asp .
Though this question is rather old, here's a answer :)
What you are asking for can be achieved by using jQuery's .click() event method and .on() event method
So this could be the code:
// Set the global variables
var userImage = $("#img-giLkojRpuK");
var hangoutButton = $("#hangout-giLkojRpuK");
$(document).ready(function() {
// When the document is ready/loaded, execute function
// Hide hangoutButton
hangoutButton.hide();
// Assign "click"-event-method to userImage
userImage.on("click", function() {
console.log("in onclick");
hangoutButton.click();
});
});
I've suffered from this problem and found that, for some reason or other, environment variables were simply not being parsed (executing cd %M2%
told me that there was no folder %M2%
in the current directory). In the end adding the explicit path to Maven's executable worked for me:
C:\apache-maven-3.1.0\bin
When using JBOSS Server, double click on the server:
Go to "Open Launch Configuration"
Then change min and max memory sizes (like 1G, 1m):
I can't tell if you've found some special case code which requires you to test against private fields. But in my experience you never have to test something private - always public. Maybe you could give an example of some code where you need to test private?
Depending on what you want to do runnning it via a Proxy is not ideal. A transparent proxy might work ok as long as the packets do not get tampered with.
I am about to reverse the GPS data that gets transferred from the iPhone to the iPad on iOS 4.3.x to get to the the vanilla data the best way to get a clean Network Dump is to use "tcpdump" and/or "pirni" as already suggested.
In this particular case where we want the Tethered data it needs to be as transparent as possible. Obviously you need your phone to be JailBroken for this to work.
For those using CloudFormation template. You can set AWS_DEFAULT_REGION
environment variable using UserData and AWS::Region
. For example,
MyInstance1:
Type: AWS::EC2::Instance
Properties:
ImageId: ami-04b9e92b5572fa0d1 #ubuntu
InstanceType: t2.micro
UserData:
Fn::Base64: !Sub |
#!/bin/bash -x
echo "export AWS_DEFAULT_REGION=${AWS::Region}" >> /etc/profile
What about that?
HTML
<div class="chart" id="graph" data-percent="88"></div>
Javascript
var el = document.getElementById('graph'); // get canvas
var options = {
percent: el.getAttribute('data-percent') || 25,
size: el.getAttribute('data-size') || 220,
lineWidth: el.getAttribute('data-line') || 15,
rotate: el.getAttribute('data-rotate') || 0
}
var canvas = document.createElement('canvas');
var span = document.createElement('span');
span.textContent = options.percent + '%';
if (typeof(G_vmlCanvasManager) !== 'undefined') {
G_vmlCanvasManager.initElement(canvas);
}
var ctx = canvas.getContext('2d');
canvas.width = canvas.height = options.size;
el.appendChild(span);
el.appendChild(canvas);
ctx.translate(options.size / 2, options.size / 2); // change center
ctx.rotate((-1 / 2 + options.rotate / 180) * Math.PI); // rotate -90 deg
//imd = ctx.getImageData(0, 0, 240, 240);
var radius = (options.size - options.lineWidth) / 2;
var drawCircle = function(color, lineWidth, percent) {
percent = Math.min(Math.max(0, percent || 1), 1);
ctx.beginPath();
ctx.arc(0, 0, radius, 0, Math.PI * 2 * percent, false);
ctx.strokeStyle = color;
ctx.lineCap = 'round'; // butt, round or square
ctx.lineWidth = lineWidth
ctx.stroke();
};
drawCircle('#efefef', options.lineWidth, 100 / 100);
drawCircle('#555555', options.lineWidth, options.percent / 100);
and CSS
div {
position:relative;
margin:80px;
width:220px; height:220px;
}
canvas {
display: block;
position:absolute;
top:0;
left:0;
}
span {
color:#555;
display:block;
line-height:220px;
text-align:center;
width:220px;
font-family:sans-serif;
font-size:40px;
font-weight:100;
margin-left:5px;
}
http://jsfiddle.net/Aapn8/3410/
Basic code was taken from Simple PIE Chart http://rendro.github.io/easy-pie-chart/
The answers in this topic are all great. However i'd like to propose another one. Most likely you have been given an api and want that into your c# project. Using Postman, you can setup and test the api call there and once it runs properly, you can simply click 'Code' and the request that you have been working on, is written to a c# snippet. like this:
var client = new RestClient("https://api.XXXXX.nl/oauth/token");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic N2I1YTM4************************************jI0YzJhNDg=");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("grant_type", "password");
request.AddParameter("username", "[email protected]");
request.AddParameter("password", "XXXXXXXXXXXXX");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
The code above depends on the nuget package RestSharp, which you can easily install.
A functional approach:
a = [1,"A", 34, -123, "Hello", 12]
b = [0, 2, 5]
from operator import itemgetter
print(list(itemgetter(*b)(a)))
[1, 34, 12]
Normally this error occurs when you invoke java by supplying the wrong arguments/options. In this case it should be the version
option.
java -version
So to double check you can always do java -help
, and see if the option exists. In this case, there is no option such as v
.
Posting this late just for others..I bet the first coder is done by now. For simple datatypes no copy is needed, just revert to good old C code methods.
std::vector <int> myVec;
int *p;
// Add some data here and set start, then
p=myVec.data()+start;
Then pass the pointer p and a len to anything needing a subvector.
notelen must be!! len < myVec.size()-start
For future readers, here is an elegant solution(5x5):
var matrix = [[Int]](repeating: [Int](repeating: 0, count: 5), count: 5)
and a dynamic approach:
var matrix = [[Int]]() // creates an empty matrix
var row = [Int]() // fill this row
matrix.append(row) // add this row
Another way to differentiate between 0 rows or some rows from a ResultSet:
ResultSet res = getData();
if(!res.isBeforeFirst()){ //res.isBeforeFirst() is true if the cursor
//is before the first row. If res contains
//no rows, rs.isBeforeFirst() is false.
System.out.println("0 rows");
}
else{
while(res.next()){
// code to display the rows in the table.
}
}
If you must know the number of rows given a ResultSet, here is a method to get it:
public int getRows(ResultSet res){
int totalRows = 0;
try {
res.last();
totalRows = res.getRow();
res.beforeFirst();
}
catch(Exception ex) {
return 0;
}
return totalRows ;
}
I'm going to add to this, as it's a search that came out top on google..
When using ExtJS / Javascript I insert this and the console is cleared out - unless there is an error..
console.log('\033[2J');
I'm more than likely way off course, but this is how I clear the console for each page load/refresh.
C also does a good job at not making anything ambiguous.
Sure the dot could be overloaded to mean both things, but the arrow makes sure that the programmer knows that he's operating on a pointer, just like when the compiler won't let you mix two incompatible types.
Unfortunately, there isn't a TryParse() equivalent. If you create a new instance of a System.Guid and pass the string value in, you can catch the three possible exceptions it would throw if it is invalid.
Those are:
I have seen some implementations where you can do a regex on the string prior to creating the instance, if you are just trying to validate it and not create it.
If I understood you correctly:
var hash = {};
hash['bob'] = 123;
hash['joe'] = 456;
var sum = 0;
for (var name in hash) {
sum += hash[name];
}
alert(sum); // 579
See my detailed answer to a very similar previous question
@Beau Crawford's is a good way in SQL 2005 and below, though if you're granting rep it should go to the first guy to SO it. The only problem is that for inserts it's still two IO operations.
MS Sql2008 introduces merge
from the SQL:2003 standard:
merge tablename with(HOLDLOCK) as target
using (values ('new value', 'different value'))
as source (field1, field2)
on target.idfield = 7
when matched then
update
set field1 = source.field1,
field2 = source.field2,
...
when not matched then
insert ( idfield, field1, field2, ... )
values ( 7, source.field1, source.field2, ... )
Now it's really just one IO operation, but awful code :-(
I used friedmud's answer. I looked into this for a while, and it seems to be a good way to get started. This solution also has a well defined method of adding compiler flags. I answered again, because I made changes to make it work in my environment, Ubuntu and g++. More working examples are the best teacher, sometimes.
appname := myapp
CXX := g++
CXXFLAGS := -Wall -g
srcfiles := $(shell find . -maxdepth 1 -name "*.cpp")
objects := $(patsubst %.cpp, %.o, $(srcfiles))
all: $(appname)
$(appname): $(objects)
$(CXX) $(CXXFLAGS) $(LDFLAGS) -o $(appname) $(objects) $(LDLIBS)
depend: .depend
.depend: $(srcfiles)
rm -f ./.depend
$(CXX) $(CXXFLAGS) -MM $^>>./.depend;
clean:
rm -f $(objects)
dist-clean: clean
rm -f *~ .depend
include .depend
Makefiles seem to be very complex. I was using one, but it was generating an error related to not linking in g++ libraries. This configuration solved that problem.
In my case I received this exception even when all parameter values were correctly supplied but the type of command was not specified :
cmd.CommandType = System.Data.CommandType.StoredProcedure;
This is obviously not the case in the question above, but exception description is not very clear in this case, so I decided to specify that.
You can do:
git diff master~20:pom.xml pom.xml
... to compare your current pom.xml
to the one from master
20 revisions ago through the first parent. You can replace master~20
, of course, with the object name (SHA1sum) of a commit or any of the many other ways of specifying a revision.
Note that this is actually comparing the old pom.xml
to the version in your working tree, not the version committed in master
. If you want that, then you can do the following instead:
git diff master~20:pom.xml master:pom.xml
If you didn't want to use async/await inside your method, but still "decorate" it so as to be able to use the await keyword from outside, TaskCompletionSource.cs:
public static Task<T> RunAsync<T>(Func<T> function)
{
if (function == null) throw new ArgumentNullException(“function”);
var tcs = new TaskCompletionSource<T>();
ThreadPool.QueueUserWorkItem(_ =>
{
try
{
T result = function();
tcs.SetResult(result);
}
catch(Exception exc) { tcs.SetException(exc); }
});
return tcs.Task;
}
To support such a paradigm with Tasks, we need a way to retain the Task façade and the ability to refer to an arbitrary asynchronous operation as a Task, but to control the lifetime of that Task according to the rules of the underlying infrastructure that’s providing the asynchrony, and to do so in a manner that doesn’t cost significantly. This is the purpose of TaskCompletionSource.
I saw it's also used in the .NET source, e.g. WebClient.cs:
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public Task<string> UploadStringTaskAsync(Uri address, string method, string data)
{
// Create the task to be returned
var tcs = new TaskCompletionSource<string>(address);
// Setup the callback event handler
UploadStringCompletedEventHandler handler = null;
handler = (sender, e) => HandleCompletion(tcs, e, (args) => args.Result, handler, (webClient, completion) => webClient.UploadStringCompleted -= completion);
this.UploadStringCompleted += handler;
// Start the async operation.
try { this.UploadStringAsync(address, method, data, tcs); }
catch
{
this.UploadStringCompleted -= handler;
throw;
}
// Return the task that represents the async operation
return tcs.Task;
}
Finally, I also found the following useful:
I get asked this question all the time. The implication is that there must be some thread somewhere that’s blocking on the I/O call to the external resource. So, asynchronous code frees up the request thread, but only at the expense of another thread elsewhere in the system, right? No, not at all.
To understand why asynchronous requests scale, I’ll trace a (simplified) example of an asynchronous I/O call. Let’s say a request needs to write to a file. The request thread calls the asynchronous write method. WriteAsync is implemented by the Base Class Library (BCL), and uses completion ports for its asynchronous I/O. So, the WriteAsync call is passed down to the OS as an asynchronous file write. The OS then communicates with the driver stack, passing along the data to write in an I/O request packet (IRP).
This is where things get interesting: If a device driver can’t handle an IRP immediately, it must handle it asynchronously. So, the driver tells the disk to start writing and returns a “pending” response to the OS. The OS passes that “pending” response to the BCL, and the BCL returns an incomplete task to the request-handling code. The request-handling code awaits the task, which returns an incomplete task from that method and so on. Finally, the request-handling code ends up returning an incomplete task to ASP.NET, and the request thread is freed to return to the thread pool.
Introduction to Async/Await on ASP.NET
If the target is to improve scalability (rather than responsiveness), it all relies on the existence of an external I/O that provides the opportunity to do that.
Try this way..
public static HttpContext getCurrentSession()
{
HttpContext.Current = new HttpContext(new HttpRequest("", ConfigurationManager.AppSettings["UnitTestSessionURL"], ""), new HttpResponse(new System.IO.StringWriter()));
System.Web.SessionState.SessionStateUtility.AddHttpSessionStateToContext(
HttpContext.Current, new HttpSessionStateContainer("", new SessionStateItemCollection(), new HttpStaticObjectsCollection(), 20000, true,
HttpCookieMode.UseCookies, SessionStateMode.InProc, false));
return HttpContext.Current;
}
I had to implement a heap traversal which outputs in a BFS order. It isn't actually BFS but accomplishes the same task.
private void getNodeValue(Node node, int index, int[] array) {
array[index] = node.value;
index = (index*2)+1;
Node left = node.leftNode;
if (left!=null) getNodeValue(left,index,array);
Node right = node.rightNode;
if (right!=null) getNodeValue(right,index+1,array);
}
public int[] getHeap() {
int[] nodes = new int[size];
getNodeValue(root,0,nodes);
return nodes;
}
Do I understand right that you assume that DATE_ADD("2011-01-01", INTERVAL 6 MONTH)
should give you '2011-06-30' instead of '2011-07-01'? Of course, 2011-01-01 + 6 months is 2011-07-01. You want something like DATE_SUB(DATE_ADD("2011-01-01", INTERVAL 6 MONTH), INTERVAL 1 DAY)
.
sql = "INSERT INTO MyTable (Name) VALUES (@Name);" +
"SELECT CAST(scope_identity() AS int)";
SqlCommand cmd = new SqlCommand(sql, conn);
int newId = (int)cmd.ExecuteScalar();
you can achieve vertical aligning with display:table-cell
:
#section1 {
height: 90%;
text-align:center;
display:table;
width:100%;
}
#section1 h1 {display:table-cell; vertical-align:middle}
Update - CSS3
For an alternate way to vertical align, you can use the following css 3 which should be supported in all the latest browsers:
#section1 {
height: 90%;
width:100%;
display:flex;
align-items: center;
justify-content: center;
}
There isn't any in printf
- the two are synonyms.
Here is the docs from the zsh man pages under STARTUP/SHUTDOWN FILES section.
Commands are first read from /etc/zshenv this cannot be overridden.
Subsequent behaviour is modified by the RCS and GLOBAL_RCS options; the
former affects all startup files, while the second only affects global
startup files (those shown here with an path starting with a /). If
one of the options is unset at any point, any subsequent startup
file(s) of the corresponding type will not be read. It is also possi-
ble for a file in $ZDOTDIR to re-enable GLOBAL_RCS. Both RCS and
GLOBAL_RCS are set by default.
Commands are then read from $ZDOTDIR/.zshenv. If the shell is a login
shell, commands are read from /etc/zprofile and then $ZDOTDIR/.zpro-
file. Then, if the shell is interactive, commands are read from
/etc/zshrc and then $ZDOTDIR/.zshrc. Finally, if the shell is a login
shell, /etc/zlogin and $ZDOTDIR/.zlogin are read.
From this we can see the order files are read is:
/etc/zshenv # Read for every shell
~/.zshenv # Read for every shell except ones started with -f
/etc/zprofile # Global config for login shells, read before zshrc
~/.zprofile # User config for login shells
/etc/zshrc # Global config for interactive shells
~/.zshrc # User config for interactive shells
/etc/zlogin # Global config for login shells, read after zshrc
~/.zlogin # User config for login shells
~/.zlogout # User config for login shells, read upon logout
/etc/zlogout # Global config for login shells, read after user logout file
You can get more information here.
Updating Eli's answer to Python 3:
class Timer(object):
def __init__(self, name=None, filename=None):
self.name = name
self.filename = filename
def __enter__(self):
self.tstart = time.time()
def __exit__(self, type, value, traceback):
message = 'Elapsed: %.2f seconds' % (time.time() - self.tstart)
if self.name:
message = '[%s] ' % self.name + message
print(message)
if self.filename:
with open(self.filename,'a') as file:
print(str(datetime.datetime.now())+": ",message,file=file)
Just like Eli's, it can be used as a context manager:
import time
with Timer('Count'):
for i in range(0,10_000_000):
pass
Output:
[Count] Elapsed: 0.27 seconds
I have also updated it to print the units of time reported (seconds) and trim the number of digits as suggested by Can, and with the option of also appending to a log file. You must import datetime to use the logging feature:
import time
import datetime
with Timer('Count', 'log.txt'):
for i in range(0,10_000_000):
pass
For all who are interested in a swift extension, this is what I'm using now:
extension UINavigationController {
var rootViewController : UIViewController? {
return self.viewControllers.first
}
}
I for myself prefer Lukas Edger's solution.
But you might want to know there is also a function SYS_GUID which can be applied as a default value to a column and generate unique ids.
you can read more about pros and cons here
Maybe you are looking for this plyr::revalue function:
mutate(dat, x = revalue(x, c("A" = "B")))
You can see plyr::mapvalues too.
Try to update the package.json
file so that "@angular-devkit/build-angular": "^0.800.1"
reads "@angular-devkit/build-angular": "^0.12.4"
Then run npm install
in the command line.
Reference: https://stackoverflow.com/a/56537342
Though this question seems to be answered, another common issue that you can get is the DB user has been mis-configured. This is a mysql administration and permissions issue:
10.55.142.100
10.55.142.144
'root'@'localhost'
)'my_user'@'%' IDENTIFIED BY PASSWORD 'password'
mysql -umy_user -p -h ip-10-55-142-100.ec2.internal
as does host references to the explicit IP, public DNS, etc.Step 6 fails because the mysql DB has the wrong user permisions. It needs this:
GRANT ALL PRIVILEGES ON *.* TO 'my_user'@'ip-10-55-142-144.ec2.internal' IDENTIFIED BY PASSWORD 'password'
I would like to think that %
would work for any remote server, but I did not find this to be the case.
Please let me know if this helps you.
I do something like this where I just give each table a string name to identify it in column A, and a count for column. Then I union them all so they stack. The result is pretty in my opinion - not sure how efficient it is compared to other options but it got me what I needed.
select 'table1', count (*) from table1
union select 'table2', count (*) from table2
union select 'table3', count (*) from table3
union select 'table4', count (*) from table4
union select 'table5', count (*) from table5
union select 'table6', count (*) from table6
union select 'table7', count (*) from table7;
Result:
-------------------
| String | Count |
-------------------
| table1 | 123 |
| table2 | 234 |
| table3 | 345 |
| table4 | 456 |
| table5 | 567 |
-------------------
You could also do it by defining your own selector:
$.extend($.expr[':'],{
textboxEmpty: function(el){
return $(el).val() === "";
}
});
And then access them like this:
alert($(':text:textboxEmpty').length); //alerts the number of text boxes in your selection
@jeb
And after using this, the stderr seems to be inaccessible
No, try this:
@echo off 2>Nul 3>Nul 4>Nul
ben ali
mubarak 2>&1
gadeffi
..next ?
echo hello Tunisia
pause
But why it works?
sorry, i answer the question in frensh:
( la redirection par 3> est spécial car elle persiste, on va l'utiliser pour capturer le flux des erreurs 2> est on va le transformer en un flux persistant à l'ade de 3> ceci va nous permettre d'avoir une gestion des erreur pour tout notre environement de script..par la suite si on veux recuperer le flux 'stderr' il faut faire une autre redirection du handle 2> au handle 1> qui n'est autre que la console.. )
This function is fully configurable and generates unique uid based on the format specified
eg:- [8, 4, 4, 4, 12] , this is the format mentioned and it will generate the following uuid
LxoYNyXe-7hbQ-caJt-DSdU-PDAht56cMEWi
import random as r
def generate_uuid():
random_string = ''
random_str_seq = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
uuid_format = [8, 4, 4, 4, 12]
for n in uuid_format:
for i in range(0,n):
random_string += str(random_str_seq[r.randint(0, len(random_str_seq) - 1)])
if n != 12:
random_string += '-'
return random_string
Well, In my applications I just need to Add a reference to "DocumentFormat.OpenXml" under .Net tab and both references (DocumentFormat.OpenXml and WindowsBase) are always added automatically. But They are not included within the Bin folder. So when the Application is published to an external server I always place DocumentFormat.OpenXml.dll under the Bin folder manually. Or set the reference "Copy Local" property to true.
I had the same issue.For me the problem was how to configure a cache limit to images.And i came across this site which gave some insights to the procedure on how the issue can be handled.Hope it will be helpful for you too Link:[https://varvy.com/pagespeed/cache-control.html]
Overriding the input directive does seem to do the job. I made some minor alterations to Dan Hunsaker's code:
$parse().assign()
on fields without a ngModel attributes.assign()
function param order.app.directive('input', function ($parse) {
return {
restrict: 'E',
require: '?ngModel',
link: function (scope, element, attrs) {
if (attrs.ngModel && attrs.value) {
$parse(attrs.ngModel).assign(scope, attrs.value);
}
}
};
});
Without a separate step to extract the archive:
# import gzipped-mysql dump
gunzip < DUMP_FILE.sql.gz | mysql --user=DB_USER --password DB_NAME
I use the above snippet to re-import mysqldump-backups, and the following for backing it up.
# mysqldump and gzip (-9 ? highest compression)
mysqldump --user=DB_USER --password DB_NAME | gzip -9 > DUMP_FILE.sql.gz
You don't need HttpServletResponse to set a header on the response. You can do it using javax.ws.rs.core.Response. Just make your method to return Response instead of entity:
return Response.ok(entity).header("Content-Disposition", "attachment; filename=\"" + fileName + "\"").build()
If you still want to use HttpServletResponse you can get it either injected to one of the class fields, or using property, or to method parameter:
@Path("/resource")
class MyResource {
// one way to get HttpServletResponse
@Context
private HttpServletResponse anotherServletResponse;
// another way
Response myMethod(@Context HttpServletResponse servletResponse) {
// ... code
}
}
In my case, I forgot to add library jackson-core.jar, I only added jackson-annotations.jar and jackson-databind.jar. When I added jackson-core.jar, it fixed the problem.
@reannual's answer works well, but there's an issue with it: os.popen
is now deprecated. The subprocess
module should be used instead, so here's a version of @reannual's code that uses subprocess
and directly answers the question (by giving the column width directly as an int
:
import subprocess
columns = int(subprocess.check_output(['stty', 'size']).split()[1])
Tested on OS X 10.9
conda activate myEnv
conda list --explicit > myEnvBkp.txt
conda create --name myEnvRestored --file myEnvBkp.txt
In Python or Java or any high level language the .dump does not work. We need to code the conversion to CSV by hand. I give an Python example. Others, examples would be appreciated:
from os import path
import csv
def convert_to_csv(directory, db_name):
conn = sqlite3.connect(path.join(directory, db_name + '.db'))
cursor = conn.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = cursor.fetchall()
for table in tables:
table = table[0]
cursor.execute('SELECT * FROM ' + table)
column_names = [column_name[0] for column_name in cursor.description]
with open(path.join(directory, table + '.csv'), 'w') as csv_file:
csv_writer = csv.writer(csv_file)
csv_writer.writerow(column_names)
while True:
try:
csv_writer.writerow(cursor.fetchone())
except csv.Error:
break
If you have 'panel data, in other words many individual entries with id's add this to the with look and it also dumps summary statistics:
if 'id' in column_names:
with open(path.join(directory, table + '_aggregate.csv'), 'w') as csv_file:
csv_writer = csv.writer(csv_file)
column_names.remove('id')
column_names.remove('round')
sum_string = ','.join('sum(%s)' % item for item in column_names)
cursor.execute('SELECT round, ' + sum_string +' FROM ' + table + ' GROUP BY round;')
csv_writer.writerow(['round'] + column_names)
while True:
try:
csv_writer.writerow(cursor.fetchone())
except csv.Error:
break
In Linux:
java -version
In Windows:
java.exe -version
If you need more info about the JVM you can call the executable with the parameter -XshowSettings:properties
. It will show a lot of System Properties. These properties can also be accessed by means of the static method System.getProperty(String)
in a Java class. As example this is an excerpt of some of the properties that can be obtained:
$ java -XshowSettings:properties -version
[...]
java.specification.version = 1.7
java.vendor = Oracle Corporation
java.vendor.url = http://java.oracle.com/
java.vendor.url.bug = http://bugreport.sun.com/bugreport/
java.version = 1.7.0_95
[...]
So if you need to access any of these properties from Java code you can use:
System.getProperty("java.specification.version");
System.getProperty("java.vendor");
System.getProperty("java.vendor.url");
System.getProperty("java.version");
Take into account that sometimes the vendor is not exposed as clear as Oracle or IBM. For example,
$ java version
"1.6.0_22" Java(TM) SE Runtime Environment (build 1.6.0_22-b04) Java HotSpot(TM) Client VM (build 17.1-b03, mixed mode, sharing)
HotSpot is what Oracle calls their implementation of the JVM. Check this list if the vendor does not seem to be shown with -version
.
Just to add to the answers above,
I was having a 2 regular buttons as shown below. (No type="submit"anywhere)
<button ng-click="clearAll();" class="btn btn-default">Clear Form</button>
<button ng-disabled="form.$invalid" ng-click="submit();"class="btn btn-primary pull-right">Submit</button>
No matter how much i tried, pressing enter once the form was valid, the "Clear Form" button was called, clearing the entire form.
As a workaround,
I had to add a dummy submit button which was disabled and hidden. And This dummy button had to be on top of all the other buttons as shown below.
<button type="submit" ng-hide="true" ng-disabled="true">Dummy</button>
<button ng-click="clearAll();" class="btn btn-default">Clear Form</button>
<button ng-disabled="form.$invalid" ng-click="submit();"class="btn btn-primary pull-right">Submit</button>
Well, my intention was never to submit on Enter, so the above given hack just works fine.
This worked for me:
access_token = #yourAccessTokenHere#
result = requests.post(url,
headers={'Content-Type':'application/json',
'Authorization': 'Bearer {}'.format(access_token)})
I experienced the same issue on nginx server (DigitalOcean) - all I had to do is to log in as root
and modify the file /etc/php5/fpm/php.ini
.
To find the line with the always_populate_raw_post_data
I first run grep
:
grep -n 'always_populate_raw_post_data' php.ini
That returned the line 704
704:;always_populate_raw_post_data = -1
Then simply open php.ini
on that line with vi
editor:
vi +704 php.ini
Remove the semi colon to uncomment it and save the file :wq
Lastly reboot the server and the error went away.
Assigning debounce in methods
can be trouble. So instead of this:
// Bad
methods: {
foo: _.debounce(function(){}, 1000)
}
You may try:
// Good
created () {
this.foo = _.debounce(function(){}, 1000);
}
It becomes an issue if you have multiple instances of a component - similar to the way data
should be a function that returns an object. Each instance needs its own debounce function if they are supposed to act independently.
Here's an example of the problem:
Vue.component('counter', {_x000D_
template: '<div>{{ i }}</div>',_x000D_
data: function(){_x000D_
return { i: 0 };_x000D_
},_x000D_
methods: {_x000D_
// DON'T DO THIS_x000D_
increment: _.debounce(function(){_x000D_
this.i += 1;_x000D_
}, 1000)_x000D_
}_x000D_
});_x000D_
_x000D_
_x000D_
new Vue({_x000D_
el: '#app',_x000D_
mounted () {_x000D_
this.$refs.counter1.increment();_x000D_
this.$refs.counter2.increment();_x000D_
}_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>_x000D_
_x000D_
<div id="app">_x000D_
<div>Both should change from 0 to 1:</div>_x000D_
<counter ref="counter1"></counter>_x000D_
<counter ref="counter2"></counter>_x000D_
</div>
_x000D_
UPDATE
If you are working in a particular project I highly recommend using editorconfig.
It lets you define an .editorconfig
file at the root of your repository defining the indentation you want to use for each file type across your repository.
For example:
root = true
[*.css]
charset = utf-8
indent_style = space
indent_size = 4
[*.js]
charset = utf-8
indent_style = space
indent_size = 2
There is a vim plugin that automatically configures vim according to the config file for file you open.
On top of that the .editorconfig
file is automatically supported on many other IDEs and editors so it is the best option for collaborating between users with different environments.
ORIGINAL ANSWER
If you need to change sizes often and you don't want to bind this to a specific file type you can have predefined commands on your .vimrc file to quickly switch preferences:
nmap <leader>t :set expandtab tabstop=4 shiftwidth=4 softtabstop=4<CR>
nmap <leader>m :set expandtab tabstop=2 shiftwidth=2 softtabstop=2<CR>
This maps two different sets of sizes to keys \t and \m. You can rebind this to whatever keys you want.
Use IFERROR(value, value_if_error)
If you are using resources, you can manually force it by:
Resource1.Culture = new System.Globalization.CultureInfo("fr");
In the resource manager, there is an auto generated code that is as follows:
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
Now every time you refer to your individual string within this resource, it overrides the culture (thread or process) with the specified resourceCulture.
You can either specify language as in "fr", "de" etc. or put the language code as in 0x0409 for en-US or 0x0410 for it-IT. For a full list of language codes please refer to: Language Identifiers and Locales
Select 'YOU WILL SEE ME' as ANSWER from dual
where exists (select 1 from dual where 1 = 1);
Select 'YOU CAN NOT SEE ME' as ANSWER from dual
where exists (select 1 from dual where 1 = 0);
Select 'YOU WILL SEE ME, TOO' as ANSWER from dual
where not exists (select 1 from dual where 1 = 0);
You can simple try String(); to remove the quotes.
Refer the first example here: https://www.w3schools.com/jsref/jsref_string.asp
Thank me later.
PS: TO MODs: don't mistaken me for digging the dead old question. I faced this issue today and I came across this post while searching for the answer and I'm just posting the answer.
I'd recommend using some work queue using, for example, the excellent Gearman, which will provide you with a great way to dispatch background jobs, and asynchronously get their result once they're processed.
The advantage of this, used heavily at Digg (among many others) is that it provides a strong, scalable and robust way to make workers in any language to speak with clients in any language.
Here (in below snippet) is comparison of chosen available browser "built-in" methods and their execution sequence. Remarks
document.onload
(X) is not supported by any modern browser (event is never fired)<body onload="bodyOnLoad()">
(F) and at the same time window.onload
(E) then only first one will be executed (because it override second one)<body onload="...">
(F) is wrapped by additional onload
functiondocument.onreadystatechange
(D) not override document .addEventListener('readystatechange'...)
(C) probably cecasue onXYZevent-like
methods are independent than addEventListener
queues (which allows add multiple listeners). Probably nothing happens between execution this two handlers.div
write their timestamps also in body (click "Full Page" link after script execution to see it).readystatechange
(C,D) are executed multiple times by browser but for different document states:DOMContentLoaded
body/window onload
<html>
<head>
<script>
// solution A
console.log(`[timestamp: ${Date.now()}] A: Head script`) ;
// solution B
document.addEventListener("DOMContentLoaded", () => {
print(`[timestamp: ${Date.now()}] B: DOMContentLoaded`);
});
// solution C
document.addEventListener('readystatechange', () => {
print(`[timestamp: ${Date.now()}] C: ReadyState: ${document.readyState}`);
});
// solution D
document.onreadystatechange = s=> {print(`[timestamp: ${Date.now()}] D: document.onreadystatechange ReadyState: ${document.readyState}`)};
// solution E (never executed)
window.onload = () => {
print(`E: <body onload="..."> override this handler`);
};
// solution F
function bodyOnLoad() {
print(`[timestamp: ${Date.now()}] F: <body onload='...'>`);
infoAboutOnLoad(); // additional info
}
// solution X
document.onload = () => {print(`document.onload is never fired`)};
// HELPERS
function print(txt) {
console.log(txt);
if(mydiv) mydiv.innerHTML += txt.replace('<','<').replace('>','>') + '<br>';
}
function infoAboutOnLoad() {
console.log("window.onload (after override):", (''+document.body.onload).replace(/\s+/g,' '));
console.log(`body.onload==window.onload --> ${document.body.onload==window.onload}`);
}
console.log("window.onload (before override):", (''+document.body.onload).replace(/\s+/g,' '));
</script>
</head>
<body onload="bodyOnLoad()">
<div id="mydiv"></div>
<!-- this script must te at the bottom of <body> -->
<script>
// solution G
print(`[timestamp: ${Date.now()}] G: <body> bottom script`);
</script>
</body>
</html>
_x000D_
PARTITION BY
segregate sets, this enables you to be able to work(ROW_NUMBER(),COUNT(),SUM(),etc) on related set independently.
In your query, the related set comprised of rows with similar cdt.country_code, cdt.account, cdt.currency. When you partition on those columns and you apply ROW_NUMBER on them. Those other columns on those combination/set will receive sequential number from ROW_NUMBER
But that query is funny, if your partition by some unique data and you put a row_number on it, it will just produce same number. It's like you do an ORDER BY on a partition that is guaranteed to be unique. Example, think of GUID as unique combination of cdt.country_code, cdt.account, cdt.currency
newid()
produces GUID, so what shall you expect by this expression?
select
hi,ho,
row_number() over(partition by newid() order by hi,ho)
from tbl;
...Right, all the partitioned(none was partitioned, every row is partitioned in their own row) rows' row_numbers are all set to 1
Basically, you should partition on non-unique columns. ORDER BY on OVER needed the PARTITION BY to have a non-unique combination, otherwise all row_numbers will become 1
An example, this is your data:
create table tbl(hi varchar, ho varchar);
insert into tbl values
('A','X'),
('A','Y'),
('A','Z'),
('B','W'),
('B','W'),
('C','L'),
('C','L');
Then this is analogous to your query:
select
hi,ho,
row_number() over(partition by hi,ho order by hi,ho)
from tbl;
What will be the output of that?
HI HO COLUMN_2
A X 1
A Y 1
A Z 1
B W 1
B W 2
C L 1
C L 2
You see thee combination of HI HO? The first three rows has unique combination, hence they are set to 1, the B rows has same W, hence different ROW_NUMBERS, likewise with HI C rows.
Now, why is the ORDER BY
needed there? If the previous developer merely want to put a row_number on similar data (e.g. HI B, all data are B-W, B-W), he can just do this:
select
hi,ho,
row_number() over(partition by hi,ho)
from tbl;
But alas, Oracle(and Sql Server too) doesn't allow partition with no ORDER BY
; whereas in Postgresql, ORDER BY
on PARTITION is optional: http://www.sqlfiddle.com/#!1/27821/1
select
hi,ho,
row_number() over(partition by hi,ho)
from tbl;
Your ORDER BY
on your partition look a bit redundant, not because of the previous developer's fault, some database just don't allow PARTITION
with no ORDER BY
, he might not able find a good candidate column to sort on. If both PARTITION BY columns and ORDER BY columns are the same just remove the ORDER BY, but since some database don't allow it, you can just do this:
SELECT cdt.*,
ROW_NUMBER ()
OVER (PARTITION BY cdt.country_code, cdt.account, cdt.currency
ORDER BY newid())
seq_no
FROM CUSTOMER_DETAILS cdt
You cannot find a good column to use for sorting similar data? You might as well sort on random, the partitioned data have the same values anyway. You can use GUID for example(you use newid()
for SQL Server). So that has the same output made by previous developer, it's unfortunate that some database doesn't allow PARTITION
with no ORDER BY
Though really, it eludes me and I cannot find a good reason to put a number on the same combinations (B-W, B-W in example above). It's giving the impression of database having redundant data. Somehow reminded me of this: How to get one unique record from the same list of records from table? No Unique constraint in the table
It really looks arcane seeing a PARTITION BY with same combination of columns with ORDER BY, can not easily infer the code's intent.
Live test: http://www.sqlfiddle.com/#!3/27821/6
But as dbaseman have noticed also, it's useless to partition and order on same columns.
You have a set of data like this:
create table tbl(hi varchar, ho varchar);
insert into tbl values
('A','X'),
('A','X'),
('A','X'),
('B','Y'),
('B','Y'),
('C','Z'),
('C','Z');
Then you PARTITION BY hi,ho; and then you ORDER BY hi,ho. There's no sense numbering similar data :-) http://www.sqlfiddle.com/#!3/29ab8/3
select
hi,ho,
row_number() over(partition by hi,ho order by hi,ho) as nr
from tbl;
Output:
HI HO ROW_QUERY_A
A X 1
A X 2
A X 3
B Y 1
B Y 2
C Z 1
C Z 2
See? Why need to put row numbers on same combination? What you will analyze on triple A,X, on double B,Y, on double C,Z? :-)
You just need to use PARTITION on non-unique column, then you sort on non-unique column(s)'s unique-ing column. Example will make it more clear:
create table tbl(hi varchar, ho varchar);
insert into tbl values
('A','D'),
('A','E'),
('A','F'),
('B','F'),
('B','E'),
('C','E'),
('C','D');
select
hi,ho,
row_number() over(partition by hi order by ho) as nr
from tbl;
PARTITION BY hi
operates on non unique column, then on each partitioned column, you order on its unique column(ho), ORDER BY ho
Output:
HI HO NR
A D 1
A E 2
A F 3
B E 1
B F 2
C D 1
C E 2
That data set makes more sense
Live test: http://www.sqlfiddle.com/#!3/d0b44/1
And this is similar to your query with same columns on both PARTITION BY and ORDER BY:
select
hi,ho,
row_number() over(partition by hi,ho order by hi,ho) as nr
from tbl;
And this is the ouput:
HI HO NR
A D 1
A E 1
A F 1
B E 1
B F 1
C D 1
C E 1
See? no sense?
Live test: http://www.sqlfiddle.com/#!3/d0b44/3
Finally this might be the right query:
SELECT cdt.*,
ROW_NUMBER ()
OVER (PARTITION BY cdt.country_code, cdt.account -- removed: cdt.currency
ORDER BY
-- removed: cdt.country_code, cdt.account,
cdt.currency) -- keep
seq_no
FROM CUSTOMER_DETAILS cdt
I sort of agree with leander on this one.
call:
new calc_stanica().execute(stringList.toArray(new String[stringList.size()]));
task:
public class calc_stanica extends AsyncTask<String, Void, ArrayList<String>> {
@Override
protected ArrayList<String> doInBackground(String... args) {
...
}
@Override
protected void onPostExecute(ArrayList<String> result) {
... //do something with the result list here
}
}
Or you could just make the result list a class parameter and replace the ArrayList with a boolean (success/failure);
public class calc_stanica extends AsyncTask<String, Void, Boolean> {
private List<String> resultList;
@Override
protected boolean doInBackground(String... args) {
...
}
@Override
protected void onPostExecute(boolean success) {
... //if successfull, do something with the result list here
}
}
In order to get the http status code returned from the server, you can add validateStatus: status => true
to axios options:
axios({
method: 'POST',
url: 'http://localhost:3001/users/login',
data: { username, password },
validateStatus: () => true
}).then(res => {
console.log(res.status);
});
This way, every http response resolves the promise returned from axios.
After much further research, i managed to find a solution.
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
function placeMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
}
I don't think this can be done but I found a workaround using alias
. It will only work when you place your script in your scripts directory, otherwise your alias will have an invalid name. The only point to the work around is to be able to have a function inside a file with the same name and not have to bother sourcing it before using it. Add the following code to ~/.bashrc
:
alias myFunction='unalias myFunction && . myFunction && myFunction "$@"'
You can now call myFunction
without sourcing it first.
An educational example from the stat documentation:
import os, sys
from stat import *
def walktree(top, callback):
'''recursively descend the directory tree rooted at top,
calling the callback function for each regular file'''
for f in os.listdir(top):
pathname = os.path.join(top, f)
mode = os.stat(pathname)[ST_MODE]
if S_ISDIR(mode):
# It's a directory, recurse into it
walktree(pathname, callback)
elif S_ISREG(mode):
# It's a file, call the callback function
callback(pathname)
else:
# Unknown file type, print a message
print 'Skipping %s' % pathname
def visitfile(file):
print 'visiting', file
if __name__ == '__main__':
walktree(sys.argv[1], visitfile)
The DroidUX component library has a ColorButton
widget whose color can be changed easily, both via xml definition and programmatically at run time, so you can even let the user to set the button's color/theme if your app allows it.
It is quite simple because you are using the FXMLBuilder.
Just follow these simple steps:
Note that if you only need one column from the table then using 'lists' is quite nice. In my case i am retrieving a user's favourite articles but i only want the article id's:
$favourites = $user->favourites->lists('id');
Returns an array of ids, eg:
Array
(
[0] => 3
[1] => 7
[2] => 8
)
In sybase_driver.php
/**
* Manejador de Mensajes de Error Sybase
* Autor: Isaí Moreno
* Fecha: 06/Nov/2019
*/
static $CODE_ERROR_SYBASE;
public static function SetCodeErrorSybase($Code) {
if ($Code != 3621) { /*No se toma en cuenta el código de command aborted*/
CI_DB_sybase_driver::$CODE_ERROR_SYBASE = trim(CI_DB_sybase_driver::$CODE_ERROR_SYBASE.' '.$Code);
}
}
public static function GetCodeErrorSybase() {
return CI_DB_sybase_driver::$CODE_ERROR_SYBASE;
}
public static function msg_handler($msgnumber, $severity, $state, $line, $text)
{
log_message('info', 'CI_DB_sybase_driver - CODE ERROR ['.$msgnumber.'] Mensaje - '.$text);
CI_DB_sybase_driver::SetCodeErrorSybase($msgnumber);
}
// ------------------------------------------------------------------------
Add and modify the following methods in the same sybase_driver.php file
/**
* The error message number
*
* @access private
* @return integer
*/
function _error_number()
{
// Are error numbers supported?
return CI_DB_sybase_driver::GetCodeErrorSybase();
}
function _sybase_set_message_handler()
{
// Are error numbers supported?
return sybase_set_message_handler('CI_DB_sybase_driver::msg_handler');
}
Implement in the function of a controller.
public function Eliminar_DUPLA(){
if($this->session->userdata($this->config->item('mycfg_session_object_name'))){
//***/
$Operacion_Borrado_Exitosa=false;
$this->db->trans_begin();
$this->db->_sybase_set_message_handler(); <<<<<------- Activar Manejador de errores de sybase
$Dupla_Eliminada=$this->Mi_Modelo->QUERY_Eliminar_Dupla($PARAMETROS);
if ($Dupla_Eliminada){
$this->db->trans_commit();
MostrarNotificacion("Se eliminó DUPLA exitosamente","OK",true);
$Operacion_Borrado_Exitosa=true;
}else{
$Error = $this->db->_error_number(); <<<<----- Obtengo el código de error de sybase para personilzar mensaje al usuario
$this->db->trans_rollback();
MostrarNotificacion("Ocurrio un error al intentar eliminar Dupla","Error",true);
if ($Error == 547) {
MostrarNotificacion("<strong>Código de error :[".$Error.']. No se puede eliminar documento Padre.</strong>',"Error",true);
} else {
MostrarNotificacion("<strong>Código de Error :[".$Error.']</strong><br>',"Error",true);
}
}
echo "@".Obtener_Contador_Notificaciones();
if ($Operacion_Borrado_Exitosa){
echo "@T";
}else{
echo "@F";
}
}else{
redirect($this->router->default_controller);
}
}
In the log you can check the codes and messages sent by the database server.
INFO - 2019-11-06 19:26:33 -> CI_DB_sybase_driver - CODE ERROR [547] Message - Dependent foreign key constraint violation in a referential integrity constraint. dbname = 'database', table name = 'mitabla', constraint name = 'FK_SR_RELAC_REFERENCE_SR_mitabla'. INFO - 2019-11-06 19:26:33 -> CI_DB_sybase_driver - CODE ERROR [3621] Message - Command has been aborted. ERROR - 2019-11-06 19:26:33 -> Query error: - Invalid query: delete from mitabla where ID = 1019.
class YourCollection: UIViewController,
UICollectionViewDelegate,
UICollectionViewDataSource {
class YourCollection: UIViewController,
UICollectionViewDelegate,
UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout {
class YourCollection: UIViewController,
UICollectionViewDelegate,
UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 37, height: 63)
}
That's it.
Example, if you want "each cell fills the whole collection view":
guard let b = view.superview?.bounds else { .. }
return CGSize(width: b.width, height: b.height)
If you added JComponent
to already visible Container, then you have call
frame.getContentPane().validate();
frame.getContentPane().repaint();
for example
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(460, 500);
frame.setTitle("Circles generator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame.setVisible(true);
}
});
String input = JOptionPane.showInputDialog("Enter n:");
CustomComponents0 component = new CustomComponents0();
frame.add(component);
frame.getContentPane().validate();
frame.getContentPane().repaint();
}
static class CustomComponents0 extends JLabel {
private static final long serialVersionUID = 1L;
@Override
public Dimension getMinimumSize() {
return new Dimension(200, 100);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(300, 200);
}
@Override
public void paintComponent(Graphics g) {
int margin = 10;
Dimension dim = getSize();
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(margin, margin, dim.width - margin * 2, dim.height - margin * 2);
}
}
}
Check the PASSWORD_LOCK_TIME
parameter. If it is set to 1 then you won't be able to unlock the password for 1 day even after you issue the alter user unlock
command.
Last version to support windows XP (SP3) is mono-4.3.2.467-gtksharp-2.12.30.1-win32-0.msi and that doesnot replace .NET 4.5 but could be of interest for some applications.
see there: https://download.mono-project.com/archive/4.3.2/windows-installer/
Try this one for current selection:
Sub A_SelectAllMakeTable2()
Dim tbl As ListObject
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
tbl.TableStyle = "TableStyleMedium15"
End Sub
or equivalent of your macro (for Ctrl+Shift+End range selection):
Sub A_SelectAllMakeTable()
Dim tbl As ListObject
Dim rng As Range
Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
tbl.TableStyle = "TableStyleMedium15"
End Sub
I'm using jupyter_core-4.4.0
& jupyter notebook.
![Screen%20Shot%202019-08-06%20at%201.48.10%20PM.png](attachment:Screen%20Shot%202019-08-06%20at%201.48.10%20PM.png)
attachment
links don't work:<img src="attachment:Screen%20Shot%202019-08-06%20at%201.48.10%20PM.png" width="500"/>
Just add div brackets.
<div>
<img src="attachment:Screen%20Shot%202019-08-06%20at%201.48.10%20PM.png" width="500"/>
</div>
Hope this helps!
Well, you're going to have to check for null somewhere. You could do something like this:
from item in db.vw_Dropship_OrderItems
where (listStatus == null || listStatus.Contains(item.StatusCode))
&& (listMerchants == null || listMerchants.Contains(item.MerchantId))
select item;
The path to the nginx.conf
file which is the primary Configuration file for Nginx - which is also the file which shall INCLUDE the Path for other Nginx Config files as and when required is /etc/nginx/nginx.conf
.
You may access and edit this file by typing this at the terminal
cd /etc/nginx
/etc/nginx$ sudo nano nginx.conf
Further in this file you may Include other files - which can have a SERVER directive as an independent SERVER BLOCK - which need not be within the HTTP or HTTPS blocks, as is clarified in the accepted answer above.
I repeat - if you need a SERVER BLOCK to be defined within the PRIMARY Config file itself than that SERVER BLOCK will have to be defined within an enclosing HTTP or HTTPS block in the /etc/nginx/nginx.conf
file which is the primary Configuration file for Nginx.
Also note -its OK if you define , a SERVER BLOCK directly not enclosing it within a HTTP or HTTPS block , in a file located at path /etc/nginx/conf.d
. Also to make this work you will need to include the path of this file in the PRIMARY Config file as seen below :-
http{
include /etc/nginx/conf.d/*.conf; #includes all files of file type.conf
}
Further to this you may comment out from the PRIMARY Config file , the line
http{
#include /etc/nginx/sites-available/some_file.conf; # Comment Out
include /etc/nginx/conf.d/*.conf; #includes all files of file type.conf
}
and need not keep any Config Files in /etc/nginx/sites-available/
and also no need to SYMBOLIC Link them to /etc/nginx/sites-enabled/
, kindly note this works for me - in case anyone think it doesnt for them or this kind of config is illegal etc etc , pls do leave a comment so that i may correct myself - thanks .
EDIT :- According to the latest version of the Official Nginx CookBook , we need not create any Configs within - /etc/nginx/sites-enabled/
, this was the older practice and is DEPRECIATED now .
Thus No need for the INCLUDE DIRECTIVE include /etc/nginx/sites-available/some_file.conf;
.
Quote from Nginx CookBook page - 5 .
"In some package repositories, this folder is named sites-enabled, and configuration files are linked from a folder named site-available; this convention is depre- cated."
Bootstrap's CSS for the .container
class looks like that:
.container {
padding-right: 15px;
padding-left: 15px;
margin-right: auto;
margin-left: auto;
}
@media (min-width: 768px) {
.container {
width: 750px;
}
}
@media (min-width: 992px) {
.container {
width: 970px;
}
}
@media (min-width: 1200px) {
.container {
width: 1170px;
}
}
So this means we can safely rely on jQuery('.container').css('width')
to detect breakpoints without the drawbacks of relying on jQuery(window).width()
.
We can write a function like this:
function detectBreakpoint() {
// Let's ensure we have at least 1 container in our pages.
if (jQuery('.container').length == 0) {
jQuery('body').append('<div class="container"></div>');
}
var cssWidth = jQuery('.container').css('width');
if (cssWidth === '1170px') return 'lg';
else if (cssWidth === '970px') return 'md';
else if (cssWidth === '750px') return 'sm';
return 'xs';
}
And then test it like
jQuery(document).ready(function() {
jQuery(window).resize(function() {
jQuery('p').html('current breakpoint is: ' + detectBreakpoint());
});
detectBreakpoint();
});
-- Login to psql and run the following
-- What is the result?
SELECT MAX(id) FROM your_table;
-- Then run...
-- This should be higher than the last result.
SELECT nextval('your_table_id_seq');
-- If it's not higher... run this set the sequence last to your highest id.
-- (wise to run a quick pg_dump first...)
BEGIN;
-- protect against concurrent inserts while you update the counter
LOCK TABLE your_table IN EXCLUSIVE MODE;
-- Update the sequence
SELECT setval('your_table_id_seq', COALESCE((SELECT MAX(id)+1 FROM your_table), 1), false);
COMMIT;
You can use .replaceWith()
$(function() {_x000D_
_x000D_
$(".region").click(function(e) {_x000D_
e.preventDefault();_x000D_
var content = $(this).html();_x000D_
$('#map').replaceWith('<div class="region">' + content + '</div>');_x000D_
});_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="map">_x000D_
<div class="region"><a href="link1">region1</a></div>_x000D_
<div class="region"><a href="link2">region2</a></div>_x000D_
<div class="region"><a href="link3">region3</a></div>_x000D_
</div>
_x000D_
One option is to use a numbers/tally table to drive an iterative process via a pseudo-set based query.
The general idea of char replacement can be demonstrated with a simple character map table approach:
create table charMap (srcChar char(1), replaceChar char(1))
insert charMap values ('a', 'z')
insert charMap values ('b', 'y')
create table testChar(srcChar char(1))
insert testChar values ('1')
insert testChar values ('a')
insert testChar values ('2')
insert testChar values ('b')
select
coalesce(charMap.replaceChar, testChar.srcChar) as charData
from testChar left join charMap on testChar.srcChar = charMap.srcChar
Then you can bring in the tally table approach to do the lookup on each character position in the string.
create table tally (i int)
declare @i int
set @i = 1
while @i <= 256 begin
insert tally values (@i)
set @i = @i + 1
end
create table testData (testString char(10))
insert testData values ('123a456')
insert testData values ('123ab456')
insert testData values ('123b456')
select
i,
SUBSTRING(testString, i, 1) as srcChar,
coalesce(charMap.replaceChar, SUBSTRING(testString, i, 1)) as charData
from testData cross join tally
left join charMap on SUBSTRING(testString, i, 1) = charMap.srcChar
where i <= LEN(testString)