Python strings are immutable. However, a
is not a string: it is a variable with a string value. You can't mutate the string, but can change what value of the variable to a new string.
For finding a simple string, using the indexOf() method and using regex is pretty much the same: http://jsperf.com/substring - so choose which ever one that seems easier to write.
You can try my suggestion for a work around in Doug's approach.
But if you want to stick with your logic though, you can try this:
Option Explicit
Sub GetUnique()
Dim rng As Range
Dim myarray, myunique
Dim i As Integer
ReDim myunique(1)
With ThisWorkbook.Sheets("Sheet1")
Set rng = .Range(.Range("A1"), .Range("A" & .Rows.Count).End(xlUp))
myarray = Application.Transpose(rng)
For i = LBound(myarray) To UBound(myarray)
If IsError(Application.Match(myarray(i), myunique, 0)) Then
myunique(UBound(myunique)) = myarray(i)
ReDim Preserve myunique(UBound(myunique) + 1)
End If
Next
End With
For i = LBound(myunique) To UBound(myunique)
Debug.Print myunique(i)
Next
End Sub
This uses array instead of range.
It also uses Match
function instead of a nested For Loop
.
I didn't have the time to check the time difference though.
So I leave the testing to you.
The only thing that worked for me:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().anyRequest().permitAll();
}
and
security.ignored=/**
Could be that the properties part is redundant or can be done in code, but had no time to experiment. Anyway is temporary.
You can use exec
:
exec("import myapp.commands.%s" % command)
If you:
Below was benchmarked on a ~10Mb xlsx
, xlsb
file.
xlsx, xls
from openpyxl import load_workbook
def get_sheetnames_xlsx(filepath):
wb = load_workbook(filepath, read_only=True, keep_links=False)
return wb.sheetnames
Benchmarks: ~ 14x speed improvement
# get_sheetnames_xlsx vs pd.read_excel
225 ms ± 6.21 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
3.25 s ± 140 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
xlsb
from pyxlsb import open_workbook
def get_sheetnames_xlsb(filepath):
with open_workbook(filepath) as wb:
return wb.sheets
Benchmarks: ~ 56x speed improvement
# get_sheetnames_xlsb vs pd.read_excel
96.4 ms ± 1.61 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
5.36 s ± 162 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Notes:
xlrd
is no longer maintained as of 2020You might install Microsoft Loopback driver that will create a separate interface for you. Then you can connect on it to some service of yours (your own host). Then in Network Connections you can disable/enable such interface...
Number (2) is possible by using a socket implementation (like websocket, socket.io, etc.) with a custom heartbeat for each session the user is engaged in. If a user attempts to open another window, you have a javascript handler check with the server if it's ok, and then respond with an error messages.
However, a better solution is to synchronize the two sessions if possible like in google docs.
The query either returned no rows or is erroneus, thus FALSE
is returned. Change it to
if (!$dbc || mysqli_num_rows($dbc) == 0)
mysqli_num_rows
:
Return Values
Returns TRUE on success or FALSE on failure. For SELECT, SHOW, DESCRIBE or EXPLAIN mysqli_query() will return a result object.
You are giving multiple Content-Type
headers. application/vnd.ms-excel
is enough.
And there are couple of syntax error too. To statement termination with ;
on the echo statement and wrong filename extension.
header("Content-Type: application/vnd.ms-excel; charset=utf-8");
header("Content-Disposition: attachment; filename=abc.xls"); //File name extension was wrong
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
echo "Some Text"; //no ending ; here
Not very elegant, but I add a set value with the same number of leading zeroes I desire to the numeric I want to convert, and use RIGHT function.
Example:
SELECT RIGHT(CONVERT(CHAR(7),1000000 + @number2),6)
Result: '000867'
I got this error message too.
and what makes me think it is useful to give an answer here is that the answer from @Rafal Rawicki is a good solution in some cases but not for all circumstances. example that i met:
1.run "git log" we can get the HEAD commit change-id
2.we also can get a 'HEAD' commit change-id on Gerrit website.
3.they are different ,which makes us can not push successfully and get the "missing change-id error"
solution:
0.'git add .'
1.save your HEAD commit change-id got from 'git log',it will be used later.
2.copy the HEAD commit change-id from Gerrit website.
3.'git reset HEAD'
4.'git commit --amend' and copy the change-id from **Gerrit website** to the commit message in the last paragraph(replace previous change-id)
5.'git push *' you can push successfully now but can not find the HEAD commit from **git log** on Gerrit website too
6.'git reset HEAD'
7.'git commit --amend' and copy the change-id from **git log**(we saved in step 1) to the commit message in the last paragraph(replace previous change-id)
8.'git push *' you can find the HEAD commit from **git log** on Gerrit website,they have the same change-id
9.done
maxAge = Persons.Max(c => c.age)
or something along those lines.
The way I'd do this is:
="'"&K2
Ctrl+D
to fill it down to the length of Column K's values.For those using a fresh install of Ubuntu, or another Linux distro, make sure your have at least the package "build-essential" before you try to compile Eclipse CDT projects.
At Terminal, type:
sudo apt-get install build-essential
It should be enough to compile and run your apps.
Of course, you can also perform full g++ install, using:
sudo apt-get install g++
change_column_default :employees, :foreign, false
At the application level, the application uses TCP as a stream oriented protocol. TCP in turn has segments and abstracts away the details of working with unreliable IP packets.
TCP deals with segments instead of packets. Each TCP segment has a sequence number which is contained inside a TCP header. The actual data sent in a TCP segment is variable.
There is a value for getsockopt that is supported on some OS that you can use called TCP_MAXSEG which retrieves the maximum TCP segment size (MSS). It is not supported on all OS though.
I'm not sure exactly what you're trying to do but if you want to reduce the buffer size that's used you could also look into: SO_SNDBUF and SO_RCVBUF.
It worked for me:
General -> Encryption -> Only use plain FTP
Transfer settings -> Transfer Mode -> Active
Consider that it is very insecure, and must be used only for testing.
You can use the following code snippet. readlines() reads in the whole file at once and splits it by line.
line = obj.readlines()
url
prop is deprecated as of Next.js version 6:
https://github.com/zeit/next.js/blob/master/errors/url-deprecated.md
To get the query parameters, use getInitialProps
:
import Link from 'next/link'
const About = ({query}) => (
<div>Click <Link href={{ pathname: 'about', query: { name: 'leangchhean' }}}><a>here</a></Link> to read more</div>
)
About.getInitialProps = ({query}) => {
return {query}
}
export default About;
class About extends React.Component {
static getInitialProps({query}) {
return {query}
}
render() {
console.log(this.props.query) // The query is available in the props object
return <div>Click <Link href={{ pathname: 'about', query: { name: 'leangchhean' }}}><a>here</a></Link> to read more</div>
}
}
The query object will be like: url.com?a=1&b=2&c=3
becomes: {a:1, b:2, c:3}
An old thread, but a useful one... so here's some additional code.
First, in response to Craig's point about the regex being overly greedy and failing for sheet names containing a single quote, this should do the trick (replace 'SHEETNAME'!A1 with your own sheet & cell reference):
=IF(TODAY()=TODAY(), SUBSTITUTE(REGEXREPLACE(CELL("address",'SHEETNAME'!A1),"'?(.+?)'?!\$.*","$1"),"''","'", ""), "")
It uses a lazy match (the ".+?") to find a character string (squotes included) that may or may not be enclosed by squotes but is definitely terminated by bang dollar ("!$") followed by any number of characters. Google Sheets actually protects squotes within a sheet name by appending another squote (as in ''), so the SUBSTITUTE is needed to reduce these back to single squotes.
The formula also allows for sheet names that contain bangs ("!"), but will fail for names using bang dollars ("!$") - if you really need to make your sheet names to look like full absolute cell references then put a separating character between the bang and the dollar (such as a space).
Note that it will only work correctly when pointed at a different sheet from the one that the formula resides! This is because CELL("address" returns just the cell reference (not the sheet name) when used on the same sheet. If you need a sheet to show its own name then put the formula in a cell on another sheet, point it at your target sheet, and then reference the formula cell from the target sheet. I often have a "Meta" sheet in my workbooks to hold settings, common values, database matching criteria, etc so that's also where I put this formula.
As others have said many times above, Google Sheets will only notice changes to the sheet name if you set the workbook's recalculation to "On change and every minute" which you can find on the File|Settings|Calculation menu. It can take up to a whole minute for the change to be picked up.
Secondly, if like me you happen to need an inter-operable formula that works on both Google Sheets and Excel (which for older versions at least doesn't have the REGEXREPLACE function), try:
=IF(IFERROR(INFO("release"), 0)=0, IF(TODAY()=TODAY(), SUBSTITUTE(REGEXREPLACE(CELL("address",'SHEETNAME'!A1),"'?(.+?)'?!\$.*","$1"),"''","'", ""), ""), MID(CELL("filename",'SHEETNAME'!A1),FIND("]",CELL("filename",'SHEETNAME'!A1))+1,255))
This uses INFO("release") to determine which platform we are on... Excel returns a number >0 whereas Google Sheets does not implement the INFO function and generates an error which the formula traps into a 0 and uses for numerical comparison. The Google code branch is as above.
For clarity and completeness, this is the Excel-only version (which does correctly return the name of the sheet it resides on):
=MID(CELL("filename",'SHEETNAME'!A1),FIND("]",CELL("filename",'SHEETNAME'!A1))+1,255)
It looks for the "]" filename terminator in the output of CELL("filename" and extracts the sheet name from the remaining part of the string using the MID function. Excel doesn't allow sheet names to contain "]" so this works for all possible sheet names. In the inter-operable version, Excel is happy to be fed a call to the non-existent REGEXREPLACE function because it never gets to execute the Google code branch.
With Markdown-2.5.2, you can use this:
[link](url){:target="_blank"}
The simplest way to delete rows and columns from arrays is the numpy.delete
method.
Suppose I have the following array x
:
x = array([[1,2,3],
[4,5,6],
[7,8,9]])
To delete the first row, do this:
x = numpy.delete(x, (0), axis=0)
To delete the third column, do this:
x = numpy.delete(x,(2), axis=1)
So you could find the indices of the rows which have a 0 in them, put them in a list or a tuple and pass this as the second argument of the function.
There is a another best/effective way to solve this error,
for example, let's take a loop which counts till 10 thousand, here you may get the error Out of memory
, do to solve it you can give the computer time to recover.
So, you can sleep for 400-500ms
before you're loop counts the next number :
new Thread(new Runnable() {
public void run() {
try {
sleep(550); // 550 ms (milli seconds)
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
By doing this, will make you're program slower but you don't get any error till the heap space
is full again, so by waiting some ms
, you can prevent that error.
You can apply this method other than loop.
Hope it helped you, :D
One other place worth checking: Look in the pom.xml for your project, if you are using Maven compiler plugin, at the source/target config and make sure it is the desired version of Java. I found that I had 1.7 in the following; I changed it to 1.8 and then everything compiled correctly in IntelliJ.
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
This is just a sample code, but it may help you get on your way:
Public Sub testIt()
Workbooks("Workbook2").Activate
ActiveWorkbook.Sheets("Sheet2").Activate
ActiveSheet.Range("B3").Select
ActiveCell.EntireRow.Insert
End Sub
I am assuming that you can open the book (called Workbook2
in the example).
I think (but I'm not sure) you can squash all this in a single line of code:
Workbooks("Workbook2").Sheets("Sheet2").Range("B3").EntireRow.Insert
This way you won't need to activate the workbook (or sheet or cell)... Obviously, the book has to be open.
Using Query parameter
<a href="edit.jsp?userId=${user.id}" />
Using Hidden variable .
<form method="post" action="update.jsp">
...
<input type="hidden" name="userId" value="${user.id}">
you can send Using Session object.
session.setAttribute("userId", userid);
These values will now be available from any jsp as long as your session is still active.
int userid = session.getAttribute("userId");
This error occurs when you are sending JSON data to server. Maybe in your string you are trying to add new line character by using /n.
If you add / before /n, it should work, you need to escape new line character.
"Hello there //n start coding"
The result should be as following
Hello there
start coding
And with Prototype:
$('yourDivId').setStyle({top: '100px', left:'80px'});
Tortoise SVN on Windows happens to lose sync quite often with the real file status.
In that case try doing an svn cleanup
.
Another thing, it may also depend where your source files are located, different drive, network drive, etc. There's an option in Tortoise to allow icon overlay or not, on remote drives.
Check this out in: TortoiseSVN / Settings / Icon Overlays / Drive types
This is in response to a number of comments as my reputation isn't high enough to comment directly.
You can specify the profile at runtime as long as the application context has not yet been loaded.
// Previous answers incorrectly used "spring.active.profiles" instead of
// "spring.profiles.active" (as noted in the comments).
// Use AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME to avoid this mistake.
System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, environment);
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/META-INF/spring/applicationContext.xml");
just in case someone comes with this question, this is how I do it, please forget about the repository object, I'm using the Repository Pattern, you can use your object context to retrieve the entities. And also don't pay attention to my entity names, my entity type Action has nothing to do with an MVC Action.
Controller:
ViewBag.ActionStatusId = new SelectList(repository.GetAll<ActionStatus>(), "ActionStatusId", "Name", myAction.ActionStatusId);
Pay attention that the last variable of the SelectList constructor is the selected value (object selectedValue)
Then this is my view to render it:
<div class="editor-label">
@Html.LabelFor(model => model.ActionStatusId, "ActionStatus")
</div>
<div class="editor-field">
@Html.DropDownList("ActionStatusId")
@Html.ValidationMessageFor(model => model.ActionStatusId)
</div>
I think it is pretty simple, I hope this helps! :)
i did a test on a 64bit system with c# console, the exception is type of out of memory, using 2949 threads.
I realize we should be using threading pool, which I do, but this answer is in response to the main question ;)
With a simple JSON object, you don't need jQuery:
for (var i in json) {
for (var j in json[i]) {
console.log(json[i][j]);
}
}
You should be able to access your windows system under the /mnt
directory. For example inside of bash, use this to get to your pictures directory:
cd /mnt/c/Users/<ubuntu.username>/Pictures
Hope this helps!
A DateTime object can be constructed with a specific value of ticks. Once you have determined the ticks value, you can do the following:
DateTime myDate = new DateTime(numberOfTicks);
String test = myDate.ToString("MMMM dd, yyyy");
Imho the best solution is:
fooBar | 0
This is used in asm.js to force integer type.
Slightly easier - use the new-timespan
cmdlet, which creates a time interval from the current time.
ls | where-object {(new-timespan $_.LastWriteTime).days -ge 1}
shows all files not written to today.
The regex you're looking for is ^[A-Za-z.\s_-]+$
^
asserts that the regular expression must match at the beginning of the subject[]
is a character class - any character that matches inside this expression is allowedA-Z
allows a range of uppercase charactersa-z
allows a range of lowercase characters.
matches a period
rather than a range of characters\s
matches whitespace (spaces and tabs)_
matches an underscore-
matches a dash (hyphen); we have it as the last character in the character class so it doesn't get interpreted as being part of a character range. We could also escape it (\-
) instead and put it anywhere in the character class, but that's less clear+
asserts that the preceding expression (in our case, the character class) must match one or more times$
Finally, this asserts that we're now at the end of the subjectWhen you're testing regular expressions, you'll likely find a tool like regexpal helpful. This allows you to see your regular expression match (or fail to match) your sample data in real time as you write it.
Although git pull origin yourbranch
works, it's not really a good idea
You can alternatively do the following:
git fetch origin
git merge origin/yourbranch
The first line fetches all the branches from origin, but doesn't merge with your branches. This simply completes your copy of the repository.
The second line merges your current branch with that of yourbranch
that you fetched from origin
(which is one of your remotes
).
This is assuming origin
points to the repository at address ssh://11.21.3.12:23211/dir1/dir2
If you are looking at this today, and using SQL server 2012 or newer you have the EOMONTH function which makes things easier:
SELECT DATEADD(day, 1, EOMONTH(DATEADD(month, -1, GETDATE()))) as firstdateofmonth
You can change GETDATE() with whatever date variable you want.
I you have the char '9'
, it will store its ASCII code, so to get the int value, you have 2 ways
char x = '9';
int y = Character.getNumericValue(x); //use a existing function
System.out.println(y + " " + (y + 1)); // 9 10
or
char x = '9';
int y = x - '0'; // substract '0' code to get the difference
System.out.println(y + " " + (y + 1)); // 9 10
And it fact, this works also :
char x = 9;
System.out.println(">" + x + "<"); //> < prints a horizontal tab
int y = (int) x;
System.out.println(y + " " + (y + 1)); //9 10
You store the 9
code, which corresponds to a horizontal tab
(you can see when print as String
, bu you can also use it as int
as you see above
Here's how to list local branches that do not have a remote branch in origin with the same name:
git branch | sed 's|* | |' | sort > local
git branch -r | sed 's|origin/||' | sort > remote
comm -23 local remote
by default you would need to use the postgres user:
sudo -u postgres psql postgres
The lscpu(1)
command provided by the util-linux project might also be useful:
$ lscpu
Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Byte Order: Little Endian
CPU(s): 4
On-line CPU(s) list: 0-3
Thread(s) per core: 2
Core(s) per socket: 2
Socket(s): 1
NUMA node(s): 1
Vendor ID: GenuineIntel
CPU family: 6
Model: 58
Model name: Intel(R) Core(TM) i7-3520M CPU @ 2.90GHz
Stepping: 9
CPU MHz: 3406.253
CPU max MHz: 3600.0000
CPU min MHz: 1200.0000
BogoMIPS: 5787.10
Virtualization: VT-x
L1d cache: 32K
L1i cache: 32K
L2 cache: 256K
L3 cache: 4096K
NUMA node0 CPU(s): 0-3
If you are cross-domain, simply setting the src back to the same url will not always trigger a reload, even if the location hash changes.
Ran into this problem while manually constructing Twitter button iframes, which wouldn't refresh when I updated the urls.
Twitter like buttons have the form:
.../tweet_button.html#&_version=2&count=none&etc=...
Since Twitter uses the document fragment for the url, changing the hash/fragment didn't reload the source, and the button targets didn't reflect my new ajax-loaded content.
You can append a query string parameter for force the reload (eg: "?_=" + Math.random()
but that will waste bandwidth, especially in this example where Twitter's approach was specifically trying to enable caching.
To reload something which only changes with hash tags, you need to remove the element, or change the src
, wait for the thread to exit, then assign it back. If the page is still cached, this shouldn't require a network hit, but does trigger the frame reload.
var old = iframe.src;
iframe.src = '';
setTimeout( function () {
iframe.src = old;
}, 0);
Update: Using this approach creates unwanted history items. Instead, remove and recreate the iframe element each time, which keeps this back() button working as expected. Also nice not to have the timer.
You are using the pointer newFile
without allocating space for it.
struct stasher_file *newFile = malloc(sizeof(stasher_file));
Also you should put the struct name at the top. Where you specified stasher_file is to create an instance of that struct.
struct stasher_file {
char name[32];
int size;
int start;
int popularity;
};
As you discovered, in VS11 the compiler will disallow an async Main
method. This was allowed (but never recommended) in VS2010 with the Async CTP.
I have recent blog posts about async/await and asynchronous console programs in particular. Here's some background info from the intro post:
If "await" sees that the awaitable has not completed, then it acts asynchronously. It tells the awaitable to run the remainder of the method when it completes, and then returns from the async method. Await will also capture the current context when it passes the remainder of the method to the awaitable.
Later on, when the awaitable completes, it will execute the remainder of the async method (within the captured context).
Here's why this is a problem in Console programs with an async Main
:
Remember from our intro post that an async method will return to its caller before it is complete. This works perfectly in UI applications (the method just returns to the UI event loop) and ASP.NET applications (the method returns off the thread but keeps the request alive). It doesn't work out so well for Console programs: Main returns to the OS - so your program exits.
One solution is to provide your own context - a "main loop" for your console program that is async-compatible.
If you have a machine with the Async CTP, you can use GeneralThreadAffineContext
from My Documents\Microsoft Visual Studio Async CTP\Samples(C# Testing) Unit Testing\AsyncTestUtilities. Alternatively, you can use AsyncContext
from my Nito.AsyncEx NuGet package.
Here's an example using AsyncContext
; GeneralThreadAffineContext
has almost identical usage:
using Nito.AsyncEx;
class Program
{
static void Main(string[] args)
{
AsyncContext.Run(() => MainAsync(args));
}
static async void MainAsync(string[] args)
{
Bootstrapper bs = new Bootstrapper();
var list = await bs.GetList();
}
}
Alternatively, you can just block the main Console thread until your asynchronous work has completed:
class Program
{
static void Main(string[] args)
{
MainAsync(args).GetAwaiter().GetResult();
}
static async Task MainAsync(string[] args)
{
Bootstrapper bs = new Bootstrapper();
var list = await bs.GetList();
}
}
Note the use of GetAwaiter().GetResult()
; this avoids the AggregateException
wrapping that happens if you use Wait()
or Result
.
Update, 2017-11-30: As of Visual Studio 2017 Update 3 (15.3), the language now supports an async Main
- as long as it returns Task
or Task<T>
. So you can now do this:
class Program
{
static async Task Main(string[] args)
{
Bootstrapper bs = new Bootstrapper();
var list = await bs.GetList();
}
}
The semantics appear to be the same as the GetAwaiter().GetResult()
style of blocking the main thread. However, there's no language spec for C# 7.1 yet, so this is only an assumption.
It is not possible to dynamically change the value of a file field, otherwise you could set it to "c:\yourfile" and steal files very easily.
However there are many solutions to a multi-upload system. I'm guessing that you're wanting to have a multi-select open dialog.
Perhaps have a look at http://www.plupload.com/ - it's a very flexible solution to multiple file uploads, and supports drop zones e.t.c.
Also both the tables need to have same character set.
for e.g.
CREATE TABLE1 (
FIELD1 VARCHAR(100) NOT NULL PRIMARY KEY,
FIELD2 VARCHAR(100) NOT NULL
)ENGINE=INNODB CHARACTER SET utf8 COLLATE utf8_bin;
to
CREATE TABLE2 (
Field3 varchar(64) NOT NULL PRIMARY KEY,
Field4 varchar(64) NOT NULL,
CONSTRAINT FORIGEN KEY (Field3) REFERENCES TABLE1(FIELD1)
) ENGINE=InnoDB;
Will fail because they have different charsets. This is another subtle failure where mysql returns same error.
When compiling for x64, the difference between int and long is somewhere between 0 and 4 bytes, depending on what compiler you use.
GCC uses the LP64 model, which means that ints are 32-bits but longs are 64-bits under 64-bit mode.
MSVC for example uses the LLP64 model, which means both ints and longs are 32-bits even in 64-bit mode.
Use next, it will bypass that condition and rest of the code will work. Below i have provided the Full script and out put
class TestBreak
puts " Enter the nmber"
no= gets.to_i
for i in 1..no
if(i==5)
next
else
puts i
end
end
end
obj=TestBreak.new()
Output: Enter the nmber 10
1 2 3 4 6 7 8 9 10
function hasClass(ele,cls) {
return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
function removeClass(ele,cls) {
if (hasClass(ele,cls)) {
var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
ele.className=ele.className.replace(reg,' ');
}
}
you could use key
value to reset state when need, pass props to state it's not a good practice , because you have uncontrolled and controlled component in one place. Data should be in one place handled
read this
https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key
If you didn't index too much data into the index yet, you can use term facet query on the field that you would like to debug to see the tokens and their frequencies:
curl -XDELETE 'http://localhost:9200/test-idx'
echo
curl -XPUT 'http://localhost:9200/test-idx' -d '
{
"settings": {
"index.number_of_shards" : 1,
"index.number_of_replicas": 0
},
"mappings": {
"doc": {
"properties": {
"message": {"type": "string", "analyzer": "snowball"}
}
}
}
}'
echo
curl -XPUT 'http://localhost:9200/test-idx/doc/1' -d '
{
"message": "How is this going to be indexed?"
}
'
echo
curl -XPOST 'http://localhost:9200/test-idx/_refresh'
echo
curl -XGET 'http://localhost:9200/test-idx/doc/_search?pretty=true&search_type=count' -d '{
"query": {
"match": {
"_id": "1"
}
},
"facets": {
"tokens": {
"terms": {
"field": "message"
}
}
}
}
'
echo
You can use T-SQL:
use master
GO
CREATE LOGIN [NT AUTHORITY\LOCALSERVICE] FROM WINDOWS WITH
DEFAULT_DATABASE=yourDbName
GO
CREATE LOGIN [NT AUTHORITY\NETWORKSERVICE] FROM WINDOWS WITH
DEFAULT_DATABASE=yourDbName
I use this as a part of restore from production server to testing machine:
USE master
GO
ALTER DATABASE yourDbName SET OFFLINE WITH ROLLBACK IMMEDIATE
RESTORE DATABASE yourDbName FROM DISK = 'd:\DropBox\backup\myDB.bak'
ALTER DATABASE yourDbName SET ONLINE
GO
CREATE LOGIN [NT AUTHORITY\LOCALSERVICE] FROM WINDOWS WITH
DEFAULT_DATABASE=yourDbName
GO
CREATE LOGIN [NT AUTHORITY\NETWORKSERVICE] FROM WINDOWS WITH
DEFAULT_DATABASE=yourDbName
GO
You will need to use localized name of services in case of German or French Windows, see How to create a SQL Server login for a service account on a non-English Windows?
Assuming that this is about OAuth 2.0 since it is about JWTs and refresh tokens...:
just like an access token, in principle a refresh token can be anything including all of the options you describe; a JWT could be used when the Authorization Server wants to be stateless or wants to enforce some sort of "proof-of-possession" semantics on to the client presenting it; note that a refresh token differs from an access token in that it is not presented to a Resource Server but only to the Authorization Server that issued it in the first place, so the self-contained validation optimization for JWTs-as-access-tokens does not hold for refresh tokens
that depends on the security/access of the database; if the database can be accessed by other parties/servers/applications/users, then yes (but your mileage may vary with where and how you store the encryption key...)
an Authorization Server may issue both access tokens and refresh tokens at the same time, depending on the grant that is used by the client to obtain them; the spec contains the details and options on each of the standardized grants
You can enforce VM arguments for a JAR
file with the following code:
import java.io.File;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
public class JVMArgumentEnforcer
{
private String argument;
public JVMArgumentEnforcer(String argument)
{
this.argument = argument;
}
public static long getTotalPhysicalMemory()
{
com.sun.management.OperatingSystemMXBean bean =
(com.sun.management.OperatingSystemMXBean)
java.lang.management.ManagementFactory.getOperatingSystemMXBean();
return bean.getTotalPhysicalMemorySize();
}
public static boolean isUsing64BitJavaInstallation()
{
String bitVersion = System.getProperty("sun.arch.data.model");
return bitVersion.equals("64");
}
private boolean hasTargetArgument()
{
RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
List<String> inputArguments = runtimeMXBean.getInputArguments();
return inputArguments.contains(argument);
}
public void forceArgument() throws Exception
{
if (!hasTargetArgument())
{
// This won't work from IDEs
if (JARUtilities.isRunningFromJARFile())
{
// Supply the desired argument
restartApplication();
} else
{
throw new IllegalStateException("Please supply the VM argument with your IDE: " + argument);
}
}
}
private void restartApplication() throws Exception
{
String javaBinary = getJavaBinaryPath();
ArrayList<String> command = new ArrayList<>();
command.add(javaBinary);
command.add("-jar");
command.add(argument);
String currentJARFilePath = JARUtilities.getCurrentJARFilePath();
command.add(currentJARFilePath);
ProcessBuilder processBuilder = new ProcessBuilder(command);
processBuilder.start();
// Kill the current process
System.exit(0);
}
private String getJavaBinaryPath()
{
return System.getProperty("java.home")
+ File.separator + "bin"
+ File.separator + "java";
}
public static class JARUtilities
{
static boolean isRunningFromJARFile() throws URISyntaxException
{
File currentJarFile = getCurrentJARFile();
return currentJarFile.getName().endsWith(".jar");
}
static String getCurrentJARFilePath() throws URISyntaxException
{
File currentJarFile = getCurrentJARFile();
return currentJarFile.getPath();
}
private static File getCurrentJARFile() throws URISyntaxException
{
return new File(JVMArgumentEnforcer.class.getProtectionDomain().getCodeSource().getLocation().toURI());
}
}
}
It is used as follows:
JVMArgumentEnforcer jvmArgumentEnforcer = new JVMArgumentEnforcer("-Duser.language=pt-BR"); // For example
jvmArgumentEnforcer.forceArgument();
The following command will create a copy in a new window. So you can continue see both original file and the new file.
:w {newfilename} | sp #
Yes, it's possible. for example checkout:
<div class="singleMatch" ng-if="match.date | date:'ddMMyyyy' === main.date && match.team1.code === main.team1code && match.team2.code === main.team2code">
//Do something here
</div>
I wrote a plugin which enables me to navigate the file without moving the cursor position. It's based on folding the lines between your position and your target position and then jumping over the fold, or abort it and don't move at all.
It's also easy to fast-switch between the cursor on the first line, the last line and cursor in the middle by just clicking j, k or l when you are in the mode of the plugin.
I guess it would be a good fit here.
Here is the code of ReadDoc/docx.java: This will read a dox/docx file and print its content to the console. you can customize it your way.
import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
public class ReadDocFile
{
public static void main(String[] args)
{
File file = null;
WordExtractor extractor = null;
try
{
file = new File("c:\\New.doc");
FileInputStream fis = new FileInputStream(file.getAbsolutePath());
HWPFDocument document = new HWPFDocument(fis);
extractor = new WordExtractor(document);
String[] fileData = extractor.getParagraphText();
for (int i = 0; i < fileData.length; i++)
{
if (fileData[i] != null)
System.out.println(fileData[i]);
}
}
catch (Exception exep)
{
exep.printStackTrace();
}
}
}
Salvete! I needed, simply, a function I could call to make the code wait for the page to load before it continued. After scouring the web for answers, and fiddling around for several hours, I came up with this to solve for myself, the exact dilemma you present. I know I am late in the game with an answer, but I wish to post this for anyone else who comes along.
usage: just call WaitForPageLoad()
just after a call to navigation:
whatbrowser.Navigate("http://www.google.com")
WaitForPageLoad()
another example
we don't combine the navigate feature with the page load, because sometimes you need to wait for a load without also navigating, for example, you might need to wait for a page to load that was started with an invokemember
event:
whatbrowser.Document.GetElementById("UserName").InnerText = whatusername
whatbrowser.Document.GetElementById("Password").InnerText = whatpassword
whatbrowser.Document.GetElementById("LoginButton").InvokeMember("click")
WaitForPageLoad()
Here is the code: You need both subs plus the accessible variable, pageready
.
First, make sure to fix the variable called whatbrowser
to be your webbrowser control
Now, somewhere in your module or class, place this:
Private Property pageready As Boolean = False
#Region "Page Loading Functions"
Private Sub WaitForPageLoad()
AddHandler whatbrowser.DocumentCompleted, New WebBrowserDocumentCompletedEventHandler(AddressOf PageWaiter)
While Not pageready
Application.DoEvents()
End While
pageready = False
End Sub
Private Sub PageWaiter(ByVal sender As Object, ByVal e As WebBrowserDocumentCompletedEventArgs)
If whatbrowser.ReadyState = WebBrowserReadyState.Complete Then
pageready = True
RemoveHandler whatbrowser.DocumentCompleted, New WebBrowserDocumentCompletedEventHandler(AddressOf PageWaiter)
End If
End Sub
#End Region
Create a model which contains your list and other things you need for the view.
For example:
public class MyModel
{
public List<string> _MyList { get; set; }
}
From the action method put your desired list to the Model, _MyList
property, like:
public ActionResult ArticleList(MyModel model)
{
model._MyList = new List<string>{"item1","item2","item3"};
return PartialView(@"~/Views/Home/MyView.cshtml", model);
}
In your view access the model as follows
@model MyModel
foreach (var item in Model)
{
<div>@item</div>
}
I think it will help for start.
Iam amazed that none of the top answers pointed out that under recent Objective-C versions (after they added literals), you can concatenate just like this:
@"first" @"second"
And it will result in:
@"firstsecond"
You can not use it with NSString objects, only with literals, but it can be useful in some cases.
The problem is from regional Options . The decimal separator in win 7 for european countries is coma . You have to open Control Panel -> Regional and Language Options -> Aditional Settings -> Decimal Separator : click to enter a dot (.) and to List Separator enter a coma (,) . This is !
The tab character is \t
. Notice the use of "
instead of '
.
$chunk = "abc\tdef\tghi";
If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters:
...
\t horizontal tab (HT or 0x09 (9) in ASCII)
Also, let me recommend the fputcsv() function which is for the purpose of writing CSV files.
I recommend you to use CodeCompare tool. It supports native highlighting of XML-data and it can be a good solution for your task.
I know this is an old question and was already answered, but for some reason, I still wanna post this alternative solution. I know it's easy to just find out which built-in function does the "magic" you need, but it doesn't hurt to know you can do it by yourself.
>>> list_1 = ['Ace', 'King']
>>> list_2 = ['Spades', 'Clubs', 'Diamonds']
>>> deck = []
>>> for i in range(max((len(list_1),len(list_2)))):
while True:
try:
card = (list_1[i],list_2[i])
except IndexError:
if len(list_1)>len(list_2):
list_2.append('')
card = (list_1[i],list_2[i])
elif len(list_1)<len(list_2):
list_1.append('')
card = (list_1[i], list_2[i])
continue
deck.append(card)
break
>>>
>>> #and the result should be:
>>> print deck
>>> [('Ace', 'Spades'), ('King', 'Clubs'), ('', 'Diamonds')]
An image of how to in Android Studio 1.5.1.
Within the "Android" project (see the drop-down in the topleft of my image), Right-click on the app...
SELECT
sc.name +'.'+ ta.name TableName, SUM(pa.rows) RowCnt
FROM
sys.tables ta
INNER JOIN sys.partitions pa
ON pa.OBJECT_ID = ta.OBJECT_ID
INNER JOIN sys.schemas sc
ON ta.schema_id = sc.schema_id
WHERE ta.is_ms_shipped = 0 AND pa.index_id IN (1,0)
GROUP BY sc.name,ta.name
ORDER BY SUM(pa.rows) DESC
My solution. It may be slower on performance:
a = pd.concat(df[df[c] == 1] for c in df.columns if c.startswith('foo'))
a.sort_index()
bar.baz foo.aa foo.bars foo.fighters foo.fox foo.manchu nas.foo
0 5.0 1.0 0 0 2 NA NA
1 5.0 2.1 0 1 4 0 0
2 6.0 NaN 0 NaN 1 0 1
5 6.8 6.8 1 0 5 0 0
Extension attributes are added by Exchange. According to this Technet article something like this should work:
Set-Mailbox -Identity "anyUser" -ExtensionCustomAttribute4 @{Remove="myString"}
In my opinion one of the worst chosen word's to describe the process, as it is not related to anything in real-life or similar. In general the word "queue" is very bad as if pronounced, it sounds like the English character "q". See the inefficiency here?
enqueue: to place something into a queue; to add an element to the tail of a queue;
dequeue to take something out of a queue; to remove the first available element from the head of a queue
exit(0) is equivalent to exit(EXIT_SUCCESS).
exit(1) is equivalent to exit(EXIT_FAILURE).
On failure normally any positive value get returned to exit the process, that you can find on shell by using $?.
Value more than 128 that is caused the termination by signal. So if any shell command terminated by signal the return status must be (128+signal number).
For example:
If any shell command is terminated by SIGINT then $? will give 130 ( 128+2) (Here 2 is signal number for SIGINT, check by using kill -l )
i think this may help. Below Macro checks if folder exists, if does not then create the folder and save in both xls and pdf formats in such folder. It happens that the folder is shared with the involved people so everybody is updated.
Sub PDF_laudo_e_Prod_SP_Sem_Ajuste_Preco()
'
' PDF_laudo_e_Prod_SP_Sem_Ajuste_Preco Macro
'
'
Dim MyFolder As String
Dim LaudoName As String
Dim NF1Name As String
Dim OrigFolder As String
MyFolder = ThisWorkbook.path & "\" & Sheets("Laudo").Range("C9")
LaudoName = Sheets("Laudo").Range("K27")
NF1Name = Sheets("PROD SP sem ajuste").Range("Q3")
OrigFolder = ThisWorkbook.path
Sheets("Laudo").Select
Columns("D:P").Select
Selection.EntireColumn.Hidden = True
If Dir(MyFolder, vbDirectory) <> "" Then
Sheets("Laudo").ExportAsFixedFormat Type:=xlTypePDF, filename:=MyFolder & "\" & LaudoName & ".pdf", Quality:=xlQualityMinimum, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
False
Sheets("PROD SP sem ajuste").ExportAsFixedFormat Type:=xlTypePDF, filename:=MyFolder & "\" & NF1Name & ".pdf", Quality:=xlQualityMinimum, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
False
ThisWorkbook.SaveAs filename:=MyFolder & "\" & LaudoName
Application.DisplayAlerts = False
ThisWorkbook.SaveAs filename:=OrigFolder & "\" & "Entregas e Instrucao Barter 2015 - beta"
Application.DisplayAlerts = True
Else
MkDir MyFolder
Sheets("Laudo").ExportAsFixedFormat Type:=xlTypePDF, filename:=MyFolder & "\" & LaudoName & ".pdf", Quality:=xlQualityMinimum, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
False
Sheets("PROD SP sem ajuste").ExportAsFixedFormat Type:=xlTypePDF, filename:=MyFolder & "\" & NF1Name & ".pdf", Quality:=xlQualityMinimum, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
False
ThisWorkbook.SaveAs filename:=MyFolder & "\" & LaudoName
Application.DisplayAlerts = False
ThisWorkbook.SaveAs filename:=OrigFolder & "\" & "Entregas e Instrucao Barter 2015 - beta"
Application.DisplayAlerts = True
End If
Sheets("Laudo").Select
Columns("C:Q").Select
Selection.EntireColumn.Hidden = False
Range("A1").Select
End Sub
For this you have to use HtmlAttributes, but there is a catch: HtmlAttributes and css class .
you can define it like this:
new { Attrubute="Value", AttributeTwo = IntegerValue, @class="className" };
and here is a more realistic example:
new { style="width:50px" };
new { style="width:50px", maxsize = 50 };
new {size=30, @class="required"}
and finally in:
MVC 1
<%= Html.TextBox("test", new { style="width:50px" }) %>
MVC 2
<%= Html.TextBox("test", null, new { style="width:50px" }) %>
MVC 3
@Html.TextBox("test", null, new { style="width:50px" })
In C++, variable length arrays are not legal. G++ allows this as an "extension" (because C allows it), so in G++ (without being -pedantic
about following the C++ standard), you can do:
int n = 10;
double a[n]; // Legal in g++ (with extensions), illegal in proper C++
If you want a "variable length array" (better called a "dynamically sized array" in C++, since proper variable length arrays aren't allowed), you either have to dynamically allocate memory yourself:
int n = 10;
double* a = new double[n]; // Don't forget to delete [] a; when you're done!
Or, better yet, use a standard container:
int n = 10;
std::vector<double> a(n); // Don't forget to #include <vector>
If you still want a proper array, you can use a constant, not a variable, when creating it:
const int n = 10;
double a[n]; // now valid, since n isn't a variable (it's a compile time constant)
Similarly, if you want to get the size from a function in C++11, you can use a constexpr
:
constexpr int n()
{
return 10;
}
double a[n()]; // n() is a compile time constant expression
let tap = UITapGestureRecognizer(target: self, action: Selector("handleFrontTap:"))
frontView.addGestureRecognizer(tap)
// Make sure this is not private
func handleFrontTap(gestureRecognizer: UITapGestureRecognizer) {
print("tap working")
}
The type of the elements of an std::map
(which is also the type of an expression obtained by dereferencing an iterator of that map) whose key is K
and value is V
is std::pair<const K, V>
- the key is const
to prevent you from interfering with the internal sorting of map values.
std::pair<>
has two members named first
and second
(see here), with quite an intuitive meaning. Thus, given an iterator i
to a certain map, the expression:
i->first
Which is equivalent to:
(*i).first
Refers to the first (const
) element of the pair
object pointed to by the iterator - i.e. it refers to a key in the map. Instead, the expression:
i->second
Which is equivalent to:
(*i).second
Refers to the second element of the pair
- i.e. to the corresponding value in the map.
instead of doing it like that, why not just make the flyout position:fixed, top:0; left:0;
once your window has scrolled pass a certain height:
jQuery
$(window).scroll(function(){
if ($(this).scrollTop() > 135) {
$('#task_flyout').addClass('fixed');
} else {
$('#task_flyout').removeClass('fixed');
}
});
css
.fixed {position:fixed; top:0; left:0;}
http://jqapi.com/ Traversing--> Tree Traversal --> Children
values = ['A', 'B', 'C', 'D', 'E']
values[0] # returns 'A'
values[2] # returns 'C'
# etc.
It's simply pointless to create variable variable names. Why?
exec
or globals()
exec/globals()
againUsing a list is much easier:
# 8 strings: `Hello String 0, .. ,Hello String 8`
strings = ["Hello String %d" % x for x in range(9)]
for string in strings: # you can loop over them
print string
print string[6] # or pick any of them
You can use plain javascript Object class to achieve it, Object class has keys function which takes 1 argument as input as follows,
Object.keys(obj).length === 0
You can achieve it in 3 ways, 1) Current controller scope 2) Filter 3) $rootScope
1) First way is current controller scope,
$scope.isObjEmpty = function(obj){ return Object.keys(obj).length === 0; }
Then you can call the function from the view:
ng-show="!isObjEmpty(obj)" if you want to show and hide dom dynamically & ng-if="!isObjEmpty(obj)" if you want to remove or add dom dynamically.
2) The second way is a custom filter. Following code should work for the object & Array,
angular.module('angularApp')
.filter('isEmpty', [function () {
return function (obj) {
if (obj == undefined || obj == null || obj == '')
return true;
if (angular.isObject(obj))
return Object.keys(obj).length != 0;
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
return false;
}
}
return true;
};
}]);
<div ng-hide="items | isEmpty"> Your content's goes here </div>
3) The third way is $rootScope, create a plain javascript function and add it in $rootScope server it will accessible default in all scopes and UI.
function isObjEmpty (obj){ return Object.keys(obj).length === 0; }
$rootScope.isObjEmpty = isObjEmpty ;
* Don't change anything to Listen : keep it as it is..
1) Open httpd.conf of Apache server (backup first) Look for the the following :
<Directory />
Options FollowSymLinks
AllowOverride None
Order deny,allow
Allow from all
#Deny from all
</Directory>
and also this
<Directory "cgi-bin">
AllowOverride None
Options None
Order allow,deny
Allow from all
</Directory>
2) Now From taskbar :
Click on wamp icon > Apache > Apache modules > apache_rewrite (enable this module)
And Ya Also Activate "Put Online" From same taskbar icon
You need to allow port request from windows firewall setting.
(Windows 7)
Go to control panel > windows firewall > advance setting (on left sidebar)
then
Right click on inbound rules -> add new rule -> port -> TCP (Specific port 80 - if your localhost wok on this port) -> Allow the connections -> Give a profile name -> ok
Now Restart all the services of Apache server & you are done..
You may also have answered a setup question wrong and have zero staff members. In which case head to postgres:
obvioustest=# \c [yourdatabasename]
obvioustest=# \x
obvioustest=# select * from auth_user;
-[ RECORD 1 ]+-------------
id | 1
is_superuser | f
is_staff | f
...
To fix, edit directly:
update auth_user set is_staff='true' where id=1;
Doing this with a CSS Grid is pretty easy. The trick is to set the grid's height to 100vw, then assign one of the rows to 75vw, and the remaining one (optional) to 1fr. This gives you, from what I assume is what you're after, a ratio-locked resizing container.
Example here: https://codesandbox.io/s/21r4z95p7j
You can even utilize the bottom gutter space if you so choose, simply by adding another "item".
Edit: StackOverflow's built-in code runner has some side effects. Pop over to the codesandbox link and you'll see the ratio in action.
body {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
background-color: #334;_x000D_
color: #eee;_x000D_
}_x000D_
_x000D_
.main {_x000D_
min-height: 100vh;_x000D_
min-width: 100vw;_x000D_
display: grid;_x000D_
grid-template-columns: 100%;_x000D_
grid-template-rows: 75vw 1fr;_x000D_
}_x000D_
_x000D_
.item {_x000D_
background-color: #558;_x000D_
padding: 2px;_x000D_
margin: 1px;_x000D_
}_x000D_
_x000D_
.item.dead {_x000D_
background-color: transparent;_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
<title>Parcel Sandbox</title>_x000D_
<meta charset="UTF-8" />_x000D_
<link rel="stylesheet" href="src/index.css" />_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div id="app">_x000D_
<div class="main">_x000D_
<div class="item">Item 1</div>_x000D_
<!-- <div class="item dead">Item 2 (dead area)</div> -->_x000D_
</div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
Our version of Oracle is running on Red Hat Enterprise Linux. We experimented with several different types of group permissions to no avail. The /defaultdir directory had a group that was a secondary group for the oracle user. When we updated the /defaultdir directory to have a group of "oinstall" (oracle's primary group), I was able to select from the external tables underneath that directory with no problem.
So, for others that come along and might have this issue, make the directory have oracle's primary group as the group and it might resolve it for you as it did us. We were able to set the permissions to 770 on the directory and files and selecting on the external tables works fine now.
As of September 2016 this addon is the best to disable CORS: https://github.com/fredericlb/Force-CORS/releases
In the options panel you can configure which header to inject and specific website to have it enabled automatically.
if you are looking to change the colour of the cell in case of vlookup error then go for conditional formatting . To do this go the "CONDITIONAL FORMATTING" > "NEW RULE". In this choose the "Select the rule type" = "Format only cells that contains" . After this the window below changes , in which choose "Error" in the first drop-down .After this proceed accordingly.
The logic in the "one-liner" works fine. From personal experience, what has helped me is to assign the statements to variables (in their "True" form) and then use logical operators for the result:
A = year % 4 == 0
B = year % 100 == 0
C = year % 400 == 0
I used '==' in the B statement instead of "!=" and applied 'not' logical operator in the calculation:
leap = A and (not B or C)
This comes in handy with a larger set of conditions, and to simplify the boolean operation where applicable before writing a whole bunch of if statements.
let employee = <Employee>JSON.parse(employeeString);
Remember: Strong typings is compile time only since javascript doesn't support it.
Ok, finally found the solution.
Probably due to lack of experience with ReactJS and web development...
var Task = React.createClass({
render: function() {
var percentage = this.props.children + '%';
....
<div className="ui-progressbar-value ui-widget-header ui-corner-left" style={{width : percentage}}/>
...
I created the percentage variable outside in the render function.
SELECT PersonName, songName, status
FROM table
WHERE name IN ('Holly', 'Ryan')
If you are using parametrized Stored procedure:
INNER JOIN ON t.PersonName = newTable.PersonName
using a table variable which contains passed in namesThis one more version - this will help in generic
Public strSubTag As String
Public iStartCol As Integer
Public iEndCol As Integer
Public strSubTag2 As String
Public iStartCol2 As Integer
Public iEndCol2 As Integer
Sub Create()
Dim strFilePath As String
Dim strFileName As String
'ThisWorkbook.Sheets("Sheet1").Range("C3").Activate
'strTag = ActiveCell.Offset(0, 1).Value
strFilePath = ThisWorkbook.Sheets("Sheet1").Range("B4").Value
strFileName = ThisWorkbook.Sheets("Sheet1").Range("B5").Value
strSubTag = ThisWorkbook.Sheets("Sheet1").Range("F3").Value
iStartCol = ThisWorkbook.Sheets("Sheet1").Range("F4").Value
iEndCol = ThisWorkbook.Sheets("Sheet1").Range("F5").Value
strSubTag2 = ThisWorkbook.Sheets("Sheet1").Range("G3").Value
iStartCol2 = ThisWorkbook.Sheets("Sheet1").Range("G4").Value
iEndCol2 = ThisWorkbook.Sheets("Sheet1").Range("G5").Value
Dim iCaptionRow As Integer
iCaptionRow = ThisWorkbook.Sheets("Sheet1").Range("B3").Value
'strFileName = ThisWorkbook.Sheets("Sheet1").Range("B4").Value
MakeXML iCaptionRow, iCaptionRow + 1, strFilePath, strFileName
End Sub
Sub MakeXML(iCaptionRow As Integer, iDataStartRow As Integer, sOutputFilePath As String, sOutputFileName As String)
Dim Q As String
Dim sOutputFileNamewithPath As String
Q = Chr$(34)
Dim sXML As String
'sXML = sXML & "<rows>"
' ''--determine count of columns
Dim iColCount As Integer
iColCount = 1
While Trim$(Cells(iCaptionRow, iColCount)) > ""
iColCount = iColCount + 1
Wend
Dim iRow As Integer
Dim iCount As Integer
iRow = iDataStartRow
iCount = 1
While Cells(iRow, 1) > ""
'sXML = sXML & "<row id=" & Q & iRow & Q & ">"
sXML = "<?xml version=" & Q & "1.0" & Q & " encoding=" & Q & "UTF-8" & Q & "?>"
For iCOl = 1 To iColCount - 1
If (iStartCol = iCOl) Then
sXML = sXML & "<" & strSubTag & ">"
End If
If (iEndCol = iCOl) Then
sXML = sXML & "</" & strSubTag & ">"
End If
If (iStartCol2 = iCOl) Then
sXML = sXML & "<" & strSubTag2 & ">"
End If
If (iEndCol2 = iCOl) Then
sXML = sXML & "</" & strSubTag2 & ">"
End If
sXML = sXML & "<" & Trim$(Cells(iCaptionRow, iCOl)) & ">"
sXML = sXML & Trim$(Cells(iRow, iCOl))
sXML = sXML & "</" & Trim$(Cells(iCaptionRow, iCOl)) & ">"
Next
'sXML = sXML & "</row>"
Dim nDestFile As Integer, sText As String
''Close any open text files
Close
''Get the number of the next free text file
nDestFile = FreeFile
sOutputFileNamewithPath = sOutputFilePath & sOutputFileName & iCount & ".XML"
''Write the entire file to sText
Open sOutputFileNamewithPath For Output As #nDestFile
Print #nDestFile, sXML
iRow = iRow + 1
sXML = ""
iCount = iCount + 1
Wend
'sXML = sXML & "</rows>"
Close
End Sub
Here is the other way:
using Newtonsoft.Json.Linq;
internal class DymanicTest
{
public static string Json = @"{
""AED"": 3.672825,
""AFN"": 56.982875,
""ALL"": 110.252599,
""AMD"": 408.222002,
""ANG"": 1.78704,
""AOA"": 98.192249,
""ARS"": 8.44469
}";
public static void Run()
{
dynamic dynamicObject = JObject.Parse(Json);
foreach (JProperty variable in dynamicObject)
{
if (variable.Name == "AMD")
{
var value = variable.Value;
}
}
}
}
ORDER BY column OFFSET 0 ROWS
Surprisingly makes it work, what a strange feature.
A bigger example with a CTE as a way to temporarily "store" a long query to re-order it later:
;WITH cte AS (
SELECT .....long select statement here....
)
SELECT * FROM
(
SELECT * FROM
( -- necessary to nest selects for union to work with where & order clauses
SELECT * FROM cte WHERE cte.MainCol= 1 ORDER BY cte.ColX asc OFFSET 0 ROWS
) first
UNION ALL
SELECT * FROM
(
SELECT * FROM cte WHERE cte.MainCol = 0 ORDER BY cte.ColY desc OFFSET 0 ROWS
) last
) as unionized
ORDER BY unionized.MainCol desc -- all rows ordered by this one
OFFSET @pPageSize * @pPageOffset ROWS -- params from stored procedure for pagination, not relevant to example
FETCH FIRST @pPageSize ROWS ONLY -- params from stored procedure for pagination, not relevant to example
So we get all results ordered by MainCol
But the results with MainCol = 1
get ordered by ColX
And the results with MainCol = 0
get ordered by ColY
Not sure why SSMS doesn’t take into account execution order but it just doesn’t. This is not an issue for small databases but what if your database has 200 objects? In that case order of execution does matter because it’s not really easy to go through all of these.
For unordered scripts generated by SSMS you can go following
a) Execute script (some objects will be inserted some wont, there will be some errors)
b) Remove all objects from the script that have been added to database
c) Go back to a) until everything is eventually executed
Alternative option is to use third party tool such as ApexSQL Script or any other tools already mentioned in this thread (SSMS toolpack, Red Gate and others).
All of these will take care of the dependencies for you and save you even more time.
The reason for "permission denied" is because your Android machine has not been correctly rooted. Did you see $
after you started adb shell
? If you correctly rooted your machine, you would have seen #
instead.
If you see the $
, try entering Super User mode by typing su
. If Root is enabled, you will see the #
- without asking for password.
I always use QString::setNum()
.
int i = 10;
double d = 10.75;
QString str;
str.setNum(i);
str.setNum(d);
setNum()
is overloaded in many ways. See QString
class reference.
I tried to test performance using some of the various approaches listed. It's hard to make a rigorous test as many factors affect the result. I prepared two folders, one with 330 jpg files and another one with 330 png files. The average file size was 4Mb in both cases. Then I called getDimension for each file. Each implementation of getDimension method and each image type was tested separately (separate run). Here is the execution times that I got (first number for jpg, second number for png):
1(Apurv) - 101454ms, 84611ms
2(joinJpegs) - 471ms, N/A
3(Andrew Taylor) - 707ms, 68ms
4(Karussell, ImageIcon) - 106655ms, 100898ms
5(user350756) - 2649ms, 68ms
It's obvious that some methods load the whole file in order to get dimensions while others get by just reading some header information from the image. I think these numbers may be useful when application performance is critical.
Thank you everyone for the contribution to this thread - very helpful.
Windows 10 and Android Studio: Ctrl + / (on small num pad), don't use Ctrl + Shift-7!
you need to add it to Foo's prototype:
function Foo(){}
Foo.prototype.bar = function(){}
var x = new Foo()
x.bar()
I have solved this problem by importing the following dependency. you must manually import httpclient
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
public class RoundedCornerLayout extends FrameLayout {
private double mCornerRadius;
public RoundedCornerLayout(Context context) {
this(context, null, 0);
}
public RoundedCornerLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RoundedCornerLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs, defStyle);
}
private void init(Context context, AttributeSet attrs, int defStyle) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
public double getCornerRadius() {
return mCornerRadius;
}
public void setCornerRadius(double cornerRadius) {
mCornerRadius = cornerRadius;
}
@Override
public void draw(Canvas canvas) {
int count = canvas.save();
final Path path = new Path();
path.addRoundRect(new RectF(0, 0, canvas.getWidth(), canvas.getHeight()), (float) mCornerRadius, (float) mCornerRadius, Path.Direction.CW);
canvas.clipPath(path, Region.Op.REPLACE);
canvas.clipPath(path);
super.draw(canvas);
canvas.restoreToCount(count);
}
}
None of those methods work the way the questioner is asking for and which I've often had a need for as well. eg:
$ git remote
fatal: Not a git repository (or any of the parent directories): .git
$ git remote user@bserver
fatal: Not a git repository (or any of the parent directories): .git
$ git remote user@server:/home/user
fatal: Not a git repository (or any of the parent directories): .git
$ git ls-remote
fatal: No remote configured to list refs from.
$ git ls-remote user@server:/home/user
fatal: '/home/user' does not appear to be a git repository
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
The whole point of doing this is that you do not have any information except the remote user and server and want to find out what you have access to.
The majority of the answers assume you are querying from within a git working set. The questioner is assuming you are not.
As a practical example, assume there was a repository foo.git on the server. Someone in their wisdom decides they need to change it to foo2.git. It would really be nice to do a list of a git directory on the server. And yes, I see the problems for git. It would still be nice to have though.
This is how I solved my problem:
List<User> list = GetAllUsers(); //Private Method
if (!sortAscending)
{
list = list
.OrderBy(r => r.GetType().GetProperty(sortBy).GetValue(r,null))
.ToList();
}
else
{
list = list
.OrderByDescending(r => r.GetType().GetProperty(sortBy).GetValue(r,null))
.ToList();
}
Use the analytic function :
select case when
max(field) keep (dense_rank first order by datfin desc nulls first) is null then 1
else 0 end as flag
from MYTABLE;
A call to Class#getResourceAsStream(String)
delegates to the class loader and the resource is searched in the class path. In other words, you current code won't work and you should put abc.txt
in WEB-INF/classes
, or in WEB-INF/lib
if packaged in a jar file.
Or use ServletContext.getResourceAsStream(String)
which allows servlet containers to make a resource available to a servlet from any location, without using a class loader. So use this from a Servlet:
this.getServletContext().getResourceAsStream("/WEB-INF/abc.txt") ;
But is there a way I can call getServletContext from my Web Service?
If you are using JAX-WS, then you can get a WebServiceContext
injected:
@Resource
private WebServiceContext wsContext;
And then get the ServletContext
from it:
ServletContext sContext= wsContext.getMessageContext()
.get(MessageContext.SERVLET_CONTEXT));
PipedInputStream
and PipedOutputStream
should only be used when you have multiple threads, as noted by the Javadoc.
Also, note that input streams and output streams do not wrap any thread interruptions with IOException
s... So, you should consider incorporating an interruption policy to your code:
byte[] buffer = new byte[1024];
int len = in.read(buffer);
while (len != -1) {
out.write(buffer, 0, len);
len = in.read(buffer);
if (Thread.interrupted()) {
throw new InterruptedException();
}
}
This would be an useful addition if you expect to use this API for copying large volumes of data, or data from streams that get stuck for an intolerably long time.
When the session is closed the process receives the SIGHUP signal which it is apparently not catching. You can use the nohup
command when launching the process or the bash built-in command disown -h
after starting the process to prevent this from happening:
> help disown
disown: disown [-h] [-ar] [jobspec ...]
By default, removes each JOBSPEC argument from the table of active jobs.
If the -h option is given, the job is not removed from the table, but is
marked so that SIGHUP is not sent to the job if the shell receives a
SIGHUP. The -a option, when JOBSPEC is not supplied, means to remove all
jobs from the job table; the -r option means to remove only running jobs.
If you install Notepad++ on Linux system by wine (In my case desktop Ubuntu 14.04-LTS_X64) the file "shortcuts.xml" is under :
$/home/[USER-NAME]/.wine/drive_c/users/[USER-NAME]/My Documents/.wine/drive_c/Program Files (x86)/Notepad++/shortcuts.xml
Thanks to Harrison and all that have suggestions for that isssue.
You can use command like,
curl -u user-name -p http://www.example.com/path-to-file/file-name.ext > new-file-name.ext
Then HTTP password will be triggered.
Reference: http://www.asempt.com/article/how-use-curl-http-password-protected-site
If you want to retrieve the key's value if it exists, you can also use
try:
value = a[key]
except KeyError:
# Key is not present
pass
If you want to retrieve a default value when the key does not exist, use
value = a.get(key, default_value)
.
If you want to set the default value at the same time in case the key does not exist, use
value = a.setdefault(key, default_value)
.
You are looking for the CASE statement
http://msdn.microsoft.com/en-us/library/ms181765.aspx
Example copied from MSDN:
USE AdventureWorks;
GO
SELECT ProductNumber, Category =
CASE ProductLine
WHEN 'R' THEN 'Road'
WHEN 'M' THEN 'Mountain'
WHEN 'T' THEN 'Touring'
WHEN 'S' THEN 'Other sale items'
ELSE 'Not for sale'
END,
Name
FROM Production.Product
ORDER BY ProductNumber;
GO
I found this page very useful
public abstract class GenericDAOWithJPA<T, ID extends Serializable> {
private Class<T> persistentClass;
//This you might want to get injected by the container
protected EntityManager entityManager;
@SuppressWarnings("unchecked")
public GenericDAOWithJPA() {
this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
@SuppressWarnings("unchecked")
public List<T> findAll() {
return entityManager.createQuery("Select t from " + persistentClass.getSimpleName() + " t").getResultList();
}
}
Each directive's compile
function is only called once, when Angular bootstraps.
Officially, this is the place to perform (source) template manipulations that do not involve scope or data binding.
Primarily, this is done for optimisation purposes; consider the following markup:
<tr ng-repeat="raw in raws">
<my-raw></my-raw>
</tr>
The <my-raw>
directive will render a particular set of DOM markup. So we can either:
ng-repeat
to duplicate the source template (<my-raw>
), and then modify the markup of each instance template (outside the compile
function).compile
function), and then allow ng-repeat
to duplicate it.If there are 1000 items in the raws
collection, the latter option may be faster than the former one.
NeDB seems to be what you are looking for. From the blurb:
Embedded persistent database for Node.js, written in Javascript, with no dependency (except npm modules of course). You can think of it as a SQLite for Node.js projects, which can be used with a simple require statement. The API is a subset of MongoDB's. You can use it as a persistent or an in-memory only datastore.
Yes, require is a Node.JS function and doesn't work in client side scripting without certain requirements. If you're getting this error while writing electronJS code, try the following:
In your BrowserWindow declaration, add the following webPreferences field:
i.e, instead of plain mainWindow = new BrowserWindow()
, write
mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true
}
});
You can use removeItem()
class of localStorage
to destroy that key on browser close with:
window.onbeforeunload = function{
localStorage.removeItem('your key');
};
This work around will fix the issue found by @Cletus.
function submitForm(form) {
//get the form element's document to create the input control with
//(this way will work across windows in IE8)
var button = form.ownerDocument.createElement('input');
//make sure it can't be seen/disrupts layout (even momentarily)
button.style.display = 'none';
//make it such that it will invoke submit if clicked
button.type = 'submit';
//append it and click it
form.appendChild(button).click();
//if it was prevented, make sure we don't get a build up of buttons
form.removeChild(button);
}
Will work on all modern browsers.
Will work across tabs/spawned child windows (yes, even in IE<9).
And is in vanilla!
Just pass it a DOM reference to a form element and it'll make sure all the attached listeners, the onsubmit, and (if its not prevented by then) finally, submit the form.
Latest revision based on comment from BinaryZebra's comment
and tested here. The addition of command eval
allows for the expression to be kept in the present execution environment while the expressions before are only held for the duration of the eval.
Use $IFS that has no spaces\tabs, just newlines/CR
$ IFS=$'\r\n' GLOBIGNORE='*' command eval 'XYZ=($(cat /etc/passwd))'
$ echo "${XYZ[5]}"
sync:x:5:0:sync:/sbin:/bin/sync
Also note that you may be setting the array just fine but reading it wrong - be sure to use both double-quotes ""
and braces {}
as in the example above
Edit:
Please note the many warnings about my answer in comments about possible glob expansion, specifically gniourf-gniourf's comments about my prior attempts to work around
With all those warnings in mind I'm still leaving this answer here (yes, bash 4 has been out for many years but I recall that some macs only 2/3 years old have pre-4 as default shell)
Other notes:
Can also follow drizzt's suggestion below and replace a forked subshell+cat with
$(</etc/passwd)
The other option I sometimes use is just set IFS into XIFS, then restore after. See also Sorpigal's answer which does not need to bother with this
The answer from ks1322 helped me to identify the issue while using docker-compose exec
:
If you omit the -T
flag, docker-compose exec
add a special character that break output, we see b
instead of 1b
:
$ test=$(/usr/local/bin/docker-compose exec db bash -c "echo 1")
$ echo "${test}b"
b
echo "${test}" | cat -vte
1^M$
With -T
flag, docker-compose exec
works as expected:
$ test=$(/usr/local/bin/docker-compose exec -T db bash -c "echo 1")
$ echo "${test}b"
1b
IDP Initiated SSO
From PingFederate documentation :- https://docs.pingidentity.com/bundle/pf_sm_supportedStandards_pf82/page/task/idpInitiatedSsoPOST.html
In this scenario, a user is logged on to the IdP and attempts to access a resource on a remote SP server. The SAML assertion is transported to the SP via HTTP POST.
Processing Steps:
SP Initiated SSO
From PingFederate documentation:- http://documentation.pingidentity.com/display/PF610/SP-Initiated+SSO--POST-POST
In this scenario a user attempts to access a protected resource directly on an SP Web site without being logged on. The user does not have an account on the SP site, but does have a federated account managed by a third-party IdP. The SP sends an authentication request to the IdP. Both the request and the returned SAML assertion are sent through the user’s browser via HTTP POST.
Processing Steps:
Additional information about the user may be retrieved from the user data store for inclusion in the SAML response. (These attributes are predetermined as part of the federation agreement between the IdP and the SP)
The IdP’s SSO service returns an HTML form to the browser with a SAML response containing the authentication assertion and any additional attributes. The browser automatically posts the HTML form back to the SP. NOTE: SAML specifications require that POST responses be digitally signed.
(Not shown) If the signature and assertion are valid, the SP establishes a session for the user and redirects the browser to the target resource.
WorksheetFunction Transpose()
Instead of copying, pasting via PasteSpecial, and using the Transpose
option you can simply type a formula
=TRANSPOSE(Sheet1!A1:A5)
or if you prefer VBA:
Dim v
v = WorksheetFunction.Transpose(Sheet1.Range("A1:A5"))
Sheet2.Range("A1").Resize(1, UBound(v)) = v
Note: alternatively you could use late-bound Application.Transpose
instead.
MS help reference states that having a current version of Microsoft 365, one can simply input the formula in the top-left-cell of the target range, otherwise the formula must be entered as a legacy array formula via Ctrl+Shift+Enter to confirm it.
Versions Excel vers. 2007+, Mac since 2011, Excel for Microsoft 365
To avoid this warning, do not use:
async: false
in any of your $.ajax()
calls. This is the only feature of XMLHttpRequest
that's deprecated.
The default is async: true
, so if you never use this option at all, your code should be safe if the feature is ever really removed.
However, it probably won't be -- it may be removed from the standards, but I'll bet browsers will continue to support it for many years. So if you really need synchronous AJAX for some reason, you can use async: false
and just ignore the warnings. But there are good reasons why synchronous AJAX is considered poor style, so you should probably try to find a way to avoid it. And the people who wrote Flash applications probably never thought it would go away, either, but it's in the process of being phased out now.
Notice that the Fetch
API that's replacing XMLHttpRequest
does not even offer a synchronous option.
Improvement to @madprops answer - solution as a django management command:
import MySQLdb
from django.conf import settings
from django.core.management.base import BaseCommand
class Command(BaseCommand):
def handle(self, *args, **options):
host = settings.DATABASES['default']['HOST']
password = settings.DATABASES['default']['PASSWORD']
user = settings.DATABASES['default']['USER']
dbname = settings.DATABASES['default']['NAME']
db = MySQLdb.connect(host=host, user=user, passwd=password, db=dbname)
cursor = db.cursor()
cursor.execute("ALTER DATABASE `%s` CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'" % dbname)
sql = "SELECT DISTINCT(table_name) FROM information_schema.columns WHERE table_schema = '%s'" % dbname
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
print(f'Changing table "{row[0]}"...')
sql = "ALTER TABLE `%s` convert to character set DEFAULT COLLATE DEFAULT" % (row[0])
cursor.execute(sql)
db.close()
Hope this helps anybody but me :)
There is no such thing as a truly global variable in Java. Every static variable must belong to some class (like System.out), but when you have decided which class it will go in, you can refer to it from everywhere loaded by the same classloader.
Note that static variables should always be protected when updating to avoid race conditions.
Use the TextInputLayout
provided by the Material Components Library:
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Label">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="match_parent" />
</com.google.android.material.textfield.TextInputLayout>
Assume that you have a tr row with multiple checkboxes in it, and you want to count only if the first checkbox is checked.
You can do that by giving a class to the first checkbox
For example class='mycxk'
and you can count that using the filter, like this
$('.mycxk').filter(':checked').length
Recently had this problem but with unkown number of promises.Solved using jQuery.map().
function methodThatChainsPromises(args) {
//var args = [
// 'myArg1',
// 'myArg2',
// 'myArg3',
//];
var deferred = $q.defer();
var chain = args.map(methodThatTakeArgAndReturnsPromise);
$q.all(chain)
.then(function () {
$log.debug('All promises have been resolved.');
deferred.resolve();
})
.catch(function () {
$log.debug('One or more promises failed.');
deferred.reject();
});
return deferred.promise;
}
Assuming you don't want the user to be in control, you can't. The web doesn't work like that, the best you can hope for is some heuristics.
If it is an option to force your visitor to install some software and use TCPA you may be able to pull something off.
macOS 10.14+ with 5.7.26 installed from Mac OSX DMG installer.
When attempting to use the UPDATE command posted by other users results in the following error:
ERROR 1820 (HY000): You must reset your password using ALTER USER statement before executing this statement.
Copy the password that was presented to you by the Installer open terminal and do the following:
mysql -uroot -p
ALTER USER 'root'@'localhost' IDENTIFIED BY 'YOURPASSWORDHERE';
I've used the below before, and it has worked. It isn't very pretty, but you can alter it to suit your needs.
The following JavaScript function grabs the location.href
& document.title
for the sharer, and you can ultimately change these.
function fbs_click() {
u=location.href;
t=document.title;
window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),
'sharer',
'toolbar=0,status=0,width=626,height=436');
return false;
}
Usage:
<a rel="nofollow" href="http://www.facebook.com/share.php?u=<;url>" onclick="return fbs_click()" target="_blank">
Share on Facebook
</a>
It looks like this is what you could possibly be looking for: Facebook sharer title / desc....
For casting varchar fields/values to number format can be little hack used:
SELECT (`PROD_CODE` * 1) AS `PROD_CODE` FROM PRODUCT`
For Swift 3.0+
extension String {
func SizeOf_String( font: UIFont) -> CGSize {
let fontAttribute = [NSFontAttributeName: font]
let size = self.size(attributes: fontAttribute) // for Single Line
return size;
}
}
Use it like...
let Str = "ABCDEF"
let Font = UIFont.systemFontOfSize(19.0)
let SizeOfString = Str.SizeOfString(font: Font!)
To clear only certain parameters, you can use:
[:param1, :param2, :param3].each { |k| session.delete(k) }
your id attribute is not set. this MAY be due to the fact that the DB field is not set to auto increment? what DB are you using? MySQL? is your field set to AUTO INCREMENT?
I came up with a unique solution because:
sudo -E "$@"
was leaking variables that was causing problems for my commandsudo VAR1="$VAR1" ... VAR42="$VAR42" "$@"
was long and ugly in my case#!/bin/bash
function sudo_exports(){
eval sudo $(for x in $_EXPORTS; do printf '%q=%q ' "$x" "${!x}"; done;) "$@"
}
# create a test script to call as sudo
echo 'echo Forty-Two is $VAR42' > sudo_test.sh
chmod +x sudo_test.sh
export VAR42="The Answer to the Ultimate Question of Life, The Universe, and Everything."
export _EXPORTS="_EXPORTS VAR1 VAR2 VAR3 VAR4 VAR5 VAR6 VAR7 VAR8 VAR9 VAR10 VAR11 VAR12 VAR13 VAR14 VAR15 VAR16 VAR17 VAR18 VAR19 VAR20 VAR21 VAR22 VAR23 VAR24 VAR25 VAR26 VAR27 VAR28 VAR29 VAR30 VAR31 VAR32 VAR33 VAR34 VAR35 VAR36 VAR37 VAR38 VAR39 VAR40 VAR41 VAR42"
# clean function style
sudo_exports ./sudo_test.sh
# or just use the content of the function
eval sudo $(for x in $_EXPORTS; do printf '%q=%q ' "$x" "${!x}"; done;) ./sudo_test.sh
$ ./demo.sh
Forty-Two is The Answer to the Ultimate Question of Life, The Universe, and Everything.
Forty-Two is The Answer to the Ultimate Question of Life, The Universe, and Everything.
This is made possible by a feature of the bash builtin printf
. The %q
produces a shell quoted string. Unlike the parameter expansion in bash 4.4, this works in bash versions < 4.0
Use Random.nextInt(int).
In your case it would look something like this:
a[i][j] = r.nextInt(101);
Truth be told there are many, many resources explaining how to do this already out on the web:
Git: how to reverse-merge a commit?
Git: how to reverse-merge a commit?
Undoing Merges, from Git's blog (retrieved from archive.org's Wayback Machine)
So I guess I'll just summarize some of these:
git revert <merge commit hash>
This creates an extra "revert" commit saying you undid a merge
git reset --hard <commit hash *before* the merge>
This reset history to before you did the merge. If you have commits after the merge you will need to cherry-pick
them on to afterwards.
But honestly this guide here is better than anything I can explain, with diagrams! :)
The solution that was eventually implemented was to use a wrapper for the callback function of the Ajax call and in this wrapper check for the existence of a specific element on the returned HTML chunk. If the element was found then the wrapper executed a redirection. If not, the wrapper forwarded the call to the actual callback function.
For example, our wrapper function was something like:
function cbWrapper(data, funct){
if($("#myForm", data).length > 0)
top.location.href="login.htm";//redirection
else
funct(data);
}
Then, when making the Ajax call we used something like:
$.post("myAjaxHandler",
{
param1: foo,
param2: bar
},
function(data){
cbWrapper(data, myActualCB);
},
"html"
);
This worked for us because all Ajax calls always returned HTML inside a DIV element that we use to replace a piece of the page. Also, we only needed to redirect to the login page.
Here is a YouTube video that explains exactly what you're wanting to do: Save and load a Keras model
There are three different saving methods that Keras makes available. These are described in the video link above (with examples), as well as below.
First, the reason you're receiving the error is because you're calling load_model
incorrectly.
To save and load the weights of the model, you would first use
model.save_weights('my_model_weights.h5')
to save the weights, as you've displayed. To load the weights, you would first need to build your model, and then call load_weights
on the model, as in
model.load_weights('my_model_weights.h5')
Another saving technique is model.save(filepath)
. This save
function saves:
To load this saved model, you would use the following:
from keras.models import load_model
new_model = load_model(filepath)'
Lastly, model.to_json()
, saves only the architecture of the model. To load the architecture, you would use
from keras.models import model_from_json
model = model_from_json(json_string)
Well, on Windows I happily run diff
and many other of the GNU tools. You can do it with cygwin, but I personally prefer GnuWin32 because it is a much lighter installation experience.
So, my answer is that the Windows equivalent of diff
, is none other than diff
itself!
Create epoll
object,
open many client TCP sockets,
adjust their send buffers to be a bit more than request header,
send a request header — it should be immediate, just placing into a buffer,
register socket in epoll
object,
do .poll
on epoll
obect,
read first 3 bytes from each socket from .poll
,
write them to sys.stdout
followed by \n
(don't flush),
close the client socket.
Limit number of sockets opened simultaneously — handle errors when sockets are created. Create a new socket only if another is closed.
Adjust OS limits.
Try forking into a few (not many) processes: this may help to use CPU a bit more effectively.
I stumbled upon this exception, and found out that I forgot to add a Main.
Check out if you have public static void main(String[] args)
correctly.
Good luck!
You can also do:
(from u in table
orderby u.Status descending
select u).Take(1);
If you use Google Chrome browser you can hack with an extension.
You can find a Chrome extension that will modify CORS headers on the fly in your application. Obviously, this is Chrome only, but I like that it works with zero changes anywhere at all.
You can use it for debugging your app on a local machine (if everything works in production).
Notice: If URL becomes broken the extension name is Access-Control-Allow-Origin: *. I recommend you to disable this extension when you not working on your stuff, because, for example, youtube does not work with this extension.
You have to close that application first. There is no way to delete it, if it's used by some application.
UnLock IT is a neat utility that helps you to take control of any file or folder when it is locked by some application or system. For every locked resource, you get a list of locking processes and can unlock it by terminating those processes. EMCO Unlock IT offers Windows Explorer integration that allows unlocking files and folders by one click in the context menu.
There's also Unlocker (not recommended, see Warning below), which is a free tool which helps locate any file locking handles running, and give you the option to turn it off. Then you can go ahead and do anything you want with those files.
Warning: The installer includes a lot of undesirable stuff. You're almost certainly better off with UnLock IT.
You may need to install Hotfix KB980368.
This article describes a update that enables certain Internet Information Services (IIS) 7.0 or IIS 7.5 handlers to handle requests whose URLs do not end with a period. Specifically, these handlers are mapped to "." request paths. Currently, a handler that is mapped to a "." request path handles only requests whose URLs end with a period. For example, the handler handles only requests whose URLs resemble the following URL:
http://www.example.com/ExampleSite/ExampleFile.
After you apply this update, handlers that are mapped to a "*." request path can handle requests whose URLs end with a period and requests whose URLs do not end with a period. For example, the handler can now handle requests that resemble the following URLs:
http://www.example.com/ExampleSite/ExampleFile
http://www.example.com/ExampleSite/ExampleFile.
After this patch is applied, ASP.NET 4 applications can handle requests for extensionless URLs. Therefore, managed HttpModules that run prior to handler execution will run. In some cases, the HttpModules can return errors for extensionless URLs. For example, an HttpModule that was written to expect only .aspx requests may now return errors when it tries to access the HttpContext.Session property.
You can use this Function if you have some variable in the SSIS.
Package pkg;
Microsoft.SqlServer.Dts.Runtime.Application app;
DTSExecResult pkgResults;
Variables vars;
app = new Microsoft.SqlServer.Dts.Runtime.Application();
pkg = app.LoadPackage(" Location of your SSIS package", null);
vars = pkg.Variables;
// your variables
vars["somevariable1"].Value = "yourvariable1";
vars["somevariable2"].Value = "yourvariable2";
pkgResults = pkg.Execute(null, vars, null, null, null);
if (pkgResults == DTSExecResult.Success)
{
Console.WriteLine("Package ran successfully");
}
else
{
Console.WriteLine("Package failed");
}
On windows, you can use PuttyGen to load the private key file, remove the passphrase and then overwrite the existing private key file.
For the device, you also need to add the dynamic framework to the Embedded binaries
section in the General
tab of the project.
I'll try and answer several different things, however my contribution may not cover all of your questions. Maybe several of us can take different chunks out of this. However, this info should be helpful for you. Here we go..
Opening A Seperate File:
ChDir "[Path here]" 'get into the right folder here
Workbooks.Open Filename:= "[Path here]" 'include the filename in this path
'copy data into current workbook or whatever you want here
ActiveWindow.Close 'closes out the file
Opening A File With Specified Date If It Exists:
I'm not sure how to search your directory to see if a file exists, but in my case I wouldn't bother to search for it, I'd just try to open it and put in some error checking so that if it doesn't exist then display this message or do xyz.
Some common error checking statements:
On Error Resume Next 'if error occurs continues on to the next line (ignores it)
ChDir "[Path here]"
Workbooks.Open Filename:= "[Path here]" 'try to open file here
Or (better option):
if one doesn't exist then bring up either a message box or dialogue box to say "the file does not exist, would you like to create a new one?
you would most likely want to use the GoTo ErrorHandler
shown below to achieve this
On Error GoTo ErrorHandler:
ChDir "[Path here]"
Workbooks.Open Filename:= "[Path here]" 'try to open file here
ErrorHandler:
'Display error message or any code you want to run on error here
Much more info on Error handling here: http://www.cpearson.com/excel/errorhandling.htm
Also if you want to learn more or need to know more generally in VBA I would recommend Siddharth Rout's site, he has lots of tutorials and example code here: http://www.siddharthrout.com/vb-dot-net-and-excel/
Hope this helps!
Example on how to ensure error code doesn't run EVERYtime:
if you debug through the code without the Exit Sub
BEFORE the error handler you'll soon realize the error handler will be run everytime regarldess of if there is an error or not. The link below the code example shows a previous answer to this question.
Sub Macro
On Error GoTo ErrorHandler:
ChDir "[Path here]"
Workbooks.Open Filename:= "[Path here]" 'try to open file here
Exit Sub 'Code will exit BEFORE ErrorHandler if everything goes smoothly
'Otherwise, on error, ErrorHandler will be run
ErrorHandler:
'Display error message or any code you want to run on error here
End Sub
Also, look at this other question in you need more reference to how this works: goto block not working VBA
In Oracle the solution would be:
UPDATE
MasterTbl
SET
(TotalX,TotalY,TotalZ) =
(SELECT SUM(X),SUM(Y),SUM(Z)
from DetailTbl where DetailTbl.MasterID = MasterTbl.ID)
Don't know if your system allows the same.
You can still use it (mysqli is just another way of communicating with the server, the SQL language itself is expanded, not changed). Prepared statements are safer, though - since you don't need to go through the trouble of properly escaping your values each time. You can leave them as they were, if you want to but the risk of sql piggybacking is reduced if you switch.
I found it easier to move the files into a separate Class Library project and then reference that project in the web project and apply the namespace in the using
section of the file.
For some reason the other solutions were not working for me, but this work around did.
I had run python setup.py install
once in my PyCharm, it installs all the packages into my conda base environment. Later when I want to remove all these packages, pip uninstall
does not work. I had to delete them from /anaconda3/lib/python3.7/site-packages manually :(
So I don't see the reason why they use setup.py instead of writing requirements.txt file. The requirement file can be used to install packages in virtual environment and won't mess with system python packages.
Gwerder's solution wont work because hash = hmac.read();
happens before the stream is done being finalized. Thus AngraX's issues. Also the hmac.write
statement is un-necessary in this example.
Instead do this:
var crypto = require('crypto');
var hmac;
var algorithm = 'sha1';
var key = 'abcdeg';
var text = 'I love cupcakes';
var hash;
hmac = crypto.createHmac(algorithm, key);
// readout format:
hmac.setEncoding('hex');
//or also commonly: hmac.setEncoding('base64');
// callback is attached as listener to stream's finish event:
hmac.end(text, function () {
hash = hmac.read();
//...do something with the hash...
});
More formally, if you wish, the line
hmac.end(text, function () {
could be written
hmac.end(text, 'utf8', function () {
because in this example text is a utf string
Calling exactly super()
is always redundant. It's explicitly doing what would be implicitly done otherwise. That's because if you omit a call to the super constructor, the no-argument super constructor will be invoked automatically anyway. Not to say that it's bad style; some people like being explicit.
However, where it becomes useful is when the super constructor takes arguments that you want to pass in from the subclass.
public class Animal {
private final String noise;
protected Animal(String noise) {
this.noise = noise;
}
public void makeNoise() {
System.out.println(noise);
}
}
public class Pig extends Animal {
public Pig() {
super("Oink");
}
}
In my case, simply giving the user permissions on the database fixed it.
So Right click on the database -> Click Properties -> [left hand menu] Click Permissions -> and scroll down to Backup database -> Tick "Grant"
You just need to write the first query as a subquery (derived table), inside parentheses, pick an alias for it (t
below) and alias the columns as well.
The DISTINCT
can also be safely removed as the internal GROUP BY
makes it redundant:
SELECT DATE(`date`) AS `date` , COUNT(`player_name`) AS `player_count`
FROM (
SELECT MIN(`date`) AS `date`, `player_name`
FROM `player_playtime`
GROUP BY `player_name`
) AS t
GROUP BY DATE( `date`) DESC LIMIT 60 ;
Since the COUNT
is now obvious that is only counting rows of the derived table, you can replace it with COUNT(*)
and further simplify the query:
SELECT t.date , COUNT(*) AS player_count
FROM (
SELECT DATE(MIN(`date`)) AS date
FROM player_playtime
GROUP BY player_name
) AS t
GROUP BY t.date DESC LIMIT 60 ;
If you want to get database encodings:
psql -U postgres -h somehost --list
You'll see something like:
List of databases
Name | Owner | Encoding
------------------------+----------+----------
db1 | postgres | UTF8
You can do this:
$('.searchbychar').click(function () {
var divID = '#' + this.id;
$('html, body').animate({
scrollTop: $(divID).offset().top
}, 2000);
});
F.Y.I.
.
(dot) like in your first line of code.$( 'searchbychar' ).click(function() {
$('.searchbychar').attr('id')
will return a string ID not a jQuery object. Hence, you can not apply .offset()
method to it.The difference between test, [ and [[ is explained in great details in the BashFAQ.
To cut a long story short: test implements the old, portable syntax of the command. In almost all shells (the oldest Bourne shells are the exception), [ is a synonym for test (but requires a final argument of ]). Although all modern shells have built-in implementations of [, there usually still is an external executable of that name, e.g. /bin/[.
[[ is a new improved version of it, which is a keyword, not a program. This has beneficial effects on the ease of use, as shown below. [[ is understood by KornShell and BASH (e.g. 2.03), but not by the older POSIX or BourneShell.
And the conclusion:
When should the new test command [[ be used, and when the old one [? If portability to the BourneShell is a concern, the old syntax should be used. If on the other hand the script requires BASH or KornShell, the new syntax is much more flexible.
Simpler more performant version, with simple caching.
var TITLE_CASE_LOWER_MAP = {_x000D_
'a': 1, 'an': 1, 'and': 1, 'as': 1, 'at': 1, 'but': 1, 'by': 1, 'en':1, 'with': 1,_x000D_
'for': 1, 'if': 1, 'in': 1, 'of': 1, 'on': 1, 'the': 1, 'to': 1, 'via': 1_x000D_
};_x000D_
_x000D_
// LEAK/CACHE TODO: evaluate using LRU._x000D_
var TITLE_CASE_CACHE = new Object();_x000D_
_x000D_
toTitleCase: function (title) {_x000D_
if (!title) return null;_x000D_
_x000D_
var result = TITLE_CASE_CACHE[title];_x000D_
if (result) {_x000D_
return result;_x000D_
}_x000D_
_x000D_
result = "";_x000D_
var split = title.toLowerCase().split(" ");_x000D_
for (var i=0; i < split.length; i++) {_x000D_
_x000D_
if (i > 0) {_x000D_
result += " ";_x000D_
}_x000D_
_x000D_
var word = split[i];_x000D_
if (i == 0 || TITLE_CASE_LOWER_MAP[word] != 1) {_x000D_
word = word.substr(0,1).toUpperCase() + word.substr(1);_x000D_
}_x000D_
_x000D_
result += word;_x000D_
}_x000D_
_x000D_
TITLE_CASE_CACHE[title] = result;_x000D_
_x000D_
return result;_x000D_
},
_x000D_
Cut can take several ranges in -f
:
Columns up to 4 and from 7 onwards:
cut -f -4,7-
or for fields 1,2,5,6 and from 10 onwards:
cut -f 1,2,5,6,10-
etc
Which means this response is sent when the web server, after performing server-driven content negotiation, doesn't find any content that conforms to the criteria given by the user agent.
First, here's some sample data:
set.seed(1)
dat <- data.frame(one = rnorm(15),
two = sample(LETTERS, 15),
three = rnorm(15),
four = runif(15))
dat <- data.frame(lapply(dat, function(x) { x[sample(15, 5)] <- NA; x }))
head(dat)
# one two three four
# 1 NA M 0.80418951 0.8921983
# 2 0.1836433 O -0.05710677 NA
# 3 -0.8356286 L 0.50360797 0.3899895
# 4 NA E NA NA
# 5 0.3295078 S NA 0.9606180
# 6 -0.8204684 <NA> -1.28459935 0.4346595
Here's our replacement:
dat[["four"]][is.na(dat[["four"]])] <- 0
head(dat)
# one two three four
# 1 NA M 0.80418951 0.8921983
# 2 0.1836433 O -0.05710677 0.0000000
# 3 -0.8356286 L 0.50360797 0.3899895
# 4 NA E NA 0.0000000
# 5 0.3295078 S NA 0.9606180
# 6 -0.8204684 <NA> -1.28459935 0.4346595
Alternatively, you can, of course, write dat$four[is.na(dat$four)] <- 0
You can use imagecrop
function in (PHP 5 >= 5.5.0, PHP 7)
Example:
<?php
$im = imagecreatefrompng('example.png');
$size = min(imagesx($im), imagesy($im));
$im2 = imagecrop($im, ['x' => 0, 'y' => 0, 'width' => $size, 'height' => $size]);
if ($im2 !== FALSE) {
imagepng($im2, 'example-cropped.png');
imagedestroy($im2);
}
imagedestroy($im);
?>
If you have a list of words you can do a method like this:
public bool ContainWords(List<string> wordList, string text)
{
foreach(string currentWord in wordList)
if(!text.Contains(currentWord))
return false;
return true;
}
install -d -m 0777 /your/dir
should give you what you want. Be aware that every user has the right to write add and delete files in that directory.
I was able to fix this!
Had the same problems as stated above, made sure nothing was using port 80 and still not working and getting the message that Apache and Mysql were detected with the wrong path.
I did install XAMPP once before, uninstalled and reinstalled. I even manually uninstalled but still had issues.
The fix. Make sure you backup your system first!
Start Services via Control Panel>Admin Tools (also with Ctrl+R and services.msc
)
Look for Apache and MySQL services. Look at the patch indicated in the description (right click on service then click on properties). Chances are that you have Apache listed twice, one from your correct install and one from a previous install. Even if you only see one, look at the path, chances are it's from a previous install and causing your install not to work. In either case, you need to delete those incorrect services.
a. Got to command prompt (run as administrator): Start > all programs > Accessories > right click on Command Prompt > Select 'run as administrator'
b. on command prompt type sc delete service
, where service is the service you're wanting to delete, such as apache2.1 (or sc delete Apache2.4
). It should be exactly as it appears in your services. If the service has spaces such as Apache 2.1 then enter it in quotes, i.e. sc delete "Apache 2.1"
c. press enter. Now refresh or close/open your services window and you'll see it`s gone.
DO THIS for all services that XAMPP finds as running with an incorrect path.
Once you do this, go ahead and restart the XAMPP control panel (as administrator) and voila! all works. No conflicts
I was having the same question. Here is a working solution which is similar to eglasius's. I am using postgresql.
UPDATE QuestionTrackings
SET QuestionID = a.QuestionID
FROM QuestionTrackings q, QuestionAnswers a
WHERE q.QuestionID IS NULL
It complains if q was used in place of table name in line 1, and nothing should precede QuestionID in line 2.
If your static variables need to be set at runtime then a static {...}
block is very helpful.
For example, if you need to set the static member to a value which is stored in a config file or database.
Also useful when you want to add values to a static Map
member as you can't add these values in the initial member declaration.
ASP.Net Web API has Authorization Server build-in already. You can see it inside Startup.cs when you create a new ASP.Net Web Application with Web API template.
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
// In production mode set AllowInsecureHttp = false
AllowInsecureHttp = true
};
All you have to do is to post URL encoded username and password inside query string.
/Token/userName=johndoe%40example.com&password=1234&grant_type=password
If you want to know more detail, you can watch User Registration and Login - Angular Front to Back with Web API by Deborah Kurata.
For your code to compile you need to cast the result to an int.
int abc = (int) (Math.random() * 100);
However, if you instead use the java.util.Random class it has built in method for you
Random random = new Random();
int abc = random.nextInt(100);
yes, but why !!??
Select CustomerID,
Min(Case DBColumnName When 'FirstName' Then Data End) FirstName,
Min(Case DBColumnName When 'MiddleName' Then Data End) MiddleName,
Min(Case DBColumnName When 'LastName' Then Data End) LastName,
Min(Case DBColumnName When 'Date' Then Data End) Date
From table
Group By CustomerId
If you'd like to redirect to another domain without the user having to do anything you can use a link with the property:
target="_parent"
as said previously, and then use:
document.getElementById('link').click();
to have it automatically redirect.
Example:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<a id="link" target="_parent" href="outsideDomain.html"></a>
<script type="text/javascript">
document.getElementById('link').click();
</script>
</body>
</html>
Note: The javascript click() command must come after you declare the link.
They remain in the fields because you are explicitly telling PHP to fill the form with the submitted data.
<input name="firstname" type="text" placeholder="First Name" required="required"
value="<?php echo $_POST['firstname'];?>">
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ HERE
Just remove this, or if you want a condition to not do so make a if
statement to that echo
or just cleanup the $_POST
fields.
$_POST = array(); // lets pretend nothing was posted
Or, if successful, redirect the user to another page:
header("Location: success.html");
exit; // Location header is set, pointless to send HTML, stop the script
Which by the way is the prefered method. If you keep the user in a page that was reached through a POST
method, if he refreshes the page the form will be submitted again.
std::vector
is a template class that encapsulate a dynamic array1, stored in the heap, that grows and shrinks automatically if elements are added or removed. It provides all the hooks (begin()
, end()
, iterators, etc) that make it work fine with the rest of the STL. It also has several useful methods that let you perform operations that on a normal array would be cumbersome, like e.g. inserting elements in the middle of a vector (it handles all the work of moving the following elements behind the scenes).
Since it stores the elements in memory allocated on the heap, it has some overhead in respect to static arrays.
std::array
is a template class that encapsulate a statically-sized array, stored inside the object itself, which means that, if you instantiate the class on the stack, the array itself will be on the stack. Its size has to be known at compile time (it's passed as a template parameter), and it cannot grow or shrink.
It's more limited than std::vector
, but it's often more efficient, especially for small sizes, because in practice it's mostly a lightweight wrapper around a C-style array. However, it's more secure, since the implicit conversion to pointer is disabled, and it provides much of the STL-related functionality of std::vector
and of the other containers, so you can use it easily with STL algorithms & co. Anyhow, for the very limitation of fixed size it's much less flexible than std::vector
.
For an introduction to std::array
, have a look at this article; for a quick introduction to std::vector
and to the the operations that are possible on it, you may want to look at its documentation.
It's simple
pd.factorize(df.purchase)[0]
Example:
labels, uniques = pd.factorize(['b', 'b', 'a', 'c', 'b'])`
labels
# array([0, 0, 1, 2, 0])
uniques
# array(['b', 'a', 'c'], dtype=object)
The best methods are already given but why not look at a couple of other methods for fun? Warning: these are more expensive methods but do serve in other circumstances.
The expensive regex method and the css attribute selector with starts with ^ operator
Option Explicit
Public Sub test()
Debug.Print StartWithSubString("ab", "abc,d")
End Sub
Regex:
Public Function StartWithSubString(ByVal substring As String, ByVal testString As String) As Boolean
'required reference Microsoft VBScript Regular Expressions
Dim re As VBScript_RegExp_55.RegExp
Set re = New VBScript_RegExp_55.RegExp
re.Pattern = "^" & substring
StartWithSubString = re.test(testString)
End Function
Css attribute selector with starts with operator
Public Function StartWithSubString(ByVal substring As String, ByVal testString As String) As Boolean
'required reference Microsoft HTML Object Library
Dim html As MSHTML.HTMLDocument
Set html = New MSHTML.HTMLDocument
html.body.innerHTML = "<div test=""" & testString & """></div>"
StartWithSubString = html.querySelectorAll("[test^=" & substring & "]").Length > 0
End Function
GO to SSMS and try this
Menu >> Tools >> Options >> Designers >> Uncheck “Prevent Saving changes that require table re-creation”.
Here is a very good explanation on this: http://blog.sqlauthority.com/2009/05/18/sql-server-fix-management-studio-error-saving-changes-in-not-permitted-the-changes-you-have-made-require-the-following-tables-to-be-dropped-and-re-created-you-have-either-made-changes-to-a-tab/
An issue that DO arise in practical Android code is that comparing them with CharSequence.equals is valid but does not necessarily work as intended.
EditText t = (EditText )getView(R.id.myEditText); // Contains "OK"
Boolean isFalse = t.getText().equals("OK"); // will always return false.
Comparison should be made by
("OK").contentEquals(t.GetText());
You have to learn Smarty syntax. That's a template system.
When testing for directories remember that every directory contains two special files.
One is called '.' and the other '..'
. is the directory's own name while .. is the name of it's parent directory.
To avoid trailing backslash problems just test to see if the directory knows it's own name.
eg:
if not exist %temp%\buffer\. mkdir %temp%\buffer
var ids = [];
$(document).ready(function($) {
$(".color_cell").bind('click', function() {
alert('Test');
ids.push(this.id);
});
});
I cannot comment on @Michael Blackburn, but I guess you got the downvote because the GroupBy is not necessary in this case.
Use it like:
var lookupOfCustomObjects = listOfCustomObjects.ToLookup(o=>o.PropertyName);
var listWithAllCustomObjectsWithPropertyName = lookupOfCustomObjects[propertyName]
Additionally, I've seen this perform way better than when using GroupBy().ToDictionary().
You have to use the FormulaEvaluator, as shown here. This will return a value that is either the value present in the cell or the result of the formula if the cell contains such a formula :
FileInputStream fis = new FileInputStream("/somepath/test.xls");
Workbook wb = new HSSFWorkbook(fis); //or new XSSFWorkbook("/somepath/test.xls")
Sheet sheet = wb.getSheetAt(0);
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
// suppose your formula is in B3
CellReference cellReference = new CellReference("B3");
Row row = sheet.getRow(cellReference.getRow());
Cell cell = row.getCell(cellReference.getCol());
if (cell!=null) {
switch (evaluator.evaluateFormulaCell(cell)) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.println(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.println(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
System.out.println(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BLANK:
break;
case Cell.CELL_TYPE_ERROR:
System.out.println(cell.getErrorCellValue());
break;
// CELL_TYPE_FORMULA will never occur
case Cell.CELL_TYPE_FORMULA:
break;
}
}
if you need the exact contant (ie the formla if the cell contains a formula), then this is shown here.
Edit : Added a few example to help you.
first you get the cell (just an example)
Row row = sheet.getRow(rowIndex+2);
Cell cell = row.getCell(1);
If you just want to set the value into the cell using the formula (without knowing the result) :
String formula ="ABS((1-E"+(rowIndex + 2)+"/D"+(rowIndex + 2)+")*100)";
cell.setCellFormula(formula);
cell.setCellStyle(this.valueRightAlignStyleLightBlueBackground);
if you want to change the message if there is an error in the cell, you have to change the formula to do so, something like
IF(ISERR(ABS((1-E3/D3)*100));"N/A"; ABS((1-E3/D3)*100))
(this formula check if the evaluation return an error and then display the string "N/A", or the evaluation if this is not an error).
if you want to get the value corresponding to the formula, then you have to use the evaluator.
Hope this help,
Guillaume
You can use it by easy way, through store
method in your controller
like the below
{{Form::open(['route' => 'user.store', 'files' => true])}}
{{Form::label('user_photo', 'User Photo',['class' => 'control-label'])}}
{{Form::file('user_photo')}}
{{Form::submit('Save', ['class' => 'btn btn-success'])}}
{{Form::close()}}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
public function store(Request $request)
{
// get current time and append the upload file extension to it,
// then put that name to $photoName variable.
$photoName = time().'.'.$request->user_photo->getClientOriginalExtension();
/*
talk the select file and move it public directory and make avatars
folder if doesn't exsit then give it that unique name.
*/
$request->user_photo->move(public_path('avatars'), $photoName);
}
}
That’s it. Now you can save the $photoName
to the database as a user_photo
field value. You can use asset(‘avatars’)
function in your view and access the photos.
Use Bootstrap to have a hustle free with your images as shown. Use class img-responsive and you are done:
<img src="cinqueterre.jpg" class="img-responsive" alt="Cinque Terre" width="304" height="236">