To complete previous answers, you can also use Wait-Job
to wait for all jobs to complete:
For ($i=1; $i -le 3; $i++) {
$ScriptBlock = {
Param (
[string] [Parameter(Mandatory=$true)] $increment
)
Write-Host $increment
}
Start-Job $ScriptBlock -ArgumentList $i
}
Get-Job | Wait-Job | Receive-Job
I learned all my Regex from this website: http://www.zytrax.com/tech/web/regex.htm. Google on 'Regex tutorials' and you'll find loads of helful articles.
String regex = "[a-zA-Z]*\.jpg";
System.out.println ("somthing.jpg".matches (regex));
returns true.
function isEqual(obj1, obj2){
type1 = typeof(obj1);
type2 = typeof(obj2);
if(type1===type2){
switch (type1){
case "object": return JSON.stringify(obj1)===JSON.stringify(obj2);
case "function": return eval(obj1).toString()===eval(obj2).toString();
default: return obj1==obj2;
}
}
return false;
}//have not tried but should work.
The answer of Shyam was right. I already faced with this issue before. It's not a problem, it's a SPRING feature. "Transaction rolled back because it has been marked as rollback-only" is acceptable.
Conclusion
Let's me explain more detail:
Question: How many Transaction we have? Answer: Only one
Because you config the PROPAGATION is PROPAGATION_REQUIRED so that the @Transaction persist() is using the same transaction with the caller-processNextRegistrationMessage(). Actually, when we get an exception, the Spring will set rollBackOnly for the TransactionManager so the Spring will rollback just only one Transaction.
Question: But we have a try-catch outside (), why does it happen this exception? Answer Because of unique Transaction
Go to the catch outside
Spring will set the rollBackOnly to true -> it determine we must
rollback the caller (processNextRegistrationMessage) also.
The persist() will rollback itself first.
Question: Why we change PROPAGATION to REQUIRES_NEW, it works?
Answer: Because now the processNextRegistrationMessage() and persist() are in the different transaction so that they only rollback their transaction.
Thanks
I can think of at least 2 different ways:
using Task Manager (Ctrl-Shift-Esc), select the process tab, look for a process name cscript.exe or wscript.exe and use End Process.
From the command line you could use taskkill /fi "imagename eq cscript.exe" (change to wscript.exe as needed)
Another way is using scripting and WMI. Here are some hints: look for the Win32_Process class and the Terminate method.
Step-1 Need to find user details by using below query
SQL> select username, account_status from dba_users where username='BOB';
USERNAME ACCOUNT_STATUS
------------------------------ --------------------------------
BOB EXPIRED
Step-2 Get users password by using below query.
SQL>SELECT 'ALTER USER '|| name ||' IDENTIFIED BY VALUES '''|| spare4 ||';'|| password ||''';' FROM sys.user$ WHERE name='BOB';
ALTER USER BOB IDENTIFIED BY VALUES 'S:9BDD17811E21EFEDFB1403AAB1DD86AB481E;T:602E36430C0D8DF7E1E453;2F9933095143F432';
Step -3 Run Above alter query
SQL> ALTER USER BOB IDENTIFIED BY VALUES 'S:9BDD17811E21EFEDFB1403AAB1DD86AB481E;T:602E36430C0D8DF7E1E453;2F9933095143F432';
User altered.
Step-4 :Check users account status
SQL> select username, account_status from dba_users where username='BOB';
USERNAME ACCOUNT_STATUS
------------------------------ --------------------------------
BOB OPEN
SELECTs do not normally do any locking that you care about on InnoDB tables. The default transaction isolation level means that selects don't lock stuff.
Of course contention still happens.
The solution was simply to comment the lines "work_mem=256MB" and "maintenance_work_mem=$3GB" in the file postgresql.conf and try to start the postgresql service. (start -> run -> services.msc) and look for the postgresql-[version] service then right click and start.
I have PHP 5.3.1 and Apache
When I add the extension=php_intl.dll
to php.ini and restart apache, it comes an alert that says "the requested operation has failed"
And this error on Event Monitor:
Faulting application name: httpd.exe, version: 2.2.14.0, time stamp: 0x4ac181d6
Faulting module name: php5ts.dll, version: 5.3.1.0, time stamp: 0x4b051b35
Exception code: 0xc0000005
The problem was some DLLs like icudt36.dll were missing (noticed with sysinternals ProcMon), I've downloaded php 5.3.1 zip version and extract all DLL's to PHP folder. That solved the problem.
As others have suggested, the best way to do this is to use a join instead of variable assignment. Re-writing your query to use a join (and using the explicit join syntax instead of the implicit join, which was also suggested--and is the best practice), you would get something like this:
select
OrderDetails.Sku,
OrderDetails.mf_item_number,
OrderDetails.Qty,
OrderDetails.Price,
Supplier.SupplierId,
Supplier.SupplierName,
Supplier.DropShipFees,
Supplier_Item.Price as cost
from
OrderDetails
join Supplier on OrderDetails.Mfr_ID = Supplier.SupplierId
join Group_Master on Group_Master.Sku = OrderDetails.Sku
join Supplier_Item on
Supplier_Item.SKU=OrderDetails.Sku and Supplier_Item.SupplierId=Supplier.SupplierID
where
invoiceid='339740'
You can use the following code for changing the String value into the time equivalent:
String str = "08:03:10 pm";
DateFormat formatter = new SimpleDateFormat("hh:mm:ss a");
Date date = (Date)formatter.parse(str);
Hope this helps you.
I like having a list of sorted indices. That way, I can sort any list in the same order as the source list. Once you have a list of sorted indices, a simple list comprehension will do the trick:
X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1]
sorted_y_idx_list = sorted(range(len(Y)),key=lambda x:Y[x])
Xs = [X[i] for i in sorted_y_idx_list ]
print( "Xs:", Xs )
# prints: Xs: ["a", "d", "h", "b", "c", "e", "i", "f", "g"]
Note that the sorted index list can also be gotten using numpy.argsort()
.
If you don't want a timeout happening for some purpose:
<session-config>
<session-timeout>0</session-timeout>
</session-config>
Should result in no timeout at all -> infinite
Two ways
System.getProperty("user.dir");
or this
File currentDirFile = new File(".");
String helper = currentDirFile.getAbsolutePath();
String currentDir = helper.substring(0, helper.length() - currentDirFile.getCanonicalPath().length());//this line may need a try-catch block
The idea is to get the current folder with ".", and then fetch the absolute position to it and remove the filename from it, so from something like
/home/shark/eclipse/workspace/project/src/com/package/name/bin/Class.class
when you remove Class.class you'd get
/home/shark/eclipse/workspace/project/src/com/package/name/bin/
which is kinda what you want.
I think you'd be interested in the H1 debate. It's a debate about whether to use the h1 element for the page's title or for the logo.
Personally I'd go with your first suggestion, something along these lines:
<div id="header">
<a href="http://example.com/"><img src="images/logo.png" id="site-logo" alt="MyCorp" /></a>
</div>
<!-- or alternatively (with css in a stylesheet ofc-->
<div id="header">
<div id="logo" style="background: url('logo.png'); display: block;
float: left; width: 100px; height: 50px;">
<a href="#" style="display: block; height: 50px; width: 100px;">
<span style="visibility: hidden;">Homepage</span>
</a>
</div>
<!-- with css in a stylesheet: -->
<div id="logo"><a href="#"><span>Homepage</span></a></div>
</div>
<div id="body">
<h1>About Us</h1>
<p>MyCorp has been dealing in narcotics for over nine-thousand years...</p>
</div>
Of course this depends on whether your design uses page titles but this is my stance on this issue.
Use the tee
command:
echo "hello" | tee logfile.txt
This post was helpful for my project hence I thought of sharing my experience as well. The essential thing to note is that the POST request is possible only with a form. I had a similar requirement as I was trying to render a page with ejs. I needed to render a navigation with a list of items that would essentially be hyperlinks and when user selects any one of them, the server responds with appropriate information.
so I basically created each of the navigation items as a form using a loop as follows:
<ul>_x000D_
begin loop..._x000D_
<li>_x000D_
<form action="/" method="post">_x000D_
<input type="hidden" name="country" value="India"/>_x000D_
<button type="submit" name="button">India</button>_x000D_
</form> _x000D_
</li>_x000D_
end loop._x000D_
</ul>
_x000D_
what it did is to create a form with hidden input with a value assigned same as the text on the button. So the end user will see only text from the button and when clicked, will send a post request to the server.
Note that the value parameter of the input box and the Button text are exactly same and were values passed using ejs that I have not shown in this example above to keep the code simple.
here is a screen shot of the navigation... enter image description here
This is extension of answer provided by Ranjith
I would suggest, you to choose a choice-parameter build, and specify the branches that you would like to build. Active Choice Parameter
And after that, you can specify branches to build. Branch to Build
Now, when you would build your project, you would be provided with "Build with Parameters, where you can choose the branch to build"
You can also write a groovy script to fetch all your branches to in active choice parameter.
I had the same issue. When I use window.location
, $window.location
or even <a href="..." target="_self">
the route does not refresh the page. So the cached services are used which is not what I want in my app. I resolved it by adding window.location.reload()
after window.location
to force the page to reload after routing. This method seems to load the page twice though. Might be a dirty trick, but it does the work. This is how I have it now:
$scope.openPage = function (pageName) {
window.location = '#/html/pages/' + pageName;
window.location.reload();
};
This doesn't work because NaN
isn't equal to anything, including NaN
. Use pd.isnull(df.var2)
instead.
After running your local host you get http://localhost:[port number]/
here you found your port number.
Then get your IP address from Command, Open your windows command and type ipconfig
In my case, IP was 192.168.10.33
so my URL will be http://192.168.10.33:[port number]/.
In Android, the studio uses this URL as your URL. And after that set your URL and your port number in manual proxy for the emulator.
You're returning a tuple
. Index it.
obj=list_benefits()
print obj[0] + " is a benefit of functions!"
print obj[1] + " is a benefit of functions!"
print obj[2] + " is a benefit of functions!"
constructor(private activatedRoute: ActivatedRoute) {
this.activatedRoute.queryParams.subscribe(params => {
console.log(params['type'])
}); }
This works for me!
Looking at the answers and the question, it seems the question has been modified significantly. So to answer the current question:
Convert LocalDateTime to LocalDateTime in UTC.
LocalDateTime
does not store any information about the time-zone, it just basically holds the values of year, month, day, hour, minute, second, and smaller units. So an important question is: What is the timezone of the original LocalDateTime
? It might as well be UTC already, therefore no conversion has to be made.
Considering that you asked the question anyway, you probably meant that the original time is in your system-default timezone and you want to convert it to UTC. Because usually a LocalDateTime
object is created by using LocalDateTime.now()
which returns the current time in the system-default timezone. In this case, the conversion would be the following:
LocalDateTime convertToUtc(LocalDateTime time) {
return time.atZone(ZoneId.systemDefault()).withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime();
}
An example of the conversion process:
2019-02-25 11:39 // [time] original LocalDateTime without a timezone
2019-02-25 11:39 GMT+1 // [atZone] converted to ZonedDateTime (system timezone is Madrid)
2019-02-25 10:39 GMT // [withZoneSameInstant] converted to UTC, still as ZonedDateTime
2019-02-25 10:39 // [toLocalDateTime] losing the timezone information
In any other case, when you explicitly specify the timezone of the time to convert, the conversion would be the following:
LocalDateTime convertToUtc(LocalDateTime time, ZoneId zone) {
return time.atZone(zone).withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime();
}
An example of the conversion process:
2019-02-25 11:39 // [time] original LocalDateTime without a timezone
2019-02-25 11:39 GMT+2 // [atZone] converted to ZonedDateTime (zone is Europe/Tallinn)
2019-02-25 09:39 GMT // [withZoneSameInstant] converted to UTC, still as ZonedDateTime
2019-02-25 09:39 // [toLocalDateTime] losing the timezone information
atZone()
MethodThe result of the atZone()
method depends on the time passed as its argument, because it considers all the rules of the timezone, including Daylight Saving Time (DST). In the examples, the time was 25th February, in Europe this means winter time (no DST).
If we were to use a different date, let's say 25th August from last year, the result would be different, considering DST:
2018-08-25 11:39 // [time] original LocalDateTime without a timezone
2018-08-25 11:39 GMT+3 // [atZone] converted to ZonedDateTime (zone is Europe/Tallinn)
2018-08-25 08:39 GMT // [withZoneSameInstant] converted to UTC, still as ZonedDateTime
2018-08-25 08:39 // [toLocalDateTime] losing the timezone information
The GMT time does not change. Therefore the offsets in the other timezones are adjusted. In this example, the summer time of Estonia is GMT+3, and winter time GMT+2.
Also, if you specify a time within the transition of changing clocks back one hour. E.g. October 28th, 2018 03:30 for Estonia, this can mean two different times:
2018-10-28 03:30 GMT+3 // summer time [UTC 2018-10-28 00:30]
2018-10-28 04:00 GMT+3 // clocks are turned back 1 hour [UTC 2018-10-28 01:00]
2018-10-28 03:00 GMT+2 // same as above [UTC 2018-10-28 01:00]
2018-10-28 03:30 GMT+2 // winter time [UTC 2018-10-28 01:30]
Without specifying the offset manually (GMT+2 or GMT+3), the time 03:30
for the timezone Europe/Tallinn
can mean two different UTC times, and two different offsets.
As you can see, the end result depends on the timezone of the time passed as an argument. Because the timezone cannot be extracted from the LocalDateTime
object, you have to know yourself which timezone it is coming from in order to convert it to UTC.
The only reason that the linter complains about using setState({..})
in componentDidMount
and componentDidUpdate
is that when the component render the setState immediately causes the component to re-render.
But the most important thing to note: using it inside these component's lifecycles is not an anti-pattern in React.
Please take a look at this issue. you will understand more about this topic. Thanks for reading my answer.
BigDecimal decPrec = (BigDecimal)yo.get("Avg");
decPrec = decPrec.setScale(5, RoundingMode.CEILING);
String value= String.valueOf(decPrec);
This way you can set specific precision of a BigDecimal
.
The value of decPrec was 1.5726903423607562595809913132345426
which is rounded off to 1.57267
.
You can also simply use the HtmlString
class
@(new HtmlString(Model.Content))
You can get this exception when the Edmx is in one project and you are using it from another.
The reason is Res://*/
is a uri which points to resources in the CURRENT assembly. If the Edm is defined in a different assembly from the code which is using it, res://*/ is not going to work because the resource cannot be found.
Instead of specifying ‘*’, you need to provide the full name of the assembly instead (including public key token). Eg:
res://YourDataAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=abcdefabcedf/YourEdmxFileName.csdl|res://...
A better way to construct connection strings is with EntityConnectionStringBuilder:
public static string GetSqlCeConnectionString(string fileName)
{
var csBuilder = new EntityConnectionStringBuilder();
csBuilder.Provider = "System.Data.SqlServerCe.3.5";
csBuilder.ProviderConnectionString = string.Format("Data Source={0};", fileName);
csBuilder.Metadata = string.Format("res://{0}/YourEdmxFileName.csdl|res://{0}/YourEdmxFileName.ssdl|res://{0}/YourEdmxFileName.msl",
typeof(YourObjectContextType).Assembly.FullName);
return csBuilder.ToString();
}
public static string GetSqlConnectionString(string serverName, string databaseName)
{
SqlConnectionStringBuilder providerCs = new SqlConnectionStringBuilder();
providerCs.DataSource = serverName;
providerCs.InitialCatalog = databaseName;
providerCs.IntegratedSecurity = true;
var csBuilder = new EntityConnectionStringBuilder();
csBuilder.Provider = "System.Data.SqlClient";
csBuilder.ProviderConnectionString = providerCs.ToString();
csBuilder.Metadata = string.Format("res://{0}/YourEdmxFileName.csdl|res://{0}/YourEdmxFileName.ssdl|res://{0}/YourEdmxFileName.msl",
typeof(YourObjectContextType).Assembly.FullName);
return csBuilder.ToString();
}
If you still encounter the exception, open the assembly in reflector and check the filenames for your .csdl, .ssdl and .msl files. When the resources have different names to the ones specified in the metadata value, it’s not going to work.
Use -H or --header
.
Man page: http://curl.haxx.se/docs/manpage.html#-H
If the string should be of fixed length, then substr
from base R
can be used. But, we can get the position of the .
with regexpr
and use that in substr
substr(a, 1, regexpr("\\.", a)-1)
#[1] "NM_020506" "NM_020519" "NM_001030297" "NM_010281" "NM_011419" "NM_053155"
Do not encrypt/decrypt passwords, that is a significant security vulnerability. HASH passwords, using a strong hash algorithm such as PBKDF2, bcrypt, scrypts, or Argon.
When the user sets their password, hash it, and store the hash (and salt).
When the user logs in, re-hash their provided password, and compare it to the hash in the database.
Try SQLDeveloper - there is a migration workbench there
http://www.oracle.com/technetwork/developer-tools/sql-developer/overview/index.html
I've implemented pagination in pure React JS recently. Here is a working demo: http://codepen.io/PiotrBerebecki/pen/pEYPbY
You would of course have to adjust the logic and the way page numbers are displayed so that it meets your requirements.
Full code:
class TodoApp extends React.Component {
constructor() {
super();
this.state = {
todos: ['a','b','c','d','e','f','g','h','i','j','k'],
currentPage: 1,
todosPerPage: 3
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(event) {
this.setState({
currentPage: Number(event.target.id)
});
}
render() {
const { todos, currentPage, todosPerPage } = this.state;
// Logic for displaying todos
const indexOfLastTodo = currentPage * todosPerPage;
const indexOfFirstTodo = indexOfLastTodo - todosPerPage;
const currentTodos = todos.slice(indexOfFirstTodo, indexOfLastTodo);
const renderTodos = currentTodos.map((todo, index) => {
return <li key={index}>{todo}</li>;
});
// Logic for displaying page numbers
const pageNumbers = [];
for (let i = 1; i <= Math.ceil(todos.length / todosPerPage); i++) {
pageNumbers.push(i);
}
const renderPageNumbers = pageNumbers.map(number => {
return (
<li
key={number}
id={number}
onClick={this.handleClick}
>
{number}
</li>
);
});
return (
<div>
<ul>
{renderTodos}
</ul>
<ul id="page-numbers">
{renderPageNumbers}
</ul>
</div>
);
}
}
ReactDOM.render(
<TodoApp />,
document.getElementById('app')
);
Quick and dirty method would be
eval("{ :key_a => { :key_1a => 'value_1a', :key_2a => 'value_2a' }, :key_b => { :key_1b => 'value_1b' } }")
But it has severe security implications.
It executes whatever it is passed, you must be 110% sure (as in, at least no user input anywhere along the way) it would contain only properly formed hashes or unexpected bugs/horrible creatures from outer space might start popping up.
Try this:
Use back-ticks for NAME
CREATE TABLE `teachers` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`addr` varchar(255) NOT NULL,
`phone` int(10) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
You can also check if there is a currentUser
var user = firebase.auth().currentUser;
if (user) {
// User is signed in.
} else {
// No user is signed in.
}
To get the port number in your code you can use the following:
@Autowired
Environment environment;
@GetMapping("/test")
String testConnection(){
return "Your server is up and running at port: "+environment.getProperty("local.server.port");
}
To understand the Environment property you can go through this Spring boot Environment
See jsFiddle demo
I needed a list exactly as described for a project that showed employees at a company, with their photo on the left, and information on the right. I managed to accomplish the clearing by using psuedo-elements after every DD
:
.myList dd:after {
content: '';
display: table;
clear: both;
}
In addition, I wanted the text to only display to the right of the image, without wrapping under the floated image (pseudo-column effect). This can be accomplished by adding a DIV
element with the CSS overflow: hidden;
around the content of the DD
tag. You can omit this extra DIV
, but the content of the DD
tag will wrap under the floated DT
.
After playing with it a while, I was able to support multiple DT
elements per DD
, but not multiple DD
elements per DT
. I tried adding another optional class to clear only after the last DD
, but subsequent DD
elements wrapped under the DT
elements (not my desired effect… I wanted the DT
and DD
elements to form columns, and the extra DD
elements were too wide).
By all rights, this should only work in IE8+, but due to a quirk in IE7 it works there as well.
Use the -o
option.
git commit -o path/to/myfile -m "the message"
-o, --only commit only specified files
Be careful when accessing DateTime.Now twice, as it's possible for the calls to straddle midnight and you'll get wacky results on rare occasions and be left scratching your head.
To be safe, you should assign DateTime.Now to a local variable first if you're going to use it more than once:
var now = DateTime.Now;
var time = now.ToString("hh:mm:ss tt");
var date = now.ToString("MM/dd/yy");
Note the use of lower case "hh" do display hours from 00-11 even in the afternoon, and "tt" to show AM/PM, as the question requested. If you want 24 hour clock 00-23, use "HH".
I know this is really old and most of the folks have already answered it right. Here are at least two ways you can find out the gradle version (not the gradle plugin version) by selecting one of the following on project tab on left:
Perhaps, take a look at this. Its working for me.
The purpose of this is to lookup 'RED' with '/red_color'.
Declaring a static map
and loading the enum
s into it only once would bring some performance benefits if the enum
s are many.
public class Mapper {
public enum Maps {
COLOR_RED("/red_color", "RED");
private final String code;
private final String description;
private static Map<String, String> mMap;
private Maps(String code, String description) {
this.code = code;
this.description = description;
}
public String getCode() {
return name();
}
public String getDescription() {
return description;
}
public String getName() {
return name();
}
public static String getColorName(String uri) {
if (mMap == null) {
initializeMapping();
}
if (mMap.containsKey(uri)) {
return mMap.get(uri);
}
return null;
}
private static void initializeMapping() {
mMap = new HashMap<String, String>();
for (Maps s : Maps.values()) {
mMap.put(s.code, s.description);
}
}
}
}
Please put in your opinons.
I think there is a specific Win32 API call which takes the application path and puts it in the registry automatically for you in the proper location, I've used it in the past but I don't remember the function name anymore.
Yes you can, just pass the integer param to the split method
String stSplit = "apple=fruit table price=5"
stSplit.split("=", 2);
Here is a java doc reference : String#split(java.lang.String, int)
Here is complete solution w.r.t exception/error handling for auto increment, this solution is backward compatible and will work on 11g & 12c, specifically if application is in production.
Please replace 'TABLE_NAME' with your appropriate table name
--checking if table already exisits
BEGIN
EXECUTE IMMEDIATE 'DROP TABLE TABLE_NAME';
EXCEPTION WHEN OTHERS THEN NULL;
END;
/
--creating table
CREATE TABLE TABLE_NAME (
ID NUMBER(10) PRIMARY KEY NOT NULL,
.
.
.
);
--checking if sequence already exists
BEGIN
EXECUTE IMMEDIATE 'DROP SEQUENCE TABLE_NAME_SEQ';
EXCEPTION WHEN OTHERS THEN NULL;
END;
--creating sequence
/
CREATE SEQUENCE TABLE_NAME_SEQ START WITH 1 INCREMENT BY 1 MINVALUE 1 NOMAXVALUE NOCYCLE CACHE 2;
--granting rights as per required user group
/
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE_NAME TO USER_GROUP;
-- creating trigger
/
CREATE OR REPLACE TRIGGER TABLE_NAME_TS BEFORE INSERT OR UPDATE ON TABLE_NAME FOR EACH ROW
BEGIN
-- auto increment column
SELECT TABLE_NAME_SEQ.NextVal INTO :New.ID FROM dual;
-- You can also put some other required default data as per need of your columns, for example
SELECT SYS_CONTEXT('USERENV', 'SESSIONID') INTO :New.SessionID FROM dual;
SELECT SYS_CONTEXT('USERENV','SERVER_HOST') INTO :New.HostName FROM dual;
SELECT SYS_CONTEXT('USERENV','OS_USER') INTO :New.LoginID FROM dual;
.
.
.
END;
/
if using logging.config.fileConfig with a configuration file use something like:
[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=%Y-%m-%d %H:%M:%S
You can also use:
String[] lines = someString.split("\n");
If that doesn't work try replacing \n
with \r\n
.
If you are planning to load an external javascript file's functions or objects, load on this context using the following code – note the runInThisContext method:
var vm = require("vm");
var fs = require("fs");
var data = fs.readFileSync('./externalfile.js');
const script = new vm.Script(data);
script.runInThisContext();
// here you can use externalfile's functions or objects as if they were instantiated here. They have been added to this context.
The second way is the preferred option.
private readonly int MyVal = 5;
public int MyProp { get { return MyVal;} }
This will ensure that MyVal
can only be assigned at initialization (it can also be set in a constructor).
As you had noted - this way you are not exposing an internal member, allowing you to change the internal implementation in the future.
If you're doing it via CMD as you say, then you can just enter the command like so:
path\to\your.exe
which will open it within the same window. For example in C++:
system("path\\to\\your.exe"); // Double backslash for escaping
will open your.exe
in the current CMD window. Likewise to start with a new window, just go for:
system("start path\\to\\your.exe");
If you go for the first option, you would have to clear your screen unless you wanted to have the command to open your.exe
on the screen still.
This may help you:
I have the same exception in my project. After searching while I found that I am missing the @Service annotation to the class where I am implementing the interface which I want to @Autowired.
In your code you can add the @Service annotation to MailManager class.
@Transactional
@Service
public class MailManager extends AbstractManager implements IMailManager {
Mecki's answer is absolutly perfect, but it's worth adding that FreeBSD also supports SO_REUSEPORT_LB
, which mimics Linux' SO_REUSEPORT
behaviour - it balances the load; see setsockopt(2)
max-width is definitely not well supported. If you're going to use it, use it in a media query in your style tag. ios, android, and windows phone default mail all support them. (gmail and outlook mobile don't)
http://www.campaignmonitor.com/guides/mobile/targeting/
Look at the starbucks example at the bottom
In my case, IntelliJ was simply in power safe mode
This should get the id added.
ASP.NET MVC 5 and lower:
<% using (Html.BeginForm(null, null, FormMethod.Post, new { id = "signupform" }))
{ } %>
ASP.NET Core: You can use tag helpers in forms to avoid the odd syntax for setting the id.
<form asp-controller="Account" asp-action="Register" method="post" id="signupform" role="form"></form>
// The integer I want to convert
int myInt = 100;
// Casting of integer to float
float newFloat = (float) myInt
req.setRetryPolicy(new DefaultRetryPolicy(
MY_SOCKET_TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
You can set MY_SOCKET_TIMEOUT_MS
as 100. Whatever you want to set this to is in milliseconds. DEFAULT_MAX_RETRIES
can be 0 default is 1.
As many other pointed out, Intel HAXM only supports Intel CPUs. Since Windows 1804 you can use Microsoft's Hyper-V instead of HAXM for the emulator. This also helps people who want to use Hyper-V for virtual machines as you need to disable hyper-v to run haxm.
Short version:
Long version with more details:
https://blogs.msdn.microsoft.com/visualstudio/2018/05/08/hyper-v-android-emulator-support/
Requirements docs:
defaultMember
already is an alias - it doesn't need to be the name of the exported function/thing. Just do
import alias from 'my-module';
Alternatively you can do
import {default as alias} from 'my-module';
but that's rather esoteric.
In testing2.php use the following code to get the name:
if ( ! empty($_POST['name'])){
$name = $_POST['name']);
}
When you create the next page, use the value of $name
to prefill the form field:
Name: <input type="text" name="name" id="name" value="<?php echo $name; ?>"><br/>
However, before doing that, be sure to use regular expressions to verify that the $name only contains valid characters, such as:
$pattern = '/^[0-9A-Za-zÁ-Úá-úàÀÜü]+$/';//integers & letters
if (preg_match($pattern, $name) == 1){
//continue
} else {
//reload form with error message
}
The WS-I group published something called "Reliable Secure Profile" that has a Glass Fish and .NET implementation that apparently inter-operate well.
With any luck there is a Javascript implementation out there as well.
There is also a Silverlight implementation that uses HTTP Duplex. You can connect javascript to the Silverlight object to get callbacks when a push occurs.
There are also commercial paid versions as well.
To explain the difference between these two let me explain the difference between encodeURI
and encodeURIComponent
.
The main difference is that:
encodeURI
function is intended for use on the full URI.encodeURIComponent
function is intended to be used on .. well .. URI components that is
any part that lies between separators (; / ? : @ & = + $ , #).So, in encodeURIComponent
these separators are encoded also because they are regarded as text and not special characters.
Now back to the difference between the decode functions, each function decodes strings generated by its corresponding encode counterpart taking care of the semantics of the special characters and their handling.
For NodeJS I would get the file name from the res.url
, write the header for the file by getting the extension of the file with path.extname
, create a read stream for the file, and pipe the response.
const http = require('http');
const fs = require('fs');
const path = require('path');
const port = process.env.PORT || 3000;
const server = http.createServer((req, res) => {
let filePath = path.join(
__dirname,
"public",
req.url === "/" ? "index.html" : req.url
);
let extName = path.extname(filePath);
let contentType = 'text/html';
switch (extName) {
case '.css':
contentType = 'text/css';
break;
case '.js':
contentType = 'text/javascript';
break;
case '.json':
contentType = 'application/json';
break;
case '.png':
contentType = 'image/png';
break;
case '.jpg':
contentType = 'image/jpg';
break;
}
console.log(`File path: ${filePath}`);
console.log(`Content-Type: ${contentType}`)
res.writeHead(200, {'Content-Type': contentType});
const readStream = fs.createReadStream(filePath);
readStream.pipe(res);
});
server.listen(port, (err) => {
if (err) {
console.log(`Error: ${err}`)
} else {
console.log(`Server listening at port ${port}...`);
}
});
You can use TreeSet class in java.util.*. It is working like Binary search tree, so it is already sorted. TreeSet class implements Iterable, Collection and Set interfaces. You can traverse through the tree with iterator like a set.
TreeSet<String> treeSet = new TreeSet<String>();
Iterator<String> it = treeSet.Iterator();
while(it.hasNext()){
...
}
Use, a global variable or property for assigning the value to the textbox, give the value for the variable in another class and assign it to the textbox.text in form class.
Android SDK implementation of FragmentTransaction wants an Animator
while support library wants an Animation
, don't ask me why but after strangeluk's comment I looked into android 4.0.3 code and support library.
Android SDK uses loadAnimator()
and support library uses loadAnimation()
If none of the solutions on this page work and you are having the below issue:
You can simply use this snippet of CSS:
td {
padding: 0;
}
Just to put one example here (system is in existingState
, and we want to find elements to remove (elements that are not in newState
but are present in existingState
) and elements to add (elements that are in newState
but are not present in existingState
) :
public class AddAndRemove {
static Set<Integer> existingState = Set.of(1,2,3,4,5);
static Set<Integer> newState = Set.of(0,5,2,11,3,99);
public static void main(String[] args) {
Set<Integer> add = new HashSet<>(newState);
add.removeAll(existingState);
System.out.println("Elements to add : " + add);
Set<Integer> remove = new HashSet<>(existingState);
remove.removeAll(newState);
System.out.println("Elements to remove : " + remove);
}
}
would output this as a result:
Elements to add : [0, 99, 11]
Elements to remove : [1, 4]
I had the same issue on Chrome. It only happened for me when the scroll bar is always visible. (found in the general settings) I have a modal and when I open the modal I noticed that...
body {
padding-left: 15px;
}
is added to the body. To stop this from happening I added
body {
padding-left: 0px !important;
}
Try declaring the unit of width:
e1.style.width = "400px"; // width in PIXELS
All you need is to give the AnchorPane
an ID, and then you can get the Stage
from that.
@FXML private AnchorPane ap;
Stage stage = (Stage) ap.getScene().getWindow();
From here, you can add in the Listener
that you need.
Edit: As stated by EarthMind below, it doesn't have to be the AnchorPane
element; it can be any element that you've defined.
The error seems clear: model objects do not support item assignment.
MyModel.objects.latest('id')['foo'] = 'bar'
will throw this same error.
It's a little confusing that your model instance is called projectForm
...
To reproduce your first block of code in a loop, you need to use setattr
for k,v in session_results.iteritems():
setattr(projectForm, k, v)
You can access user data directly in the twig template without requesting anything in the controller. The user is accessible like that : app.user
.
Now, you can access every property of the user. For example, you can access the username like that : app.user.username
.
Warning, if the user is not logged, the app.user
is null.
If you want to check if the user is logged, you can use the is_granted
twig function. For example, if you want to check if the user has ROLE_ADMIN
, you just have to do is_granted("ROLE_ADMIN")
.
So, in every of your pages you can do :
{% if is_granted("ROLE") %}
Hi {{ app.user.username }}
{% endif %}
You can set this in your manifest file..
android:name=".your launching activity name"
android:screenOrientation="portrait"
and you can also achive the same by writing the code in your class file like:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Hierarchy of log4j logging levels are as follows in Highest to Lowest order :
TRACE log level provides highest logging which would be helpful to troubleshoot issues. DEBUG log level is also very useful to trouble shoot the issues.
You can also refer this link for more information about log levels : https://logging.apache.org/log4j/2.0/manual/architecture.html
I don't think this DateTimePicker has been mentioned before:
A WPF DateTimePicker That Works Like the One in Winforms
That one is in VB and has some bugs. I converted it to C# and made a new version with bug fixes.
Note: I used the Calendar control in WPFToolkit so that I could use .NET 3.5 instead of .NET 4. If you are using .NET 4, just remove references to "wpftc" in the XAML.
Now use np.array_equal
. From documentation:
np.array_equal([1, 2], [1, 2])
True
np.array_equal(np.array([1, 2]), np.array([1, 2]))
True
np.array_equal([1, 2], [1, 2, 3])
False
np.array_equal([1, 2], [1, 4])
False
Try out this
var str ="{ "name" : "user"}";
var jsonData = JSON.parse(str);
console.log(jsonData.name)
//Array Object
str ="[{ "name" : "user"},{ "name" : "user2"}]";
jsonData = JSON.parse(str);
console.log(jsonData[0].name)
Adding msecs was the better option, Thanks. Here is my amendment using this with Python 3.5.3 in Blender
import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s.%(msecs)03d %(levelname)s:\t%(message)s', datefmt='%Y-%m-%d %H:%M:%S')
log = logging.getLogger(__name__)
log.info("Logging Info")
log.debug("Logging Debug")
/\{([^}]+)\}/
/ - delimiter
\{ - opening literal brace escaped because it is a special character used for quantifiers eg {2,3}
( - start capturing
[^}] - character class consisting of
^ - not
} - a closing brace (no escaping necessary because special characters in a character class are different)
+ - one or more of the character class
) - end capturing
\} - the closing literal brace
/ - delimiter
I don't know if it is stylable with CSS (probably not in IE), but please: do not use a "fake" drop-down box using javascript, because the usability of these things usually is horrible. Among other things, keyboard navigation is usually absent.
Use
code -n
when launching the program. This "Opens a new session of Visual Studio Code instead of restoring the previous session." (from here).
The way I used this was by modifying my "Code" shortcut to include the -n
parameter:
If it does not work, restart VSCode
I always prefer to use mixins for small CSS classes like fade in / out incase you want to use them in more than one class.
@mixin fade-in {
opacity: 1;
animation-name: fadeInOpacity;
animation-iteration-count: 1;
animation-timing-function: ease-in;
animation-duration: 2s;
}
@keyframes fadeInOpacity {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
and if you don't want to use mixins, you can create a normal class .fade-in.
You can do it as Billy Moat told you, wrap your <img>
and <h1>
in a <div>
and use float: left;
to float your image to the left, set the <div>
width
and than set a line-height
for your h1
and use <div style="clear: float;"></div>
to clear your floating elements.
If you don't handle an exception, it will propagate up the call stack up to the interpreter, which will then display a traceback and exit. IOW : you don't have to do anything to make your script exit when an exception happens.
I assume that you're running a Linux, and you're using gEdit to edit your files. In the /etc/nginx/sites-enabled
, it may have left a temp file e.g. default~
(watch the ~
).
Depending on your editor, the file could be named .save
or something like it. Just run $ ls -lah
to see which files are unintended to be there and remove them (Thanks @Tisch for this).
Delete this file, and it will solve your problem.
I see what you are trying to ask and I think this is the simplest answer to what you are looking for, given you might not know how many key pairs your are being sent.
Simple Key Pair JSON structure
var data = {
'XXXXXX' : '100.0',
'YYYYYYY' : '200.0',
'ZZZZZZZ' : '500.0',
}
Usage JavaScript code to access the key pairs
for (var key in data)
{ if (!data.hasOwnProperty(key))
{ continue; }
console.log(key + ' -> ' + data[key]);
};
Console output should look like this
XXXXXX -> 100.0
YYYYYYY -> 200.0
ZZZZZZZ -> 500.0
Here is a JSFiddle to show how it works.
Here you go: Working Fidddle
$(function(){
var dateFormat = 'DD-MM-YYYY';
alert(moment(moment("2012-10-19").format(dateFormat),dateFormat,true).isValid());
});
The simplest way to log out and redirect back to the login or index:
<?php
if (!isset($_SESSION)) { session_start(); }
$_SESSION = array();
session_destroy();
header("Location: login.php"); // Or wherever you want to redirect
exit();
?>
In the PHP version you can send 'true' in the last parameter, but the default is 'false'. The following algorithm is equivalent to the default PHP's hash function when passing 'sha256' as the first parameter:
public static string GetSha256FromString(string strData)
{
var message = Encoding.ASCII.GetBytes(strData);
SHA256Managed hashString = new SHA256Managed();
string hex = "";
var hashValue = hashString.ComputeHash(message);
foreach (byte x in hashValue)
{
hex += String.Format("{0:x2}", x);
}
return hex;
}
A2 Hosting permits node.js on their shared hosting accounts. I can vouch that I've had a positive experience with them.
Here are instructions in their KnowledgeBase for installing node.js using Apache/LiteSpeed as a reverse proxy: https://www.a2hosting.com/kb/installable-applications/manual-installations/installing-node-js-on-managed-hosting-accounts . It takes about 30 minutes to set up the configuration, and it'll work with npm, Express, MySQL, etc.
See a2hosting.com.
newTitle
is a local variable where you create the fields. So when that functions ends, the variable newTitle
, does not exist anymore. (The JTextField that was referenced by newTitle
does still exist however.)
Thus, increase the scope of the variable, so that you can access it another method.
public SomeFrame extends JFrame {
JTextField myTitle;//can be used anywhere in this class
creationOfTheFields()
{
//other code
myTitle = new JTextField("spam");
myTitle.setBounds(80, 40, 225, 20);
options.add(myTitle);
//blabla other code
}
private void New_Name()
{
this.setTitle(myTitle.getText());
}
}
Use CSS, it makes for much easier management of the style itself.
You have to create an item of type ListBoxItem and add that to the Items collection:
list.Items.add( new ListBoxItem("clan", "sifOsoba"));
After you connect the UIButton that you want to change its background as an OUtlet to your ViewController.swift file you can use the following:
yourUIButton.backgroundColor = UIColor.blue
Add a style with the attribute text-decoration:none;
:
There are a number of different ways of doing this.
Inline style:
<a href="xxx.html" style="text-decoration:none;">goto this link</a>
Inline stylesheet:
<html>
<head>
<style type="text/css">
a {
text-decoration:none;
}
</style>
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>
External stylesheet:
<html>
<head>
<link rel="Stylesheet" href="stylesheet.css" />
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>
stylesheet.css:
a {
text-decoration:none;
}
You need to set the password for root@localhost
to be blank. There are two ways:
The MySQL SET PASSWORD
command:
SET PASSWORD FOR root@localhost=PASSWORD('');
Using the command-line mysqladmin
tool:
mysqladmin -u root -pType_in_your_current_password_here password ''
Perhaps you lost some configuration, check jar dependencies in properties -> Deployment Assembly. If you miss something, try to add dependencies again.
in my case, fixing this, Run on Server appear again.
$( "#btn1" ).click(function() {
$('#btn2').css('display','none');
});
If you clone with the --depth
parameter, it sets .git/config
not to fetch all branches, but only master.
You can simply omit the parameter or update the configuration file from
fetch = +refs/heads/master:refs/remotes/origin/master
to
fetch = +refs/heads/*:refs/remotes/origin/*
My version without a loop would be like this:
echo implode(
"\n",
array_map(
function ($k, $v) {
return "$k is at $v";
},
array_keys($page),
array_values($page)
)
);
Based on @pymarco answer I wrote this solution, it's not perfect but solves the select2 focus problem and maintain tab sequence working inside modal
$.fn.modal.Constructor.prototype.enforceFocus = function () {
$(document)
.off('focusin.bs.modal') // guard against infinite focus loop
.on('focusin.bs.modal', $.proxy(function (e) {
if (this.$element[0] !== e.target && !this.$element.has(e.target).length && !$(e.target).closest('.select2-dropdown').length) {
this.$element.trigger('focus')
}
}, this))
}
see w3schools samples: https://www.w3schools.com/angular/angular_filters.asp https://www.w3schools.com/angular/tryit.asp?filename=try_ng_filters_orderby_click
then add the "reverse" flag:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<p>Click the table headers to change the sorting order:</p>
<div ng-app="myApp" ng-controller="namesCtrl">
<table border="1" width="100%">
<tr>
<th ng-click="orderByMe('name')">Name</th>
<th ng-click="orderByMe('country')">Country</th>
</tr>
<tr ng-repeat="x in names | orderBy:myOrderBy:reverse">
<td>{{x.name}}</td>
<td>{{x.country}}</td>
</tr>
</table>
</div>
<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
$scope.names = [
{name:'Jani',country:'Norway'},
{name:'Carl',country:'Sweden'},
{name:'Margareth',country:'England'},
{name:'Hege',country:'Norway'},
{name:'Joe',country:'Denmark'},
{name:'Gustav',country:'Sweden'},
{name:'Birgit',country:'Denmark'},
{name:'Mary',country:'England'},
{name:'Kai',country:'Norway'}
];
$scope.reverse=false;
$scope.orderByMe = function(x) {
if($scope.myOrderBy == x) {
$scope.reverse=!$scope.reverse;
}
$scope.myOrderBy = x;
}
});
</script>
</body>
</html>
Method overloading deals with the notion of having two or more methods in the same class with the same name but different arguments.
void foo(int a)
void foo(int a, float b)
Method overriding means having two methods with the same arguments, but different implementations. One of them would exist in the parent class, while another will be in the derived, or child class. The @Override
annotation, while not required, can be helpful to enforce proper overriding of a method at compile time.
class Parent {
void foo(double d) {
// do something
}
}
class Child extends Parent {
@Override
void foo(double d){
// this method is overridden.
}
}
I just applied the patch above and it starts working.
diff --git a/sweet-alert.js b/sweet-alert.js_x000D_
index ab6e1f1..d7eafaa 100755_x000D_
--- a/sweet-alert.js_x000D_
+++ b/sweet-alert.js_x000D_
@@ -200,7 +200,8 @@_x000D_
confirmButtonColor: '#AEDEF4',_x000D_
cancelButtonText: 'Cancel',_x000D_
imageUrl: null,_x000D_
- imageSize: null_x000D_
+ imageSize: null,_x000D_
+ html: false_x000D_
};_x000D_
_x000D_
if (arguments[0] === undefined) {_x000D_
@@ -224,6 +225,7 @@_x000D_
return false;_x000D_
}_x000D_
_x000D_
+ params.html = arguments[0].html;_x000D_
params.title = arguments[0].title;_x000D_
params.text = arguments[0].text || params.text;_x000D_
params.type = arguments[0].type || params.type;_x000D_
@@ -477,11 +479,18 @@_x000D_
$cancelBtn = modal.querySelector('button.cancel'),_x000D_
$confirmBtn = modal.querySelector('button.confirm');_x000D_
_x000D_
+ console.log(params.html);_x000D_
// Title_x000D_
- $title.innerHTML = escapeHtml(params.title).split("\n").join("<br>");_x000D_
+ if(params.html)_x000D_
+ $title.innerHTML = params.title.split("\n").join("<br>");_x000D_
+ else_x000D_
+ $title.innerHTML = escapeHtml(params.title).split("\n").join("<br>");_x000D_
_x000D_
// Text_x000D_
- $text.innerHTML = escapeHtml(params.text || '').split("\n").join("<br>");_x000D_
+ if(params.html)_x000D_
+ $text.innerHTML = params.text.split("\n").join("<br>");_x000D_
+ else_x000D_
+ $text.innerHTML = escapeHtml(params.text || '').split("\n").join("<br>");_x000D_
if (params.text) {_x000D_
show($text);_x000D_
}
_x000D_
You may use StickyMap
and MapEntry
from Cactoos:
private static final Map<String, String> MAP = new StickyMap<>(
new MapEntry<>("name", "Jeffrey"),
new MapEntry<>("age", "35")
);
I'm using this:
@RequestMapping(method = RequestMethod.GET)
public void welcome(SecurityContextHolderAwareRequestWrapper request) {
boolean b = request.isUserInRole("ROLE_ADMIN");
System.out.println("ROLE_ADMIN=" + b);
boolean c = request.isUserInRole("ROLE_USER");
System.out.println("ROLE_USER=" + c);
}
None of the other answers helped me. Here's what worked for me. I'm using the tutorial-1 sample from opencv but I will be doing using the NDK in my project so I'm using the gradle-experimental plugin which has a different structure than the gradle plugin.
Android studio should be installed, the Android NDK should be installed via the Android SDK Manager, and the OpenCV Android SDK should be downloaded and unzipped.
This is in chunks of bash script to keep it compact but complete. It's also all on the command line because on of the big problems I had was that in-IDE instructions were obsolete as the IDE evolved.
First set the location of the root directory of the OpenCV SDK.
export OPENCV_SDK=/home/user/wip/OpenCV-2.4.11-android-sdk
cd $OPENCV_SDK
Create your gradle build files...
First the OpenCV library
cat > $OPENCV_SDK/sdk/java/build.gradle <<'==='
apply plugin: 'com.android.model.library'
model {
android {
compileSdkVersion = 23
buildToolsVersion = "23.0.2"
defaultConfig.with {
minSdkVersion.apiLevel = 8
targetSdkVersion.apiLevel = 23
}
}
android.buildTypes {
release {
minifyEnabled = false
}
debug{
minifyEnabled = false
}
}
android.sources {
main.manifest.source.srcDirs += "."
main.res.source.srcDirs += "res"
main.aidl.source.srcDirs += "src"
main.java.source.srcDirs += "src"
}
}
===
Then tell the tutorial sample what to label the library as and where to find it.
cat > $OPENCV_SDK/samples/tutorial-1-camerapreview/settings.gradle <<'==='
include ':openCVLibrary2411'
project(':openCVLibrary2411').projectDir = new File('../../sdk/java')
===
Create the build file for the tutorial.
cat > $OPENCV_SDK/samples/tutorial-1-camerapreview/build.gradle <<'==='
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle-experimental:0.2.1'
}
}
allprojects {
repositories {
jcenter()
}
}
apply plugin: 'com.android.model.application'
model {
android {
compileSdkVersion = 23
buildToolsVersion = "23.0.2"
defaultConfig.with {
applicationId = "org.opencv.samples.tutorial1"
minSdkVersion.apiLevel = 8
targetSdkVersion.apiLevel = 23
}
}
android.sources {
main.manifest.source.srcDirs += "."
main.res.source.srcDirs += "res"
main.aidl.source.srcDirs += "src"
main.java.source.srcDirs += "src"
}
android.buildTypes {
release {
minifyEnabled = false
proguardFiles += file('proguard-rules.pro')
}
debug {
minifyEnabled = false
}
}
}
dependencies {
compile project(':openCVLibrary2411')
}
===
Your build tools version needs to be set correctly. Here's an easy way to see what you have installed. (You can install other versions via the Android SDK Manager). Change buildToolsVersion if you don't have 23.0.2.
echo "Your buildToolsVersion is one of: "
ls $ANDROID_HOME/build-tools
Change the environment variable on the first line to your version number
REP=23.0.2 #CHANGE ME
sed -i.bak s/23\.0\.2/${REP}/g $OPENCV_SDK/sdk/java/build.gradle
sed -i.bak s/23\.0\.2/${REP}/g $OPENCV_SDK/samples/tutorial-1-camerapreview/build.gradle
Finally, set up the correct gradle wrapper. Gradle needs a clean directory to do this.
pushd $(mktemp -d)
gradle wrapper --gradle-version 2.5
mv -f gradle* $OPENCV_SDK/samples/tutorial-1-camerapreview
popd
You should now be all set. You can now browse to this directory with Android Studio and open up the project.
Build the tutoral on the command line with the following command:
./gradlew assembleDebug
It should build your apk, putting it in ./build/outputs/apk
Actually you do not need to use delegate keyword. Just pass lambda as parameter:
control.Invoke((MethodInvoker)(() => {this.Text = "Hi"; }));
If you are using local resources you can refer to them as below:
<TextBlock Text="{Binding Source={x:Static prop:Resources.PerUnitOfMeasure}}" TextWrapping="Wrap" TextAlignment="Center"/>
Please see the following information from user Pekka ?
According to the manual, destructors are executed even if the script gets terminated using die()
or exit()
:
The destructor will be called even if script execution is stopped using exit()
. Calling exit() in a destructor will prevent the remaining shutdown routines from executing.
According to this PHP: destructor vs register_shutdown_function, the destructor does not get executed when PHP's execution time limit is reached (Confirmed on Apache 2, PHP 5.2 on Windows 7).
The destructor also does not get executed when the script terminates because the memory limit was reached. (Just tested)
The destructor does get executed on fatal errors (Just tested) Update: The OP can't confirm this - there seem to be fatal errors where things are different
It does not get executed on parse errors (because the whole script won't be interpreted)
The destructor will certainly not be executed if the server process crashes or some other exception out of PHP's control occurs.
Referenced in this question Are there any instances when the destructor in PHP is NOT called?
Trivial as it may seem in my case netbeans version maven project 7.2.1 was different. There is a folder in the project called dependencies. Right click and then it brings up a popup window where you can search for packages. In the query area put
mysql-connector
It will bring up the matches (it seems it does this against some repository). Double click then install.
When working with bootsrap usually face three main problems:
To solve first two problems download this small plugin https://github.com/codekipple/conformity
The third problem is solved here http://www.minimit.com/articles/solutions-tutorials/bootstrap-3-responsive-centered-columns
<style>
[class*=col-] {position: relative}
.row-conformity .to-bottom {position:absolute; bottom:0; left:0; right:0}
.row-centered {text-align:center}
.row-centered [class*=col-] {display:inline-block; float:none; text-align:left; margin-right:-4px; vertical-align:top}
</style>
<script src="assets/conformity/conformity.js"></script>
<script>
$(document).ready(function () {
$('.row-conformity > [class*=col-]').conformity();
$(window).on('resize', function() {
$('.row-conformity > [class*=col-]').conformity();
});
});
</script>
<div class="row row-conformity">
<div class="col-sm-3">
I<br>create<br>highest<br>column
</div>
<div class="col-sm-3">
<div class="to-bottom">
I am on the bottom
</div>
</div>
</div>
<div class="row row-conformity">
<div class="col-sm-4">We all have equal height</div>
<div class="col-sm-4">...</div>
<div class="col-sm-4">...</div>
<div class="col-sm-4">...</div>
<div class="col-sm-4">...</div>
<div class="col-sm-4">...</div>
</div>
<div class="row row-centered">
<div class="col-sm-3">...</div>
<div class="col-sm-4">...</div>
</div>
<div class="row row-conformity row-centered">
...
</div>
You need to use DateTime.ParseExact
with format "dd/MM/yyyy"
DateTime dt=DateTime.ParseExact("24/01/2013", "dd/MM/yyyy", CultureInfo.InvariantCulture);
Its safer if you use d/M/yyyy
for the format, since that will handle both single digit and double digits day/month. But that really depends if you are expecting single/double digit values.
Your date format day/Month/Year
might be an acceptable date format for some cultures. For example for Canadian Culture en-CA
DateTime.Parse
would work like:
DateTime dt = DateTime.Parse("24/01/2013", new CultureInfo("en-CA"));
Or
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-CA");
DateTime dt = DateTime.Parse("24/01/2013"); //uses the current Thread's culture
Both the above lines would work because the the string's format is acceptable for en-CA
culture. Since you are not supplying any culture to your DateTime.Parse
call, your current culture is used for parsing which doesn't support the date format. Read more about it at DateTime.Parse.
Another method for parsing is using DateTime.TryParseExact
DateTime dt;
if (DateTime.TryParseExact("24/01/2013",
"d/M/yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt))
{
//valid date
}
else
{
//invalid date
}
The TryParse
group of methods in .Net framework doesn't throw exception on invalid values, instead they return a bool
value indicating success or failure in parsing.
Notice that I have used single d
and M
for day and month respectively. Single d
and M
works for both single/double digits day and month. So for the format d/M/yyyy
valid values could be:
For further reading you should see: Custom Date and Time Format Strings
I would like to add a standard library option (i.e. cross-platform) how to generate exception backtraces, which has become available with C++11:
std::nested_exception
and std::throw_with_nested
This won't give you a stack unwind, but in my opinion the next best thing. It is described on StackOverflow here and here, how you can get a backtrace on your exceptions inside your code without need for a debugger or cumbersome logging, by simply writing a proper exception handler which will rethrow nested exceptions.
Since you can do this with any derived exception class, you can add a lot of information to such a backtrace! You may also take a look at my MWE on GitHub, where a backtrace would look something like this:
Library API: Exception caught in function 'api_function'
Backtrace:
~/Git/mwe-cpp-exception/src/detail/Library.cpp:17 : library_function failed
~/Git/mwe-cpp-exception/src/detail/Library.cpp:13 : could not open file "nonexistent.txt"
I think you want to change the inner padding/margin of the TextField
.
You can do that by adding isDense: true
and contentPadding: EdgeInsets.all(8)
properties as follow:
Container(
padding: EdgeInsets.all(12),
child: Column(
children: <Widget>[
TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Default TextField',
),
),
SizedBox(height: 16,),
TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Densed TextField',
isDense: true, // Added this
),
),
SizedBox(height: 16,),
TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Even Densed TextFiled',
isDense: true, // Added this
contentPadding: EdgeInsets.all(8), // Added this
),
)
],
),
)
It will be displayed as:
It is a trivial process. You can see a good example in the source code SMSPopup
Examine the following methods:
SmsMmsMessage getSmsDetails(Context context, long ignoreThreadId, boolean unreadOnly)
long findMessageId(Context context, long threadId, long _timestamp, int messageType
void setMessageRead(Context context, long messageId, int messageType)
void deleteMessage(Context context, long messageId, long threadId, int messageType)
this is the method for reading:
SmsMmsMessage getSmsDetails(Context context,
long ignoreThreadId, boolean unreadOnly)
{
String SMS_READ_COLUMN = "read";
String WHERE_CONDITION = unreadOnly ? SMS_READ_COLUMN + " = 0" : null;
String SORT_ORDER = "date DESC";
int count = 0;
// Log.v(WHERE_CONDITION);
if (ignoreThreadId > 0) {
// Log.v("Ignoring sms threadId = " + ignoreThreadId);
WHERE_CONDITION += " AND thread_id != " + ignoreThreadId;
}
Cursor cursor = context.getContentResolver().query(
SMS_INBOX_CONTENT_URI,
new String[] { "_id", "thread_id", "address", "person", "date", "body" },
WHERE_CONDITION,
null,
SORT_ORDER);
if (cursor != null) {
try {
count = cursor.getCount();
if (count > 0) {
cursor.moveToFirst();
// String[] columns = cursor.getColumnNames();
// for (int i=0; i<columns.length; i++) {
// Log.v("columns " + i + ": " + columns[i] + ": " + cursor.getString(i));
// }
long messageId = cursor.getLong(0);
long threadId = cursor.getLong(1);
String address = cursor.getString(2);
long contactId = cursor.getLong(3);
String contactId_string = String.valueOf(contactId);
long timestamp = cursor.getLong(4);
String body = cursor.getString(5);
if (!unreadOnly) {
count = 0;
}
SmsMmsMessage smsMessage = new SmsMmsMessage(context, address,
contactId_string, body, timestamp,
threadId, count, messageId, SmsMmsMessage.MESSAGE_TYPE_SMS);
return smsMessage;
}
} finally {
cursor.close();
}
}
return null;
}
You need to give the WebClient object the credentials. Something like this...
WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
The simplest way, with circular reference handling and all:
function dump(t, indent, done)
done = done or {}
indent = indent or 0
done[t] = true
for key, value in pairs(t) do
print(string.rep("\t", indent))
if (type(value) == "table" and not done[value]) then
done[value] = true
print(key, ":\n")
dump(value, indent + 2, done)
done[value] = nil
else
print(key, "\t=\t", value, "\n")
end
end
end
you may also like this
var Grp = Model.GroupBy(item => item.Order.Customer)
.Select(group => new
{
Customer = Model.First().Customer,
CustomerId= group.Key,
Orders= group.ToList()
})
.ToList();
Another way to make objects in Javascript
using JQuery
, getting data from the dom and pass it to the object Box and, for example, store them in an array of Boxes, could be:
var box = {}; // my object
var boxes = []; // my array
$('div.test').each(function (index, value) {
color = $('p', this).attr('color');
box = {
_color: color // being _color a property of `box`
}
boxes.push(box);
});
Hope it helps!
You can also map the share to a local drive as follows:
net use X: "\\servername\share" /user:morgan password
Lua is lightweight scripting language which want to smaller as possible. For example, many unary operation such as pre/post increment is not available
Instead of continue, you can use goto like
arr = {1,2,3,45,6,7,8}
for key,val in ipairs(arr) do
if val > 6 then
goto skip_to_next
end
# perform some calculation
::skip_to_next::
end
Reader they show at http://www.webqr.com/index.html works like a charm, but literaly, you need the one on the webpage, the github version it's really hard to make it work, however, it is possible. The best way to go is reverse-engineer the example shown at the webpage.
However, to edit and get the full potential out of it, it's not so easy. At some point I may post the stripped-down reverse-engineered QR reader, but in the meantime have some fun hacking the code.
Happy coding.
You can add these style's and it works just as expected.
.btn {
white-space:normal !important;
word-wrap: break-word;
word-break: normal;
}
Java script:
use elementid. selectedIndex()
function to get the selected index
I've had this problem before. Figured out I had another application using the same port (3000).
Easy way to find this out:
In the terminal, type netstat -a -p TCP -n | grep 3000
(substitute the port you're using for the '3000'). If there is more than one listening, something else is already occupying that port. You should stop that process or change the port for your new process.
See if this example provides any clarification. Basically you configure a set of routes and include partial templates based on the route. Setting ng-view in your main index.html allows you to inject those partial views.
The config portion looks like this:
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {controller:'ListCtrl', templateUrl:'list.html'})
.otherwise({redirectTo:'/'});
}])
The point of entry for injecting the partial view into your main template is:
<div class="container" ng-view=""></div>
There's no such concept of an "index" within a dictionary - it's fundamentally unordered. Of course when you iterate over it you'll get the items in some order, but that order isn't guaranteed and can change over time (particularly if you add or remove entries).
Obviously you can get the key from a KeyValuePair
just by using the Key
property, so that will let you use the indexer of the dictionary:
var pair = ...;
var value = dictionary[pair.Key];
Assert.AreEqual(value, pair.Value);
You haven't really said what you're trying to do. If you're trying to find some key which corresponds to a particular value, you could use:
var key = dictionary.Where(pair => pair.Value == desiredValue)
.Select(pair => pair.Key)
.FirstOrDefault();
key
will be null if the entry doesn't exist.
This is assuming that the key type is a reference type... if it's a value type you'll need to do things slightly differently.
Of course, if you really want to look up values by key, you should consider using another dictionary which maps the other way round in addition to your existing dictionary.
this.dtOptions = {
order: [],
columnDefs: [ {
'targets': [0], /* column index [0,1,2,3]*/
'orderable': false, /* true or false */
}],
........ rest all stuff .....
}
The above worked fine for me.
(I am using Angular version 7, angular-datatables version 6.0.0 and bootstrap version 4)
EDIT: As mentioned by Stephen Niedzielski in his comment, the issue seems to come from the 32-bit being of the JRE, which is de facto, looking for the 32-bit version of libXtst6
. To install the required version of the library:
$ sudo apt-get install libxtst6:i386
Type:
$ sudo apt-get update
$ sudo apt-get install libxtst6
If this isn’t OK, type:
$ sudo updatedb
$ locate libXtst
it should return something like:
/usr/lib/x86_64-linux-gnu/libXtst.so.6 # Mine is OK
/usr/lib/x86_64-linux-gnu/libXtst.so.6.1.0
If you do not have libXtst.so.6
but do have libXtst.so.6.X.X
create a symbolic link:
$ cd /usr/lib/x86_64-linux-gnu/
$ ln -s libXtst.so.6 libXtst.so.6.X.X
Hope this helps.
You should not use those headers, the headers determine what kind of type you are sending, and you are clearly sending an object, which means, JSON.
Instead you should set the option responseType
to text
:
addToCart(productId: number, quantity: number): Observable<any> {
const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
return this.http.post(
'http://localhost:8080/order/addtocart',
{ dealerId: 13, createdBy: "-1", productId, quantity },
{ headers, responseType: 'text'}
).pipe(catchError(this.errorHandlerService.handleError));
}
Normally you should use margin: 0 auto on the div as mentioned in the other answers, but you'll have to specify a width for the div. If you don't want to specify a width you could either (this is depending on what you're trying to do) use margins, something like margin: 0 200px; , this should make your content seems as if it's centered, you could also see the answer of Leyu to my question
The heredoc solutions are certainly the most common way to do this. Other common solutions are:
echo 'line 1, '"${kernel}"' line 2, line 3, '"${distro}"' line 4' > /etc/myconfig.conf
and
exec 3>&1 # Save current stdout exec > /etc/myconfig.conf echo line 1, ${kernel} echo line 2, echo line 3, ${distro} ... exec 1>&3 # Restore stdout
I wrote a tiny little function which does this. It only escapes "
, &
, <
and >
(but usually that's all you need anyway). It is slightly more elegant then the earlier proposed solutions in that it only uses one .replace()
to do all the conversion. (EDIT 2: Reduced code complexity making the function even smaller and neater, if you're curious about the original code see end of this answer.)
function escapeHtml(text) {
'use strict';
return text.replace(/[\"&<>]/g, function (a) {
return { '"': '"', '&': '&', '<': '<', '>': '>' }[a];
});
}
This is plain Javascript, no jQuery used.
/
and '
tooEdit in response to mklement's comment.
The above function can easily be expanded to include any character. To specify more characters to escape, simply insert them both in the character class in the regular expression (i.e. inside the /[...]/g
) and as an entry in the chr
object. (EDIT 2: Shortened this function too, in the same way.)
function escapeHtml(text) {
'use strict';
return text.replace(/[\"&'\/<>]/g, function (a) {
return {
'"': '"', '&': '&', "'": ''',
'/': '/', '<': '<', '>': '>'
}[a];
});
}
Note the above use of '
for apostrophe (the symbolic entity '
might have been used instead – it is defined in XML, but was originally not included in the HTML spec and might therefore not be supported by all browsers. See: Wikipedia article on HTML character encodings). I also recall reading somewhere that using decimal entities is more widely supported than using hexadecimal, but I can't seem to find the source for that now though. (And there cannot be many browsers out there which does not support the hexadecimal entities.)
Note: Adding /
and '
to the list of escaped characters isn't all that useful, since they do not have any special meaning in HTML and do not need to be escaped.
escapeHtml
FunctionEDIT 2: The original function used a variable (chr
) to store the object needed for the .replace()
callback. This variable also needed an extra anonymous function to scope it, making the function (needlessly) a little bit bigger and more complex.
var escapeHtml = (function () {
'use strict';
var chr = { '"': '"', '&': '&', '<': '<', '>': '>' };
return function (text) {
return text.replace(/[\"&<>]/g, function (a) { return chr[a]; });
};
}());
I haven't tested which of the two versions are faster. If you do, feel free to add info and links about it here.
Joining elements in a list space separated:
word = ["test", "crust", "must", "fest"]
word.reverse()
joined_string = ""
for w in word:
joined_string = w + joined_string + " "
print(joined_string.rstrim())
A couple of answers that should work above but this is how i would write it.
Also, i wouldn't declare controllers inside templates. It's better to declare them on your routes imo.
add-text.tpl.html
<div ng-controller="myController">
<form ng-submit="addText(myText)">
<input type="text" placeholder="Let's Go" ng-model="myText">
<button type="submit">Add</button>
</form>
<ul>
<li ng-repeat="text in arrayText">{{ text }}</li>
</ul>
</div>
app.js
(function() {
function myController($scope) {
$scope.arrayText = ['hello', 'world'];
$scope.addText = function(myText) {
$scope.arrayText.push(myText);
};
}
angular.module('app', [])
.controller('myController', myController);
})();
Really surprised this hasn't been posted before.
strcpy(&str[idx_to_delete], &str[idx_to_delete + 1]);
Pretty efficient and simple. strcpy
uses memmove
on most implementations.
Building on the other answers, I simplified things a bit. By cloning the last element, we get the "add new" button for free (you have to change the ID to a class because of the cloning) and also reduce DOM operations. I had to use filter() instead of find() to get only the last element.
$('.js-addNew').on('click', function(e) {
e.preventDefault();
var $rows = $('.person'),
$last = $rows.filter(':last'),
$newRow = $last.clone().insertAfter($last);
$last.find($('.js-addNew')).remove(); // remove old button
$newRow.hide().find('input').val('');
$newRow.slideDown(500);
});
Use urlencode()
rather than trying to implement your own. Be lazy.
It's even easier to do without a library
window.onload = function() {
// code
};
Text decoration none was not working for me, then i found an email in outlook that did not have the line and checked the code:
<span style='font-size: 12px; font-family: "Arial","Verdana", "sans-serif"; color: black; text-decoration-line: none;'>
<a href="http://www.test.com" style='font-size: 9.0pt; color: #C69E29; text-decoration: none;'><span>www.test.com</span></a>
</span>
This one is working for me.
Normally, that is not an error per se; it is a warning that the first file it found that matches the -lPI-Http
argument to the compiler/linker is not valid. The error occurs when no other library can be found with the right content.
So, you need to look to see whether /dvlpmnt/libPI-Http.a
is a library of 32-bit object files or of 64-bit object files - it will likely be 64-bit if you are compiling with the -m32
option. Then you need to establish whether there is an alternative libPI-Http.a
or libPI-Http.so
file somewhere else that is 32-bit. If so, ensure that the directory that contains it is listed in a -L/some/where
argument to the linker. If not, then you will need to obtain or build a 32-bit version of the library from somewhere.
To establish what is in that library, you may need to do:
mkdir junk
cd junk
ar x /dvlpmnt/libPI-Http.a
file *.o
cd ..
rm -fr junk
The 'file
' step tells you what type of object files are in the archive. The rest just makes sure you don't make a mess that can't be easily cleaned up.
SimpleDateFormat.format()
method takes a Date
as a parameter. You can get a Date
from a Calendar
by calling its getTime()
method:
public static String format(GregorianCalendar calendar) {
SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy");
fmt.setCalendar(calendar);
String dateFormatted = fmt.format(calendar.getTime());
return dateFormatted;
}
Also note that the months start at 0, so you probably meant:
int month = Integer.parseInt(splitDate[1]) - 1;
You have to remove any event handlers you've set on the node before you remove it, to avoid memory leaks in IE
One the elements are added, use the rules method to add the rules
//bug fixed thanks to @Sparky
$('input[name^="fileupload"]').each(function () {
$(this).rules('add', {
required: true,
accept: "image/jpeg, image/pjpeg"
})
})
Demo: Fiddle
Update
var filenumber = 1;
$("#AddFile").click(function () { //User clicks button #AddFile
var $li = $('<li><input type="file" name="FileUpload' + filenumber + '" id="FileUpload' + filenumber + '" required=""/> <a href="#" class="RemoveFileUpload">Remove</a></li>').prependTo("#FileUploader");
$('#FileUpload' + filenumber).rules('add', {
required: true,
accept: "image/jpeg, image/pjpeg"
})
filenumber++;
return false;
});
This is a simple way to add to an array in java. I used a second array to store my original array, and then added one more element to it. After that I passed that array back to the original one.
int [] test = {12,22,33};
int [] test2= new int[test.length+1];
int m=5;int mz=0;
for ( int test3: test)
{
test2[mz]=test3; mz++;
}
test2[mz++]=m;
test=test2;
for ( int test3: test)
{
System.out.println(test3);
}
The best superuser role would be the root.The Syntax is:
use admin
db.createUser(
{
user: "root",
pwd: "password",
roles: [ "root" ]
})
For more details look at built-in roles.
Hope this helps !!!
If you're using a technology that has a minimal JDK. Here's a way without any Java libs:
double scale = 100000;
double myVal = 0.912385;
double rounded = (int)((myVal * scale) + 0.5d) / scale;
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/substr
From link:
string.substr(start[, length])
gitweb will allow you to browse through the code (and changes) via a browser.
http://git.or.cz/gitwiki/Gitweb
(Don't know if someone has already setup a public gitweb for Android, but it's probably not too hard.)
I don't know if this is accurate, but I have found that python/ruby works much better for scripts that have a lot of mathematical computations. Otherwise you have to use dc
or some other "arbitrary precision calculator". It just becomes a very big pain. With python you have much more control over floats vs ints and it is much easier to perform a lot of computations and sometimes.
In particular, I would never work with a bash script to handle binary information or bytes. Instead I would use something like python (maybe) or C++ or even Node.JS.
I'm not sure if this functionality is new, but you can also use the get_legend_handles_labels() method rather than keeping track of lines and labels yourself:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')
pi = np.pi
# fake data
time = np.linspace (0, 25, 50)
temp = 50 / np.sqrt (2 * pi * 3**2) \
* np.exp (-((time - 13)**2 / (3**2))**2) + 15
Swdown = 400 / np.sqrt (2 * pi * 3**2) * np.exp (-((time - 13)**2 / (3**2))**2)
Rn = Swdown - 10
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(time, Swdown, '-', label = 'Swdown')
ax.plot(time, Rn, '-', label = 'Rn')
ax2 = ax.twinx()
ax2.plot(time, temp, '-r', label = 'temp')
# ask matplotlib for the plotted objects and their labels
lines, labels = ax.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax2.legend(lines + lines2, labels + labels2, loc=0)
ax.grid()
ax.set_xlabel("Time (h)")
ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
ax2.set_ylabel(r"Temperature ($^\circ$C)")
ax2.set_ylim(0, 35)
ax.set_ylim(-20,100)
plt.show()
The list may contain several elements, so the get method takes an argument : the index of the element you want to retrieve. If you want the first one, then it's 0.
The list contains Car instances, so you just have to do
Car firstCar = car.get(0);
String price = firstCar.getPrice();
or just
String price = car.get(0).getPrice();
The car
variable should be named cars
, since it's a list and thus contains several cars.
Read the tutorial about collections. And learn to use the javadoc: all the classes and methods are documented.
pointer1 = pointer2
, you give pointer1 the address of pointer2.but! if you do that within a function, and you want the result to persist after the function is done, you need do some extra work. you need a new pointer3 just to point to pointer1. pass pointer3 to the function.
here is an example. look at the output below first, to understand.
#include <stdio.h>
int main()
{
int c = 1;
int d = 2;
int e = 3;
int * a = &c;
int * b = &d;
int * f = &e;
int ** pp = &a; // pointer to pointer 'a'
printf("\n a's value: %x \n", a);
printf("\n b's value: %x \n", b);
printf("\n f's value: %x \n", f);
printf("\n can we change a?, lets see \n");
printf("\n a = b \n");
a = b;
printf("\n a's value is now: %x, same as 'b'... it seems we can, but can we do it in a function? lets see... \n", a);
printf("\n cant_change(a, f); \n");
cant_change(a, f);
printf("\n a's value is now: %x, Doh! same as 'b'... that function tricked us. \n", a);
printf("\n NOW! lets see if a pointer to a pointer solution can help us... remember that 'pp' point to 'a' \n");
printf("\n change(pp, f); \n");
change(pp, f);
printf("\n a's value is now: %x, YEAH! same as 'f'... that function ROCKS!!!. \n", a);
return 0;
}
void cant_change(int * x, int * z){
x = z;
printf("\n ----> value of 'a' is: %x inside function, same as 'f', BUT will it be the same outside of this function? lets see\n", x);
}
void change(int ** x, int * z){
*x = z;
printf("\n ----> value of 'a' is: %x inside function, same as 'f', BUT will it be the same outside of this function? lets see\n", *x);
}
Here is the output: (read this first)
a's value: bf94c204
b's value: bf94c208
f's value: bf94c20c
can we change a?, lets see
a = b
a's value is now: bf94c208, same as 'b'... it seems we can, but can we do it in a function? lets see...
cant_change(a, f);
----> value of 'a' is: bf94c20c inside function, same as 'f', BUT will it be the same outside of this function? lets see
a's value is now: bf94c208, Doh! same as 'b'... that function tricked us.
NOW! lets see if a pointer to a pointer solution can help us... remember that 'pp' point to 'a'
change(pp, f);
----> value of 'a' is: bf94c20c inside function, same as 'f', BUT will it be the same outside of this function? lets see
a's value is now: bf94c20c, YEAH! same as 'f'... that function ROCKS!!!.
First of all, all the reasons are subjective. It's more like a matter of taste rather than a reason.
Personally, I find heredoc quite useless and use it occasionally, most of the time when I need to get some HTML into a variable and don't want to bother with output buffering, to form an HTML email message for example.
Formatting doesn't fit general indentation rules, but I don't think it's a big deal.
//some code at it's proper level
$this->body = <<<HERE
heredoc text sticks to the left border
but it seems OK to me.
HERE;
$this->title = "Feedback";
//and so on
As for the examples in the accepted answer, it is merely cheating.
String examples, in fact, being more concise if one won't cheat on them
$sql = "SELECT * FROM $tablename
WHERE id in [$order_ids_list]
AND product_name = 'widgets'";
$x = 'The point of the "argument" was to illustrate the use of here documents';
On Alpine Linux OS I used this, based on others answers:
svn st | grep ^? | sed 's/? *//' | xargs -I fn svn add "fn"
Change 'middle' to 'center'. Like so:
<img align="center" ....>
<select name="taskOption">
<option value="first">First</option>
<option value="second">Second</option>
<option value="third">Third</option>
</select>
$var = $_POST['taskOption'];
You have to set to element_blank()
in theme()
elements you need to remove
ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut))+
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank())
Try loading your javascript after.
Try this:
<h2>Hello World!</h2>
<p id="myParagraph">This is an example website</p>
<form>
<input type="text" id="myTextfield" placeholder="Type your name" />
<input type="submit" id="myButton" value="Go" />
</form>
<script src="js/script.js" type="text/javascript"></script>
Seems to be issue is related to DNS Server. To resolve this issue change the IP Address to ComputerName.
Example: Change the value "10.0.0.10\TestDB" to "YourcomputerName\TestDB"
i believe the following code will only run after form1
is closed
while (true)
{
if (form1.Visible == false)
form2.Show();
}
Why not start your form2
from form1
instead?
Form2 form2 = new Form2();
private void button1_Click_1(object sender, EventArgs e)
{
if (richTextBox1.Text != null)
{
form1.Visible=false;
form2.Show();
}
else MessageBox.Show("Insert Attributes First !");
}
If you want to use strings of the numbers better take another list as shown in my code it will work fine.
list1=["1","10","3","22","23","4","2","200"]
k=[]
for item in list1:
k.append(int(item))
k.sort()
print(k)
# [1, 2, 3, 4, 10, 22, 23, 200]
The easiest way is probably to create an std::bitset
representing the value, then stream that to cout
.
#include <bitset>
...
char a = -58;
std::bitset<8> x(a);
std::cout << x << '\n';
short c = -315;
std::bitset<16> y(c);
std::cout << y << '\n';
One more thing needed for my setup was to add
172.17.0.1 localhost
to /etc/hosts
so that Docker would point to 172.17.0.1
as the DB hostname, and not rely on a changing outer ip to find the DB. Hope this helps someone else with this issue!
To set the value of a Boolean attribute, such as disabled, you can specify any value. An empty string or the name of the attribute are recommended values. All that matters is that if the attribute is present at all, regardless of its actual value, its value is considered to be true. The absence of the attribute means its value is false. By setting the value of the disabled attribute to the empty string (""), we are setting disabled to true, which results in the button being disabled.
var f = document.querySelectorAll( "label.disabled input" );
for( var i = 0; i < f.length; i++ )
{
// Reference
var e = f[ i ];
// Actions
e.setAttribute( "disabled", false|null|undefined|""|0|"disabled" );
/*
<input disabled="false"|"null"|"undefined"|empty|"0"|"disabled">
e.getAttribute( "disabled" ) === "false"|"null"|"undefined"|""|"0"|"disabled"
e.disabled === true
*/
e.removeAttribute( "disabled" );
/*
<input>
e.getAttribute( "disabled" ) === null
e.disabled === false
*/
e.disabled = false|null|undefined|""|0;
/*
<input>
e.getAttribute( "disabled" ) === null|null|null|null|null
e.disabled === false
*/
e.disabled = true|" "|"disabled"|1;
/*
<input disabled>
e.getAttribute( "disabled" ) === ""|""|""|""
e.disabled === true
*/
}
Here is a simple solution:
I running the following in my project:
./gradlew --version
------------------------------------------------------------
Gradle 4.7
------------------------------------------------------------
Build time: 2018-04-18 09:09:12 UTC
Revision: b9a962bf70638332300e7f810689cb2febbd4a6c
Groovy: 2.4.12
Ant: Apache Ant(TM) version 1.9.9 compiled on February 2 2017
JVM: 1.8.0_212 (AdoptOpenJDK 25.212-b03)
OS: Mac OS X 10.15 x86_64
Next version valid for model containing arays of simple values:
function convertModelToFormData(val, formData = new FormData(), namespace = '') {
if((typeof val !== 'undefined') && (val !== null)) {
if(val instanceof Date) {
formData.append(namespace, val.toISOString());
} else if(val instanceof Array) {
for(let element of val) {
convertModelToFormData(element, formData, namespace + '[]');
}
} else if(typeof val === 'object' && !(val instanceof File)) {
for (let propertyName in val) {
if(val.hasOwnProperty(propertyName)) {
convertModelToFormData(val[propertyName], formData, namespace ? namespace + '[' + propertyName + ']' : propertyName);
}
}
} else {
formData.append(namespace, val.toString());
}
}
return formData;
}
Several of these answers suggest that at the top of a module you you do
import logging
logger = logging.getLogger(__name__)
It is my understanding that this is considered very bad practice. The reason is that the file config will disable all existing loggers by default. E.g.
#my_module
import logging
logger = logging.getLogger(__name__)
def foo():
logger.info('Hi, foo')
class Bar(object):
def bar(self):
logger.info('Hi, bar')
And in your main module :
#main
import logging
# load my module - this now configures the logger
import my_module
# This will now disable the logger in my module by default, [see the docs][1]
logging.config.fileConfig('logging.ini')
my_module.foo()
bar = my_module.Bar()
bar.bar()
Now the log specified in logging.ini will be empty, as the existing logger was disabled by fileconfig call.
While is is certainly possible to get around this (disable_existing_Loggers=False), realistically many clients of your library will not know about this behavior, and will not receive your logs. Make it easy for your clients by always calling logging.getLogger locally. Hat Tip : I learned about this behavior from Victor Lin's Website.
So good practice is instead to always call logging.getLogger locally. E.g.
#my_module
import logging
logger = logging.getLogger(__name__)
def foo():
logging.getLogger(__name__).info('Hi, foo')
class Bar(object):
def bar(self):
logging.getLogger(__name__).info('Hi, bar')
Also, if you use fileconfig in your main, set disable_existing_loggers=False, just in case your library designers use module level logger instances.
Just a clarification on the answer given by Bkkbrad.
I tried this suggestion and it did not work for me.
For example,
split('aa|bb','\\|')
produced:
["","a","a","|","b","b",""]
But,
split('aa|bb','[|]')
produced the desired result:
["aa","bb"]
Including the metacharacter '|' inside the square brackets causes it to be interpreted literally, as intended, rather than as a metacharacter.
For elaboration of this behaviour of regexp, see: http://www.regular-expressions.info/charclass.html
C arrays are not one of the supported data types for properties. See "The Objective-C Programming Language" in Xcode documentation, in the Declared Properties page:
Supported Types
You can declare a property for any Objective-C class, Core Foundation data type, or “plain old data” (POD) type (see C++ Language Note: POD Types). For constraints on using Core Foundation types, however, see “Core Foundation.”
POD does not include C arrays. See http://www.fnal.gov/docs/working-groups/fpcltf/Pkg/ISOcxx/doc/POD.html
If you need an array, you should use NSArray or NSData.
The workarounds, as I see it, are like using (void *) to circumvent type checking. You can do it, but it makes your code less maintainable.
Here's an example - we recently developed a simulation model to measure the remote transmission response time of a yet-to-be-developed system. An emulation analysis would not have given us the answer in time to upgrade the bandwidth capacity so simulation was our approach. Because we were mostly interested in determining bandwidth needs, we cared primarily about transaction size and volume, not the processing of the system. The simulation model was on a stand-alone piece of software that was designed to model discrete-event processes. To summarize in response to your question, emulation is a type of simulation. But, in this case, simulation was NOT an emulation because it didn't fully represent the new system, only the size and volume of transactions.
If your values are not completely random, but in fact may depend on something - you may compute an md5 or sha1 hash of that 'somwthing' and then truncate it to whatever length you want.
Also you may generate and truncate a guid.
It turns out that the problem really was that the address was busy - the busyness was caused by some other problems in how we are handling network communications. Your inputs have helped me figure this out. Thank you.
EDIT: to be specific, the problems in handling our network communications were that these status updates would be constantly re-sent if the first failed. It was only a matter of time until we had every distributed slave trying to send its status update at the same time, which was over-saturating our network.
The most common idiom to create a two-dimensional array with 5 rows and 10 columns is:
int[][] multD = new int[5][10];
Alternatively, you could use the following, which is more similar to what you have, though you need to explicitly initialize each row:
int[][] multD = new int[5][];
for (int i = 0; i < 5; i++) {
multD[i] = new int[10];
}
Go to installed updates and just uninstall Internet Explorer 11 Windows update. It works for me.
You can filter all characters from the string that are not printable using string.printable, like this:
>>> s = "some\x00string. with\x15 funny characters"
>>> import string
>>> printable = set(string.printable)
>>> filter(lambda x: x in printable, s)
'somestring. with funny characters'
string.printable on my machine contains:
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c
EDIT: On Python 3, filter will return an iterable. The correct way to obtain a string back would be:
''.join(filter(lambda x: x in printable, s))
As I noticed your description, you just know that your parser will give you a dictionary that its values are dictionary too like this:
sampleDict = {
"key1": {"key10": "value10", "key11": "value11"},
"key2": {"key20": "value20", "key21": "value21"}
}
So you have to iterate over your parent dictionary. If you want to print out or access all first dictionary keys in sampleDict.values()
list, you may use something like this:
for key, value in sampleDict.items():
print value.keys()[0]
If you want to just access first key of the first item in sampleDict.values()
, this may be useful:
print sampleDict.values()[0].keys()[0]
If you use the example you gave in the question, I mean:
sampleDict = {
'Apple': {'American':'16', 'Mexican':10, 'Chinese':5},
'Grapes':{'Arabian':'25','Indian':'20'}
}
The output for the first code is:
American
Indian
And the output for the second code is:
American
EDIT 1:
Above code examples does not work for version 3 and above of python; since from version 3, python changed the type of output of methods keys
and values
from list
to dict_values
. Type dict_values
is not accepting indexing, but it is iterable. So you need to change above codes as below:
First One:
for key, value in sampleDict.items():
print(list(value.keys())[0])
Second One:
print(list(list(sampleDict.values())[0].keys())[0])
import networkx as nx
import matplotlib.pyplot as plt
g = nx.DiGraph()
g.add_nodes_from([1,2,3,4,5])
g.add_edge(1,2)
g.add_edge(4,2)
g.add_edge(3,5)
g.add_edge(2,3)
g.add_edge(5,4)
nx.draw(g,with_labels=True)
plt.draw()
plt.show()
This is just simple how to draw directed graph using python 3.x using networkx. just simple representation and can be modified and colored etc. See the generated graph here.
Note: It's just a simple representation. Weighted Edges could be added like
g.add_edges_from([(1,2),(2,5)], weight=2)
and hence plotted again.
.button{
background-image:url('/image/btn.png');
background-repeat:no-repeat;
}
Even though I had gcc already installed, I had to run
sudo apt-get install build-essential
to get rid of that error
Using a list comprehension, return a 3-tuple with current, previous and next elements:
three_tuple = [(current,
my_list[idx - 1] if idx >= 1 else None,
my_list[idx + 1] if idx < len(my_list) - 1 else None) for idx, current in enumerate(my_list)]
Are you sure you will only ever need the hours and minutes? If you want to do anything meaningful with it (like for example compute time spans between two such data points) not having information about time zones and DST may give incorrect results. Time zones do maybe not apply in your case, but DST most certainly will.
I believe this should be the way this is done...
public void function(String [] array){
....
}
And the calling will be done like...
public void test(){
String[] stringArray = {"a","b","c","d","e","f","g","h","t","k","k","k","l","k"};
function(stringArray);
}
To really get this clear, here's my for-beginners answer:
You inputed the arguments in the wrong order.
A keyword argument has this style:
nullable=True, unique=False
A fixed parameter should be defined: True, False, etc. A non-keyword argument is different:
name="Ricardo", fruit="chontaduro"
This syntax error asks you to first put name="Ricardo"
and all of its kind (non-keyword) before those like nullable=True.
I had a similar problem that I resolved myself.... I think it was partially my code hogging too much memory while too many "big things"
in my application - the workbook goes out and grabs another departments "daily report".. and I extract out all the information our team needs (to minimize mistakes and data entry).
I pull in their sheets directly... but I hate the fact that they use Merged cells... which I get rid of (ie unmerge, then find the resulting blank cells, and fill with the values from above)
I made my problem go away by
a)unmerging only the "used cells" - rather than merely attempting to do entire column... ie finding the last used row in the column, and unmerging only this range (there is literally 1000s of rows on each of the sheet I grab)
b) Knowing that the undo only looks after the last ~16 events... between each "unmerge" - i put 15 events which clear out what is stored in the "undo" to minimize the amount of memory held up (ie go to some cell with data in it.. and copy// paste special value... I was GUESSING that the accumulated sum of 30sheets each with 3 columns worth of data might be taxing memory set as side for undoing
Yes it doesn't allow for any chance of an Undo... but the entire purpose is to purge the old information and pull in the new time sensitive data for analysis so it wasn't an issue
Sound corny - but my problem went away
The accepted answer was correct up until July 2011. To get the latest version, including the Service Pack you should find the latest version as described here:
For example, if you check the SP2 CTP and SP1, you'll find the latest version of SQL Server Management Studio under SP1:
Download the 32-bit (x86) or 64-bit (x64) version of the SQLManagementStudio*.exe files as appropriate and install it. You can find out whether your system is 32-bit or 64-bit by right clicking Computer, selecting Properties and looking at the System Type.
Although you could apply the service pack to the base version that results from following the accepted answer, it's easier to just download the latest version of SQL Server Management Studio and simply install it in one step.
SSLSHopper has some pretty thorough articles about moving between different servers.
http://www.sslshopper.com/how-to-move-or-copy-an-ssl-certificate-from-one-server-to-another.html
Just pick the relevant link at bottom of this page.
Note: they have an online converter which gives them access to your private key. They can probably be trusted but it would be better to use the OPENSSL command (also shown on this site) to keep the private key private on your own machine.
UPDATE: As TimK pointed out, this isn't needed with jquery 1.5.2 any more. But if you want to add custom headers or allow the use of credentials (username, password, or cookies, etc), read on.
I think I found the answer! (4 hours and a lot of cursing later)
//This does not work!!
Access-Control-Allow-Headers: *
You need to manually specify all the headers you will accept (at least that was the case for me in FF 4.0 & Chrome 10.0.648.204).
jQuery's $.ajax method sends the "x-requested-with" header for all cross domain requests (i think its only cross domain).
So the missing header needed to respond to the OPTIONS request is:
//no longer needed as of jquery 1.5.2
Access-Control-Allow-Headers: x-requested-with
If you are passing any non "simple" headers, you will need to include them in your list (i send one more):
//only need part of this for my custom header
Access-Control-Allow-Headers: x-requested-with, x-requested-by
So to put it all together, here is my PHP:
// * wont work in FF w/ Allow-Credentials
//if you dont need Allow-Credentials, * seems to work
header('Access-Control-Allow-Origin: http://www.example.com');
//if you need cookies or login etc
header('Access-Control-Allow-Credentials: true');
if ($this->getRequestMethod() == 'OPTIONS')
{
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Max-Age: 604800');
//if you need special headers
header('Access-Control-Allow-Headers: x-requested-with');
exit(0);
}
Probably the easiest way would be use this app Hosts Editor . You need to have root
As can be seen from previous posts, one can argue that if class functionality needs to be circumvented then something is wrong in the class architecture. That might be true, but one cannot always restructure or refactor the class structure on a large mature project. The various levels of change management might be one problem, but to keep existing functionality operating the same after refactoring is not always a trivial task, especially if time constraints apply. On a mature project it can be quite an undertaking to keep various regression tests from passing after a code restructure; there are often obscure "oddities" that show up. We had a similar problem in some cases inherited functionality should not execute (or should perform something else). The approach we followed below, was to put the base code that need to be excluded in a separate virtual function. This function can then be overridden in the derived class and the functionality excluded or altered. In this example "Text 2" can be prevented from output in the derived class.
public class Base
{
public virtual void Foo()
{
Console.WriteLine("Hello from Base");
}
}
public class Derived : Base
{
public override void Foo()
{
base.Foo();
Console.WriteLine("Text 1");
WriteText2Func();
Console.WriteLine("Text 3");
}
protected virtual void WriteText2Func()
{
Console.WriteLine("Text 2");
}
}
public class Special : Derived
{
public override void WriteText2Func()
{
//WriteText2Func will write nothing when
//method Foo is called from class Special.
//Also it can be modified to do something else.
}
}
You should check your designer file. Open Form1.Designer.cs and
find this line: windows Form Designer Generated Code.
Expand this and you will see a lot of code. So check Whether this line is there inside datagridview1 controls if not place it.
this.dataGridView1.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellClick);
I hope it helps.
WITH SensorTimes As (
SELECT sensorID, MAX(timestamp) "LastReading"
FROM sensorTable
GROUP BY sensorID
)
SELECT s.sensorID,s.timestamp,s.sensorField1,s.sensorField2
FROM sensorTable s
INNER JOIN SensorTimes t on s.sensorID = t.sensorID and s.timestamp = t.LastReading
This answer https://stackoverflow.com/a/33149413/6481542 got me 90% of the way with uploading large files to a development Django server, but I had to use setFixedLengthStreamingMode to make it worked. That requires setting the Content-Length before writing the content, thus requiring a fairly significant rewrite of the above answer. Here's my end result
public class MultipartLargeUtility {
private final String boundary;
private static final String LINE_FEED = "\r\n";
private HttpURLConnection httpConn;
private String charset;
private OutputStream outputStream;
private PrintWriter writer;
private final int maxBufferSize = 4096;
private long contentLength = 0;
private URL url;
private List<FormField> fields;
private List<FilePart> files;
private class FormField {
public String name;
public String value;
public FormField(String name, String value) {
this.name = name;
this.value = value;
}
}
private class FilePart {
public String fieldName;
public File uploadFile;
public FilePart(String fieldName, File uploadFile) {
this.fieldName = fieldName;
this.uploadFile = uploadFile;
}
}
/**
* This constructor initializes a new HTTP POST request with content type
* is set to multipart/form-data
*
* @param requestURL
* @param charset
* @throws IOException
*/
public MultipartLargeUtility(String requestURL, String charset, boolean requireCSRF)
throws IOException {
this.charset = charset;
// creates a unique boundary based on time stamp
boundary = "===" + System.currentTimeMillis() + "===";
url = new URL(requestURL);
fields = new ArrayList<>();
files = new ArrayList<>();
if (requireCSRF) {
getCSRF();
}
}
/**
* Adds a form field to the request
*
* @param name field name
* @param value field value
*/
public void addFormField(String name, String value)
throws UnsupportedEncodingException {
String fieldContent = "--" + boundary + LINE_FEED;
fieldContent += "Content-Disposition: form-data; name=\"" + name + "\"" + LINE_FEED;
fieldContent += "Content-Type: text/plain; charset=" + charset + LINE_FEED;
fieldContent += LINE_FEED;
fieldContent += value + LINE_FEED;
contentLength += fieldContent.getBytes(charset).length;
fields.add(new FormField(name, value));
}
/**
* Adds a upload file section to the request
*
* @param fieldName name attribute in <input type="file" name="..." />
* @param uploadFile a File to be uploaded
* @throws IOException
*/
public void addFilePart(String fieldName, File uploadFile)
throws IOException {
String fileName = uploadFile.getName();
String fieldContent = "--" + boundary + LINE_FEED;
fieldContent += "Content-Disposition: form-data; name=\"" + fieldName
+ "\"; filename=\"" + fileName + "\"" + LINE_FEED;
fieldContent += "Content-Type: "
+ URLConnection.guessContentTypeFromName(fileName) + LINE_FEED;
fieldContent += "Content-Transfer-Encoding: binary" + LINE_FEED;
fieldContent += LINE_FEED;
// file content would go here
fieldContent += LINE_FEED;
contentLength += fieldContent.getBytes(charset).length;
contentLength += uploadFile.length();
files.add(new FilePart(fieldName, uploadFile));
}
/**
* Adds a header field to the request.
*
* @param name - name of the header field
* @param value - value of the header field
*/
//public void addHeaderField(String name, String value) {
// writer.append(name + ": " + value).append(LINE_FEED);
// writer.flush();
//}
/**
* Completes the request and receives response from the server.
*
* @return a list of Strings as response in case the server returned
* status OK, otherwise an exception is thrown.
* @throws IOException
*/
public List<String> finish() throws IOException {
List<String> response = new ArrayList<String>();
String content = "--" + boundary + "--" + LINE_FEED;
contentLength += content.getBytes(charset).length;
if (!openConnection()) {
return response;
}
writeContent();
// checks server's status code first
int status = httpConn.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
response.add(line);
}
reader.close();
httpConn.disconnect();
} else {
throw new IOException("Server returned non-OK status: " + status);
}
return response;
}
private boolean getCSRF()
throws IOException {
/// First, need to get CSRF token from server
/// Use GET request to get the token
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
HttpURLConnection conn = null;
conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("GET");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.getContent();
conn.disconnect();
/// parse the returned object for the CSRF token
CookieStore cookieJar = cookieManager.getCookieStore();
List<HttpCookie> cookies = cookieJar.getCookies();
String csrf = null;
for (HttpCookie cookie : cookies) {
Log.d("cookie", "" + cookie);
if (cookie.getName().equals("csrftoken")) {
csrf = cookie.getValue();
break;
}
}
if (csrf == null) {
Log.d(TAG, "Unable to get CSRF");
return false;
}
Log.d(TAG, "Received cookie: " + csrf);
addFormField("csrfmiddlewaretoken", csrf);
return true;
}
private boolean openConnection()
throws IOException {
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);
//httpConn.setRequestProperty("Accept-Encoding", "identity");
httpConn.setFixedLengthStreamingMode(contentLength);
httpConn.setRequestProperty("Connection", "Keep-Alive");
httpConn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
outputStream = new BufferedOutputStream(httpConn.getOutputStream());
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
true);
return true;
}
private void writeContent()
throws IOException {
for (FormField field : fields) {
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"" + field.name + "\"")
.append(LINE_FEED);
writer.append("Content-Type: text/plain; charset=" + charset).append(
LINE_FEED);
writer.append(LINE_FEED);
writer.append(field.value).append(LINE_FEED);
writer.flush();
}
for (FilePart filePart : files) {
String fileName = filePart.uploadFile.getName();
writer.append("--" + boundary).append(LINE_FEED);
writer.append(
"Content-Disposition: form-data; name=\"" + filePart.fieldName
+ "\"; filename=\"" + fileName + "\"")
.append(LINE_FEED);
writer.append(
"Content-Type: "
+ URLConnection.guessContentTypeFromName(fileName))
.append(LINE_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();
FileInputStream inputStream = new FileInputStream(filePart.uploadFile);
int bufferSize = Math.min(inputStream.available(), maxBufferSize);
byte[] buffer = new byte[bufferSize];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer, 0, bufferSize)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
inputStream.close();
writer.append(LINE_FEED);
writer.flush();
}
writer.append("--" + boundary + "--").append(LINE_FEED);
writer.close();
}
}
Usage is largely the same as in the above answer, but I've included CSRF support that Django uses by default with forms
boolean useCSRF = true;
MultipartLargeUtility multipart = new MultipartLargeUtility(url, "UTF-8",useCSRF);
multipart.addFormField("param1","value");
multipart.addFilePart("filefield",new File("/path/to/file"));
List<String> response = multipart.finish();
Log.w(TAG,"SERVER REPLIED:");
for(String line : response) {
Log.w(TAG, "Upload Files Response:::" + line);
}
Personally I find
if (id in tutorTimes === false) { ... }
easier to read than
if (!(id in tutorTimes)) { ... }
but both will work.
You can use echo and prefix "\033", simple:
Artisan::command('mycommand', function () {
echo "\033======== Start ========\n";
});
And change color text:
if (App::environment() === 'production') {
echo "\033[0;33m======== WARNING ========\033[0m\n";
}
_.merge(object, [sources], [customizer], [thisArg])
_.assign(object, [sources], [customizer], [thisArg])
_.extend(object, [sources], [customizer], [thisArg])
_.defaults(object, [sources])
_.defaultsDeep(object, [sources])
_.extend
is an alias for _.assign
, so they are identicalnull
the same_.defaults
and _.defaultsDeep
processes the arguments in reverse order compared to the others (though the first argument is still the target object)_.merge
and _.defaultsDeep
will merge child objects and the others will overwrite at the root level_.assign
and _.extend
will overwrite a value with undefined
_.assign ({}, { a: 'a' }, { a: 'bb' }) // => { a: "bb" }
_.merge ({}, { a: 'a' }, { a: 'bb' }) // => { a: "bb" }
_.defaults ({}, { a: 'a' }, { a: 'bb' }) // => { a: "a" }
_.defaultsDeep({}, { a: 'a' }, { a: 'bb' }) // => { a: "a" }
_.assign
handles undefined
but the others will skip it_.assign ({}, { a: 'a' }, { a: undefined }) // => { a: undefined }
_.merge ({}, { a: 'a' }, { a: undefined }) // => { a: "a" }
_.defaults ({}, { a: undefined }, { a: 'bb' }) // => { a: "bb" }
_.defaultsDeep({}, { a: undefined }, { a: 'bb' }) // => { a: "bb" }
null
the same_.assign ({}, { a: 'a' }, { a: null }) // => { a: null }
_.merge ({}, { a: 'a' }, { a: null }) // => { a: null }
_.defaults ({}, { a: null }, { a: 'bb' }) // => { a: null }
_.defaultsDeep({}, { a: null }, { a: 'bb' }) // => { a: null }
_.merge
and _.defaultsDeep
will merge child objects_.assign ({}, {a:{a:'a'}}, {a:{b:'bb'}}) // => { "a": { "b": "bb" }}
_.merge ({}, {a:{a:'a'}}, {a:{b:'bb'}}) // => { "a": { "a": "a", "b": "bb" }}
_.defaults ({}, {a:{a:'a'}}, {a:{b:'bb'}}) // => { "a": { "a": "a" }}
_.defaultsDeep({}, {a:{a:'a'}}, {a:{b:'bb'}}) // => { "a": { "a": "a", "b": "bb" }}
_.assign ({}, {a:['a']}, {a:['bb']}) // => { "a": [ "bb" ] }
_.merge ({}, {a:['a']}, {a:['bb']}) // => { "a": [ "bb" ] }
_.defaults ({}, {a:['a']}, {a:['bb']}) // => { "a": [ "a" ] }
_.defaultsDeep({}, {a:['a']}, {a:['bb']}) // => { "a": [ "a" ] }
a={a:'a'}; _.assign (a, {b:'bb'}); // a => { a: "a", b: "bb" }
a={a:'a'}; _.merge (a, {b:'bb'}); // a => { a: "a", b: "bb" }
a={a:'a'}; _.defaults (a, {b:'bb'}); // a => { a: "a", b: "bb" }
a={a:'a'}; _.defaultsDeep(a, {b:'bb'}); // a => { a: "a", b: "bb" }
Note: As @Mistic pointed out, Lodash treats arrays as objects where the keys are the index into the array.
_.assign ([], ['a'], ['bb']) // => [ "bb" ]
_.merge ([], ['a'], ['bb']) // => [ "bb" ]
_.defaults ([], ['a'], ['bb']) // => [ "a" ]
_.defaultsDeep([], ['a'], ['bb']) // => [ "a" ]
_.assign ([], ['a','b'], ['bb']) // => [ "bb", "b" ]
_.merge ([], ['a','b'], ['bb']) // => [ "bb", "b" ]
_.defaults ([], ['a','b'], ['bb']) // => [ "a", "b" ]
_.defaultsDeep([], ['a','b'], ['bb']) // => [ "a", "b" ]