I think the solution might be this issue on GitHub:
Try add netstandard reference in web.config like this:"
<system.web> <compilation debug="true" targetFramework="4.7.1" > <assemblies> <add assembly="netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51"/> </assemblies> </compilation> <httpRuntime targetFramework="4.7.1" />
I realise you're using 4.6.1 but the choice of .NET 4.7.1 is significant as older Framework versions are not fully compatible with .NET Standard 2.0.
I know this from painful experience, when I introduced .NET Standard libraries I had a lot of issues with NUGET packages and references breaking. The other change you need to consider is upgrading to PackageReferences instead of package.config
files.
See this guide and you might also want a tool to help the upgrade. It does require a late VS 15.7 version though.
You can set up a express proxy server using http-proxy-middleware to bypass CORS:
const express = require('express');
const proxy = require('http-proxy-middleware');
const path = require('path');
const port = process.env.PORT || 8080;
const app = express();
app.use(express.static(__dirname));
app.use('/proxy', proxy({
pathRewrite: {
'^/proxy/': '/'
},
target: 'https://server.com',
secure: false
}));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'index.html'));
});
app.listen(port);
console.log('Server started');
From your react app all requests should be sent to /proxy endpoint and they will be redirected to the intended server.
const URL = `/proxy/${PATH}`;
return axios.get(URL);
Simply replace message parameter passed in clientSocket.sendto(message,(serverName, serverPort))
to clientSocket.sendto(message.encode(),(serverName, serverPort))
. Then you would successfully run in in python3
Your int length = jsonObj.length();
should be int length = ja_data.length();
I had this same error when I had a typo for one of the views while building constraints using the visual formatter. I hope that helps someone... or me again one day.
ymptom: After configuring Nexus to serve SSL maven builds fail with "peer not authenticated" or "PKIX path building failed".
This is usually caused by using a self signed SSL certificate on Nexus. Java does not consider these to be a valid certificates, and will not allow connecting to server's running them by default.
You have a few choices here to fix this:
For option 1 you can use the keytool command and follow the steps in the below article.
Explicitly Trusting a Self-Signed or Private Certificate in a Java Based Client
For option 3, invoke Maven with "-Dmaven.wagon.http.ssl.insecure=true". If the host name configured in the certificate doesn't match the host name Nexus is running on you may also need to add "-Dmaven.wagon.http.ssl.allowall=true".
Note: These additional parameters are initialized in static initializers, so they have to be passed in via the MAVEN_OPTS environment variable. Passing them on the command line to Maven will not work.
See here for more information:
You can solve that using display table.
Here is the updated JSFiddle that solves your problem.
CSS
.body {
display: table;
background-color: green;
}
.left-side {
background-color: blue;
float: none;
display: table-cell;
border: 1px solid;
}
.right-side {
background-color: red;
float: none;
display: table-cell;
border: 1px solid;
}
HTML
<div class="row body">
<div class="col-xs-9 left-side">
<p>sdfsdf</p>
<p>sdfsdf</p>
<p>sdfsdf</p>
<p>sdfsdf</p>
<p>sdfsdf</p>
<p>sdfsdf</p>
</div>
<div class="col-xs-3 right-side">
asdfdf
</div>
</div>
You can utilize a python implementation SWTloc.
Full Disclosure : I am the author of this library
To do that :-
Notice that the text_mode here is 'lb_df', which stands for Light Background Dark Foreground i.e the text in this image is going to be in darker color than the background
from swtloc import SWTLocalizer
from swtloc.utils import imgshowN, imgshow
swtl = SWTLocalizer()
# Stroke Width Transform
swtl.swttransform(imgpaths='img1.jpg', text_mode = 'lb_df',
save_results=True, save_rootpath = 'swtres/',
minrsw = 3, maxrsw = 20, max_angledev = np.pi/3)
imgshow(swtl.swtlabelled_pruned13C)
# Grouping
respacket=swtl.get_grouped(lookup_radii_multiplier=0.9, ht_ratio=3.0)
grouped_annot_bubble = respacket[2]
maskviz = respacket[4]
maskcomb = respacket[5]
# Saving the results
_=cv2.imwrite('img1_processed.jpg', swtl.swtlabelled_pruned13C)
imgshowN([maskcomb, grouped_annot_bubble], savepath='grouped_img1.jpg')
Notice that the text_mode here is 'db_lf', which stands for Dark Background Light Foreground i.e the text in this image is going to be in lighter color than the background
from swtloc import SWTLocalizer
from swtloc.utils import imgshowN, imgshow
swtl = SWTLocalizer()
# Stroke Width Transform
swtl.swttransform(imgpaths=imgpaths[1], text_mode = 'db_lf',
save_results=True, save_rootpath = 'swtres/',
minrsw = 3, maxrsw = 20, max_angledev = np.pi/3)
imgshow(swtl.swtlabelled_pruned13C)
# Grouping
respacket=swtl.get_grouped(lookup_radii_multiplier=0.9, ht_ratio=3.0)
grouped_annot_bubble = respacket[2]
maskviz = respacket[4]
maskcomb = respacket[5]
# Saving the results
_=cv2.imwrite('img1_processed.jpg', swtl.swtlabelled_pruned13C)
imgshowN([maskcomb, grouped_annot_bubble], savepath='grouped_img1.jpg')
You will also notice that the grouping done is not so accurate, to get the desired results as the images might vary, try to tune the grouping parameters in swtl.get_grouped()
function.
Try
let bytes = [65,108,105,99,101,39,115,32,65,100,118,101,110,116,117,114,101];_x000D_
_x000D_
let base64data = btoa(String.fromCharCode.apply(null, bytes));_x000D_
_x000D_
let a = document.createElement('a');_x000D_
a.href = 'data:;base64,' + base64data;_x000D_
a.download = 'binFile.txt'; _x000D_
a.click();
_x000D_
I convert here binary data to base64 (for bigger data conversion use this) - during downloading browser decode it automatically and save raw data in file. 2020.06.14 I upgrade Chrome to 83.0 and above SO snippet stop working (probably due to sandbox security restrictions) - but JSFiddle version works - here
you could also use display: table
insted of tables. Divs are way more flexible than tables.
Example:
.table {_x000D_
display: table;_x000D_
border-collapse: collapse;_x000D_
}_x000D_
_x000D_
.table .table-row {_x000D_
display: table-row;_x000D_
}_x000D_
_x000D_
.table .table-cell {_x000D_
display: table-cell;_x000D_
text-align: left;_x000D_
vertical-align: top;_x000D_
border: 1px solid black;_x000D_
}
_x000D_
<div class="table">_x000D_
<div class="table-row">_x000D_
<div class="table-cell">test</div>_x000D_
<div class="table-cell">test1123</div>_x000D_
</div>_x000D_
<div class="table-row">_x000D_
<div class="table-cell">test</div>_x000D_
<div class="table-cell">test123</div>_x000D_
</div>_x000D_
</div>
_x000D_
The error demo:
007@WIN10-711082301 MINGW64 /d/1 (dev)
$ git add --all
007@WIN10-711082301 MINGW64 /d/1 (dev)
$ git status
On branch dev
Initial commit
Changes to be committed:
(use "git rm --cached <file>..." to unstage)
new file: index.html
new file: photo.jpg
new file: style.css
007@WIN10-711082301 MINGW64 /d/1 (dev)
$ git push origin dev
error: src refspec dev does not match any.
error: failed to push some refs to '[email protected]:yourRepo.git'
You maybe not to do $ git commit -m "discription"
.
Solution:
007@WIN10-711082301 MINGW64 /d/1 (dev)
$ git commit -m "discription"
[dev (root-commit) 0950617] discription
3 files changed, 148 insertions(+)
create mode 100644 index.html
create mode 100644 photo.jpg
create mode 100644 style.css
007@WIN10-711082301 MINGW64 /d/1 (dev)
$ git push origin dev
To [email protected]:Tom007Cheung/Rookie-s-Resume.git
! [rejected] dev -> dev (fetch first)
error: failed to push some refs to '[email protected]:yourRepo.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
I too had the similar problem. But in my case, the cause of the issue was due to the presence of apostrophes (i.e. single quotation marks) within some of the text values. This is especially frequent when working with data including texts in French, e.g. «L'autre jour».
So, the solution was simply to adjust the default setting of the quote argument to exclude the «'» symbol, and thus, using quote = "\"" (i.e. double quotation mark only), everything worked fine.
I hope that can help some of you. Cheers.
Here is a list of examples for sending cookies - https://github.com/andriichuk/php-curl-cookbook#cookies
$curlHandler = curl_init();
curl_setopt_array($curlHandler, [
CURLOPT_URL => 'https://httpbin.org/cookies',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_COOKIEFILE => $cookieFile,
CURLOPT_COOKIE => 'foo=bar;baz=foo',
/**
* Or set header
* CURLOPT_HTTPHEADER => [
'Cookie: foo=bar;baz=foo',
]
*/
]);
$response = curl_exec($curlHandler);
curl_close($curlHandler);
echo $response;
@Ahmed
Below is code that specifies fields from a named range for insertion into MS Access. The nice thing about this code is that you can name your fields in Excel whatever the hell you want (If you use * then the fields have to match exactly between Excel and Access) as you can see I have named an Excel column "Haha" even though the Access column is called "dte".
Sub test()
dbWb = Application.ActiveWorkbook.FullName
dsh = "[" & Application.ActiveSheet.Name & "$]" & "Data2" 'Data2 is a named range
sdbpath = "C:\Users\myname\Desktop\Database2.mdb"
sCommand = "INSERT INTO [main] ([dte], [test1], [values], [values2]) SELECT [haha],[test1],[values],[values2] FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh
Dim dbCon As New ADODB.Connection
Dim dbCommand As New ADODB.Command
dbCon.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sdbpath & "; Jet OLEDB:Database Password=;"
dbCommand.ActiveConnection = dbCon
dbCommand.CommandText = sCommand
dbCommand.Execute
dbCon.Close
End Sub
I guess problem is in width attributes in table and td remove 'px' for example
<table border="0" cellpadding="0" cellspacing="0" width="580px" style="background-color: #0290ba;">
Should be
<table border="0" cellpadding="0" cellspacing="0" width="580" style="background-color: #0290ba;">
Try this code using Gson library and get the things done.
Gson gson = new GsonBuilder().create();
JsonObject job = gson.fromJson(JsonString, JsonObject.class);
JsonElement entry=job.getAsJsonObject("results").getAsJsonObject("map").getAsJsonArray("entry");
String str = entry.toString();
System.out.println(str);
The result returned by find is an array.
Try this instead:
console.log(user[0]["_id"]);
Another reason of this problem can be column type of "payload" sessions table. If you have huge data on session, a text column wouldn't be enough. You will need MEDIUMTEXT or even LONGTEXT.
I've found that one of our programmers added the following line to one of the imports:
os.chdir(<path_to_a_local_folder>)
This caused the Celery worker to change its working directory from the projects' default working directory (where it could find the tasks) to a different directory (where it couldn't find the tasks).
After removing this line of code, all tasks were found and registered.
if None of those works, try this
@media print {
html, body {
height:100vh;
margin: 0 !important;
padding: 0 !important;
overflow: hidden;
}
}
make sure it is 100vh
This what worked for me. set HeaderStyle-Width="5%", in the footer set textbox width Width="15",also set the width of your gridview to 100%. following is the one of the column of my gridview.
<asp:TemplateField HeaderText = "sub" HeaderStyle-ForeColor="White" HeaderStyle-Width="5%">
<ItemTemplate>
<asp:Label ID="sub" runat="server" Font-Size="small" Text='<%# Eval("sub")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_sub" runat="server" Text='<%# Eval("sub")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txt_sub" runat="server" Width="15"></asp:TextBox>
</FooterTemplate>
window.location.href = "/";
This worked for me. If you have multiple folders/directories, you can use this:
window.location.href = "/folder_name/";
Try the <wbr>
tag - not as elegant as the word-wrap
property that others suggested, but it's a working solution until all major browsers (read IE) implement CSS3.
Find extension=php_soap.dll
or extension=soap
in php.ini and remove the commenting semicolon at the beginning of the line. Eventually check for soap.ini
under the conf.d directory.
Restart your server.
Apache
sudo apt-get install php7.0-soap
sudo systemctl restart apache2
PHP5
sudo apt-get install php-soap
sudo systemctl restart apache2
Apache
sudo zypper in php7-soap
sudo systemctl restart apache2
Nginx
sudo zypper in php7-soap
sudo systemctl restart nginx
You can see Silverlight/WPF sets ellipse with hexadecimal colour for using a hex value:
your_contorl.Color = DirectCast(ColorConverter.ConvertFromString("#D8E0A627"), Color)
If you're streaming a file that you're generating dynamically, and also have a realtime server-to-client messaging library implemented, you can alert your client pretty easily.
The server-to-client messaging library I like and recommend is Socket.io (via Node.js). After your server script is done generating the file that is being streamed for download your last line in that script can emit a message to Socket.io which sends a notification to the client. On the client, Socket.io listens for incoming messages emitted from the server and allows you to act on them. The benefit of using this method over others is that you are able to detect a "true" finish event after the streaming is done.
For example, you could show your busy indicator after a download link is clicked, stream your file, emit a message to Socket.io from the server in the last line of your streaming script, listen on the client for a notification, receive the notification and update your UI by hiding the busy indicator.
I realize most people reading answers to this question might not have this type of a setup, but I've used this exact solution to great effect in my own projects and it works wonderfully.
Socket.io is incredibly easy to install and use. See more: http://socket.io/
Use Environment.NewLine
whenever you want in any string. An example:
string text = "fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@";
text = text.Replace("@", "@" + System.Environment.NewLine);
If you have a nested list where the inner lists have different types and lengths and you would like to preserve the type, e.g.,
[[1, 2], ["foo", "bar"], [3.14, "baz", 20]]
then you can use the solution proposed by @sam-mason to this question, shown below:
from argparse import ArgumentParser
import json
parser = ArgumentParser()
parser.add_argument('-l', type=json.loads)
parser.parse_args(['-l', '[[1,2],["foo","bar"],[3.14,"baz",20]]'])
which gives:
Namespace(l=[[1, 2], ['foo', 'bar'], [3.14, 'baz', 20]])
ngOnInit() {
const $ = window["$"];
$('.flexslider').flexslider({
animation: 'slide',
start: function (slider) {
$('body').removeClass('loading')
}
})
}
Use this code:
=IFERROR((This Year/Last Year)-1,IF(AND(D2=0,E2=0),0,1))
The first part of this code iferror gets rid of the N/A issues when there is a negative or a 0 value. It does this by looking at the values in e2 and d2 and makes sure they are not both 0. If they are both 0 then it will place a 0%. If only one of the cells are a 0 then it will place 100% or -100% depending on where the 0 value falls. The second part of this code (e2/d2)-1 is the same code as (this year - lastyear)/Last year
The animate(..)
function' signature is:
.animate( properties, options );
And it says the following about the parameter properties
:
properties A map of CSS properties that the animation will move toward.
text
is not a CSS property, this is why the function isn't working as you expected.
Do you want to fade the text out? Do you want to move it? I might be able to provide an alternative.
Have a look at the following fiddle.
As detailed in the Oracle Java SE Support Roadmap
After April 2015, Oracle will no longer post updates of Java SE 7 to its public download sites. Existing Java SE 7 downloads already posted as of April 2015 will remain accessible in the Java Archive
Check the Java SE 7 Archive Downloads page. The last release was update 80, therefore the 32-bit filename to download is jdk-7u80-windows-i586.exe
(64-bit is named jdk-7u80-windows-x64.exe
.
Old Java downloads also require a sign on to an Oracle account now :-( however with some crafty cookie creating one can use wget
to grab the file without signing in.
wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/7u80-b15/jdk-7u80-windows-i586.exe"
As Christian's answer with assign()
shows, there is a way to assign in the global environment. A simpler, shorter (but not better ... stick with assign) way is to use the <<-
operator, ie
a <<- "new"
inside the function.
Use dict.setdefault()
:
dic.setdefault(key,[]).append(value)
help(dict.setdefault):
setdefault(...)
D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
In this post a similar problem was discussed and solve my problem How to load a separate Application Settings file dynamically and merge with current settings? might be helpfu
tldr: there is simply no way to do that; if you are trying to do that, you get LocalDateTime wrong.
The reason is that LocalDateTime does not record Time Zone after instances are created. You cannot convert a date time without time zone to another date time based on a specific time zone.
As a matter of fact, LocalDateTime.now() should never be called in production code unless your purpose is getting random results. When you construct a LocalDateTime instance like that, this instance contains date time ONLY based on current server's time zone, which means this piece of code will generate different result if it is running a server with a different time zone config.
LocalDateTime can simplify date calculating. If you want a real universally usable data time, use ZonedDateTime or OffsetDateTime: https://docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html.
In your quesion code you are using TimeSpan.FromMinutes
incorrectly. Please see the MSDN Documentation for TimeSpan.FromMinutes, which gives the following method signature:
public static TimeSpan FromMinutes(double value)
hence, the following code won't compile
var intMinutes = TimeSpan.FromMinutes(varTime); // won't compile
Instead, you can use the TimeSpan.TotalMinutes property to perform this arithmetic. For instance:
TimeSpan varTime = (DateTime)varFinish - (DateTime)varValue;
double fractionalMinutes = varTime.TotalMinutes;
int wholeMinutes = (int)fractionalMinutes;
You can apply the below code in your repository interface class.
entityname means your database table name like projects. And List means Project is Entity class in your Projects.
@Query(value="select p from #{#entityName} p where p.id=:projectId and p.projectName=:projectName")
List<Project> findAll(@Param("projectId") int projectId, @Param("projectName") String projectName);
You can use REINDEX to do that.
Reindex does not attempt to set up the destination index. It does not copy the settings of the source index. You should set up the destination index prior to running a _reindex action, including setting up mappings, shard counts, replicas, etc.
POST /_reindex
{
"source": {
"index": "twitter"
},
"dest": {
"index": "new_twitter"
}
}
DELETE /twitter
Building on @rocksportrocker solution, It would make sense to dill when sending and RECVing the results.
import dill
import itertools
def run_dill_encoded(payload):
fun, args = dill.loads(payload)
res = fun(*args)
res = dill.dumps(res)
return res
def dill_map_async(pool, fun, args_list,
as_tuple=True,
**kw):
if as_tuple:
args_list = ((x,) for x in args_list)
it = itertools.izip(
itertools.cycle([fun]),
args_list)
it = itertools.imap(dill.dumps, it)
return pool.map_async(run_dill_encoded, it, **kw)
if __name__ == '__main__':
import multiprocessing as mp
import sys,os
p = mp.Pool(4)
res = dill_map_async(p, lambda x:[sys.stdout.write('%s\n'%os.getpid()),x][-1],
[lambda x:x+1]*10,)
res = res.get(timeout=100)
res = map(dill.loads,res)
print(res)
This is the procedure that seems simplest to me:
SharedPreferences sp = getSharedPreferences("MySharedPrefs", MODE_PRIVATE);
SharedPreferences.Editor e = sp.edit();
if (sp.getString("sharedString", null).equals("true")
|| sp.getString("sharedString", null) == null) {
e.putString("sharedString", "false").commit();
// Do something
} else {
// Do something else
}
If you are using Reactive Forms you can use this:
<button [disabled]="!contactForm.valid" type="submit" class="btn btn-lg btn primary" (click)="printSomething()">Submit</button>
If you are using Django Framework, it has such a property to cache a view or response of API's
using @cache_page(time)
and there can be other options as well.
Example:
@cache_page(60 * 15, cache="special_cache")
def my_view(request):
...
More details can be found here.
According to Javax's persistence documentation:
Whether the column is included in SQL UPDATE statements generated by the persistence provider.
It would be best to understand from the official documentation here.
I think every process you make start executing the line you create so something like this...
pid=fork() at line 6. fork function returns 2 values
you have 2 pids, first pid=0 for child and pid>0 for parent
so you can use if to separate
.
/*
sleep(int time) to see clearly
<0 fail
=0 child
>0 parent
*/
int main(int argc, char** argv) {
pid_t childpid1, childpid2;
printf("pid = process identification\n");
printf("ppid = parent process identification\n");
childpid1 = fork();
if (childpid1 == -1) {
printf("Fork error !\n");
}
if (childpid1 == 0) {
sleep(1);
printf("child[1] --> pid = %d and ppid = %d\n",
getpid(), getppid());
} else {
childpid2 = fork();
if (childpid2 == 0) {
sleep(2);
printf("child[2] --> pid = %d and ppid = %d\n",
getpid(), getppid());
} else {
sleep(3);
printf("parent --> pid = %d\n", getpid());
}
}
return 0;
}
//pid = process identification
//ppid = parent process identification
//child[1] --> pid = 2399 and ppid = 2398
//child[2] --> pid = 2400 and ppid = 2398
//parent --> pid = 2398
\n didn't work for me. the \n appear in the bodytext of the email I was sending.. this is how I resolved it.
str_pad($input, 990); //so that the spaces will pad out to the 990 cut off.
I recently used Spring Security 3.0 for this (combined with Wicket btw), and am quite happy with it. Here's a good thorough tutorial and documentation. Also take a look at this tutorial which gives a good explanation of the hashing/salting/decoding setup for Spring Security 2.
I my case, I solved this issue going to the Publish tab in the project properties and then select the Application Files button. Then just:
Note: Before you apply this solution, make sure that you have already (as I did), checked all your solution's projects and found no references to stdole.dll assembly.
1 - Located stdole.dll file;
2 - Changed its Publish status to Exclude
3 - After that you need to republish your application.
This issue happened on a Visual Studio 2012, after its migration from Visual Studio 2010.
Hope it helps.
If you really need to do this, use reverse proxy.
For example, with nginx as reverse proxy
server {
listen api.mydomain.com:80;
server_name api.mydomain.com;
location / {
proxy_pass http://127.0.0.1:8000;
}
}
If you want to use a class:
from datetime import datetime,timedelta
class MyThread():
def __init__(self, name, timeLimit):
self.name = name
self.timeLimit = timeLimit
def run(self):
# get the start time
startTime = datetime.now()
while True:
# stop if the time limit is reached :
if((datetime.now()-startTime)>self.timeLimit):
break
print('A')
mt = MyThread('aThread',timedelta(microseconds=20000))
mt.run()
The accepted answer is fine, but I'd like to add something to this as I was using IntelliJ on Mac and couldn't get it to work using the JAVA_HOME
path variable.
It turns out Java Home was different when running the application from IntelliJ.
To figure out exactly where it is, you can just do System.getProperty("java.home")
as that's where the trusted certificates are read from.
The $.getJSON()
method is shorthand that does not let you specify advanced options like that. To do that, you need to use the full $.ajax()
method.
Notice in the documentation at http://api.jquery.com/jQuery.getJSON/:
This is a shorthand Ajax function, which is equivalent to:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback
});
So just use $.ajax()
and provide all the extra parameters you need.
A new answer to an old question: in ES6 you can do shorter:
Math.max(...(x.map(el => el.length)));
Connect to your server via SSH
then connect to your mysql console
and
USE user_base
REPAIR TABLE TABLE;
If there are a lot of broken tables in current database:
mysqlcheck -uUSER -pPASSWORD --repair --extended user_base
If there are a lot of broken tables in a lot of databases:
mysqlcheck -uUSER -pPASSWORD --repair --extended -A
In Java we don't compare string as you are doing above... Here is String comparison...
if (gender.equalsIgnoreCase("Male")) {
salutation = "Mr.";
} else if (gender.equalsIgnoreCase("Female")) {
salutation = "Ms.";
}
Search Android Monitor tab bottom of android studio screen. Click on it. It will display a window and there is a tab call logcat. If you can't see Android monitor tab, click Alt+G.
This is how I finally did it! You can put a layer (full sized) over your body with high z-index and, of course hidden. You will make it visible when the window is open, make it focused on click over parent window (the layer), and finally will disappear it when the opened window is closed or submitted or whatever.
.layer
{
position: fixed;
opacity: 0.7;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
z-index: 999999;
background-color: #BEBEBE;
display: none;
cursor: not-allowed;
}
and layer in the body:
<div class="layout" id="layout"></div>
function that opens the popup window:
var new_window;
function winOpen(){
$(".layer").show();
new_window=window.open(srcurl,'','height=750,width=700,left=300,top=200');
}
keeping new window focused:
$(document).ready(function(){
$(".layout").click(function(e) {
new_window.focus();
}
});
and in the opened window:
function submit(){
var doc = window.opener.document,
doc.getElementById("layer").style.display="none";
window.close();
}
window.onbeforeunload = function(){
var doc = window.opener.document;
doc.getElementById("layout").style.display="none";
}
I hope it would help :-)
Consider
public static void main(String[] args) {
int[][] foo = new int[][] {
new int[] { 1, 2, 3 },
new int[] { 1, 2, 3, 4},
};
System.out.println(foo.length); //2
System.out.println(foo[0].length); //3
System.out.println(foo[1].length); //4
}
Column lengths differ per row. If you're backing some data by a fixed size 2D array, then provide getters to the fixed values in a wrapper class.
from datetime import datetime
startTime = datetime.now()
#do something
#Python 2:
print datetime.now() - startTime
#Python 3:
print(datetime.now() - startTime)
Casting my hat into the ring a couple years later.
Will need to save the beginning center of the image view:
var panBegin: CGPoint.zero
Then update the new center using a transform:
if recognizer.state == .began {
panBegin = imageView!.center
} else if recognizer.state == .ended {
panBegin = CGPoint.zero
} else if recognizer.state == .changed {
let translation = recognizer.translation(in: view)
let panOffsetTransform = CGAffineTransform( translationX: translation.x, y: translation.y)
imageView!.center = panBegin.applying(panOffsetTransform)
}
This is probably what you're looking for in terms of thread safety & "prettyness" when trying to consume everything in the queue:
for (YourObject obj = queue.poll(); obj != null; obj = queue.poll()) {
}
This will guarantee that you quit when the queue is empty, and that you continue to pop objects off of it as long as it's not empty.
You can't. HTTP is a stateless protocol, so you can't tell when a user has closed their browser or they are simply sitting there with an open browser window doing nothing.
That's why sessions have a timeout - you can try and reduce the timeout in order to close inactive sessions faster, but this may cause legitimate users to have their session timeout early.
I had this problem in a Backbone project: my view contains a input and is re-rendered. Here is what happens (example for a checkbox):
The solution is to update the input rather than re-render it completely. Here is an idea of the implementation:
var MyView = Backbone.View.extend({
render: function(){
if(this.rendered){
this.update();
return;
}
this.rendered = true;
this.$el.html(tpl(this.model.toJSON()));
return this;
},
update: function(){
this.$el.find('input[type="checkbox"]').prop('checked', this.model.get('checked'));
return this;
}
});
This way you don't have to change any existing code calling render(), simply make sure update() keeps your HTML in sync and you're good to go.
You need to declare timer
outside the function. Otherwise, you get a brand new variable on each function invocation.
var timer;
function endAndStartTimer() {
window.clearTimeout(timer);
//var millisecBeforeRedirect = 10000;
timer = window.setTimeout(function(){alert('Hello!');},10000);
}
Uninstall the main iPhone app, Watch app and build them again solves the problem.
Xcode 10.3
In finder navigate to: MobileDevice/Provisioning Profiles/ and delete all files there.
Then Archive and Automatically manage singing.
You are done!
You just need to include the standard.jar
file in your project build path.
I think you cannot speak of a "conversion" here. That will be a whole project. To "convert" it i think you have to write it again for the iphone.
Have a look at this question:
Is there a multiplatform framework for developing iPhone / Android applications?
As you can see from the answers there, there is no good way of developing applications for both platforms at the same time (except if you're developing games where flash makes it easy to be portable).
In case someone is still looking for this like I was, then there is a module we can use called "stack-trace". It is really popular. NPM Link
Then walk through the trace.
var stackTrace = require('stack-trace');
.
.
.
var trace = stackTrace.get();
trace.map(function (item){
console.log(new Date().toUTCString() + ' : ' + item.toString() );
});
Or just simply print the trace:
var stackTrace = require('stack-trace');
.
.
.
var trace = stackTrace.get();
trace.toString();
I know that are already many answers written for this solution however I want to show another javascript method (dependent on JQuery) in which you simply need to include ONLY a single JS File without any dependency on CSS or Gif Images in your code and that will take care of all progress bar related animations that happens during Ajax Request. You need to simnply pass javascript function like this
var objGlobalEvent = new RegisterGlobalEvents(true, "");
Here is the working fiddle for the code. https://jsfiddle.net/vibs2006/c7wukc41/3/
You can also use get_object_or_404 django shortcut. It raises a 404 error if object is not found.
I've also faced the problem of ordering of loaded scripts, which was solved through sequential loading of scripts. The loading is based on Rob W's answer.
function scriptFromFile(file) {
var script = document.createElement("script");
script.src = chrome.extension.getURL(file);
return script;
}
function scriptFromSource(source) {
var script = document.createElement("script");
script.textContent = source;
return script;
}
function inject(scripts) {
if (scripts.length === 0)
return;
var otherScripts = scripts.slice(1);
var script = scripts[0];
var onload = function() {
script.parentNode.removeChild(script);
inject(otherScripts);
};
if (script.src != "") {
script.onload = onload;
document.head.appendChild(script);
} else {
document.head.appendChild(script);
onload();
}
}
The example of usage would be:
var formulaImageUrl = chrome.extension.getURL("formula.png");
var codeImageUrl = chrome.extension.getURL("code.png");
inject([
scriptFromSource("var formulaImageUrl = '" + formulaImageUrl + "';"),
scriptFromSource("var codeImageUrl = '" + codeImageUrl + "';"),
scriptFromFile("EqEditor/eq_editor-lite-17.js"),
scriptFromFile("EqEditor/eq_config.js"),
scriptFromFile("highlight/highlight.pack.js"),
scriptFromFile("injected.js")
]);
Actually, I'm kinda new to JS, so feel free to ping me to the better ways.
If your device is plugged into your computer and your trying to changed send GPS cords Via the Emulator control, it will not work.
This is an EMULATOR control for a reason.
Just set it up to update you on GPS change.
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
ll = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
onGPSLocationChanged(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
bigInfo.setText("Changed "+ status);
}
public void onProviderEnabled(String provider) {
bigInfo.setText("Enabled "+ provider);
}
public void onProviderDisabled(String provider) {
bigInfo.setText("Disabled "+ provider);
}
};
When GPS is updated rewrite the following method to do what you want it to;
public void onGPSLocationChanged(Location location){
if(location != null){
double pLong = location.getLongitude();
double pLat = location.getLatitude();
textLat.setText(Double.toString(pLat));
textLong.setText(Double.toString(pLong));
if(autoSave){
saveGPS();
}
}
}
Dont forget to put these in the manifest
android.permission.ACCESS_FINE_LOCATION
android.permission.ACCESS_MOCK_LOCATION
driver.findElement(By.id("urid")).sendKeys("drive:\\path\\filename.extension");
This should work:
DECLARE db_cursor CURSOR FOR SELECT name, age, color FROM table;
DECLARE @myName VARCHAR(256);
DECLARE @myAge INT;
DECLARE @myFavoriteColor VARCHAR(40);
OPEN db_cursor;
FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
WHILE @@FETCH_STATUS = 0
BEGIN
--Do stuff with scalar values
FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
END;
CLOSE db_cursor;
DEALLOCATE db_cursor;
In my experience OpenCV writes a black image when SaveImage
is given a matrix with bit depth different from 8 bit. In fact, this is sort of documented:
Only 8-bit single-channel or 3-channel (with ‘BGR’ channel order) images can be saved using this function. If the format, depth or channel order is different, use
cvCvtScale
andcvCvtColor
to convert it before saving, or use universalcvSave
to save the image to XML or YAML format.
In your case you may first investigate what kind of image is captured, change capture properties (I suppose CV_CAP_PROP_CONVERT_RGB
might be important) or convert it manually afterwards.
This is an example how to convert to 8-bit representation with OpenCV. cc
here is an original matrix of type CV_32FC1
, cc8u
is its scaled version which is actually written by SaveImage
:
# I want to save cc here
cc8u = CreateMat(cc.rows, cc.cols, CV_8U)
ccmin,ccmax,minij,maxij = MinMaxLoc(cc)
ccscale, ccshift = 255.0/(ccmax-ccmin), -ccmin
CvtScale(cc, cc8u, ccscale, ccshift)
SaveImage("cc.png", cc8u)
(sorry, this is Python code, but it should be easy to translate it to C/C++)
This will work for any resolution,
button{
position:absolute;
bottom: 5%;
right:20%;
}
You can simply try this and it should work in most cases, feel free to correct me if I am wrong :
function hereLies(obj) {
if(obj.val() != "") {
//Do this here
}
}
Where obj
is the object of your textarea
.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<html>_x000D_
<body>_x000D_
<textarea placeholder="Insert text here..." rows="5" cols="12"></textarea>_x000D_
<button id="checkerx">Check</button>_x000D_
<p>Value is not null!</p>_x000D_
_x000D_
<script>_x000D_
$("p").hide();_x000D_
$("#checkerx").click(function(){_x000D_
if($("textarea").val() != ""){_x000D_
$("p").show();_x000D_
}_x000D_
else{_x000D_
$("p").replaceWith("<p>Value is null!</p>");_x000D_
}_x000D_
});_x000D_
_x000D_
</script>_x000D_
</body></html>
_x000D_
Use %in%
as follows
A$C %in% B$C
Which will tell you which values of column C of A are in B.
What is returned is a logical vector. In the specific case of your example, you get:
A$C %in% B$C
# [1] TRUE FALSE TRUE TRUE
Which you can use as an index to the rows of A
or as an index to A$C
to get the actual values:
# as a row index
A[A$C %in% B$C, ] # note the comma to indicate we are indexing rows
# as an index to A$C
A$C[A$C %in% B$C]
[1] 1 3 4 # returns all values of A$C that are in B$C
We can negate it too:
A$C[!A$C %in% B$C]
[1] 2 # returns all values of A$C that are NOT in B$C
2 %in% B$C # "is the value 2 in B$C ?"
# FALSE
A$C[2] %in% B$C # "is the 2nd element of A$C in B$C ?"
# FALSE
If you are using the requests lib:
import requests
...
params = {'tag': 'python'}
requests.get(url, params=params)
if no luck with above try to it a class or even id something like textarea.foo and then your style. or try to !important
You can use Jinja's default
:
- name: Create user
user:
name: "{{ my_variable | default('default_value') }}"
If you get the .idb
recreated again after you delete it, then read this answer.
This how it worked with me. I had the .idb
file without it's corresponding .frm
and whenever I delete the .idb
file, the database recreate it again. and I found the solution in one line in MySQL documentation (Tablespace Does Not Exist part)
1- Create a matching .frm file in some other database directory and copy it to the database directory where the orphan table is located.
2- Issue DROP TABLE for the original table. That should successfully drop the table and InnoDB should print a warning to the error log that the .ibd file was missing.
I copied another table .frm
file and name it like my missing table, then make a normal drop table query and voila, it worked and the table is dropped normally!
my system is XAMPP on windows MariaDB v 10.1.8
Too late to answer, but nevertheless.
While using CSS, to style the div (content-less), the min-height property must be set to "n"px to make the div visible (works with webkits and chrome, while not sure if this trick will work on IE6 and lower)
Code:
.shape-round{_x000D_
width: 40px;_x000D_
min-height: 40px;_x000D_
background: #FF0000;_x000D_
border-radius: 50%;_x000D_
}
_x000D_
<div class="shape-round"></div>
_x000D_
Try this:
SELECT min(salary)
FROM employee
WHERE salary IN (SELECT top 2 salary FROM employee ORDER BY salary DESC)
^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$
Matches the following
123-456-7890
(123) 456-7890
123 456 7890
123.456.7890
+91 (123) 456-7890
If you do not want a match on non-US numbers use
^(\+0?1\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$
Update :
As noticed by user Simon Weaver below, if you are also interested in matching on unformatted numbers just make the separator character class optional as [\s.-]?
^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$
This error is caused by:
Y = Dataset.iloc[:,18].values
Indexing is out of bounds here most probably because there are less than 19 columns in your Dataset, so column 18 does not exist. The following code you provided doesn't use Y at all, so you can just comment out this line for now.
Token: Token is a sequence of characters that can be treated as a single logical entity. Typical tokens are,
1) Identifiers
2) keywords
3) operators
4) special symbols
5)constants
Pattern: A set of strings in the input for which the same token is produced as output. This set of strings is described by a rule called a pattern associated with the token.
Lexeme: A lexeme is a sequence of characters in the source program that is matched by the pattern for a token.
If anybody needs to retrive specific RowDataPacket object from multiple queries, here it is.
Before you start
Important: Ensure you enable multipleStatements
in your mysql connection like so:
// Connection to MySQL
var db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '123',
database: 'TEST',
multipleStatements: true
});
Multiple Queries
Let's say we have multiple queries running:
// All Queries are here
const lastCheckedQuery = `
-- Query 1
SELECT * FROM table1
;
-- Query 2
SELECT * FROM table2;
`
;
// Run the query
db.query(lastCheckedQuery, (error, result) => {
if(error) {
// Show error
return res.status(500).send("Unexpected database error");
}
If we console.log(result)
you'll get such output:
[
[
RowDataPacket {
id: 1,
ColumnFromTable1: 'a',
}
],
[
RowDataPacket {
id: 1,
ColumnFromTable2: 'b',
}
]
]
Both results show for both tables.
Here is where basic Javascript array's come in place https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
To get data from table1
and column named ColumnFromTable1
we do
result[0][0].ColumnFromTable1 // Notice the double [0]
which gives us result of a
.
All the answers are adding some great knowledge into this very often asked question.
So going by tradition of this question's timeline, here are my 2 cents.
I found the repartition to be faster than coalesce, in very specific case.
In my application when the number of files that we estimate is lower than the certain threshold, repartition works faster.
Here is what I mean
if(numFiles > 20)
df.coalesce(numFiles).write.mode(SaveMode.Overwrite).parquet(dest)
else
df.repartition(numFiles).write.mode(SaveMode.Overwrite).parquet(dest)
In above snippet, if my files were less than 20, coalesce was taking forever to finish while repartition was much faster and so the above code.
Of course, this number (20) will depend on the number of workers and amount of data.
Hope that helps.
Instead of retrieving the file content as a single string, it can be handy to store the content as a list of all lines the file comprises:
with open('Path/to/file', 'r') as content_file:
content_list = content_file.read().strip().split("\n")
As can be seen, one needs to add the concatenated methods .strip().split("\n")
to the main answer in this thread.
Here, .strip()
just removes whitespace and newline characters at the endings of the entire file string,
and .split("\n")
produces the actual list via splitting the entire file string at every newline character \n.
Moreover, this way the entire file content can be stored in a variable, which might be desired in some cases, instead of looping over the file line by line as pointed out in this previous answer.
Below is how I got this working.
The Key point was: I needed to use the ViewModel associated with the view in order for the runtime to be able to resolve the object in the request.
[I know that that there is a way to bind an object other than the default ViewModel object but ended up simply populating the necessary properties for my needs as I could not get it to work]
[HttpPost]
public ActionResult GetDataForInvoiceNumber(MyViewModel myViewModel)
{
var invoiceNumberQueryResult = _viewModelBuilder.HydrateMyViewModelGivenInvoiceDetail(myViewModel.InvoiceNumber, myViewModel.SelectedCompanyCode);
return Json(invoiceNumberQueryResult, JsonRequestBehavior.DenyGet);
}
The JQuery script used to call this action method:
var requestData = {
InvoiceNumber: $.trim(this.value),
SelectedCompanyCode: $.trim($('#SelectedCompanyCode').val())
};
$.ajax({
url: '/en/myController/GetDataForInvoiceNumber',
type: 'POST',
data: JSON.stringify(requestData),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
CheckIfInvoiceFound(result);
},
async: true,
processData: false
});
May be below code can help:
<button type="submit" [attr.disabled]="!ngForm.valid ? true : null">Submit</button>
I stumbled across this question to my self and I feel that a forked stream has some use cases that could prove valid. I wrote the code below as a consumer so that it does not do anything but you could apply it to functions and anything else you might come across.
class PredicateSplitterConsumer<T> implements Consumer<T>
{
private Predicate<T> predicate;
private Consumer<T> positiveConsumer;
private Consumer<T> negativeConsumer;
public PredicateSplitterConsumer(Predicate<T> predicate, Consumer<T> positive, Consumer<T> negative)
{
this.predicate = predicate;
this.positiveConsumer = positive;
this.negativeConsumer = negative;
}
@Override
public void accept(T t)
{
if (predicate.test(t))
{
positiveConsumer.accept(t);
}
else
{
negativeConsumer.accept(t);
}
}
}
Now your code implementation could be something like this:
personsArray.forEach(
new PredicateSplitterConsumer<>(
person -> person.getDateOfBirth().isPresent(),
person -> System.out.println(person.getName()),
person -> System.out.println(person.getName() + " does not have Date of birth")));
Assuming TreeMap is not good for you (and assuming you can't use generics):
List sortedKeys=new ArrayList(yourMap.keySet());
Collections.sort(sortedKeys);
// Do what you need with sortedKeys.
I have Xcode 10.1 and I can not run my application on my device with 12.2 iOS version.
The easiest solution for me was:
If this trick does not working, you have to get the versions from the new Xcode version.
But you can try, saves a lot of time. Good luck!
EDIT: Or you can download your needed device support from here: https://github.com/iGhibli/iOS-DeviceSupport/tree/master/DeviceSupport
It's notable to understand that if you'd like to conditionally add attributes you can also add a dynamic declaration:
<input v-bind="attrs" />
where attrs is declared as an object:
data() {
return {
attrs: {
required: true,
type: "text"
}
}
}
Which will result in:
<input required type="text"/>
Ideal in cases with multiple attributes.
Simplistic solution:
str := fmt.Sprintf("%s", byteArray)
I'm not sure how performant this is though.
This is how I hide and show content using a class. changing the class to nothing will change the display to block, changing the class to 'a' will show the display as none.
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color:#777777;
}
block1{
display:block; background-color:black; color:white; padding:20px; margin:20px;
}
block1.a{
display:none; background-color:black; color:white; padding:20px; margin:20px;
}
</style>
</head>
<body>
<button onclick="document.getElementById('ID').setAttribute('class', '');">Open</button>
<button onclick="document.getElementById('ID').setAttribute('class', 'a');">Close</button>
<block1 id="ID" class="a">
<p>Testing</p>
</block1>
</body>
</html>
Make sure that you're using the same host in the URL that you were when you set up the mapping. E.g. if you were at http://127.0.0.1/my-app
when you set up and mapped the workspace then breakpoints won't work if you view the page via http://localhost/my-app
.
Also, thanks for reading this far. See my answer to the Chromium issue here.
Also, here is a good answer for SQL-CLR Type Mapping with a useful chart.
From that post (by David):
Note: I have verified this in the latest version of IE, and other browsers like Mozilla and Chrome and this works for me. Hope it works for others as well.
if (data == "" || data == undefined) {
alert("Falied to open PDF.");
} else { //For IE using atob convert base64 encoded data to byte array
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
var byteCharacters = atob(data);
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var blob = new Blob([byteArray], {
type: 'application/pdf'
});
window.navigator.msSaveOrOpenBlob(blob, fileName);
} else { // Directly use base 64 encoded data for rest browsers (not IE)
var base64EncodedPDF = data;
var dataURI = "data:application/pdf;base64," + base64EncodedPDF;
window.open(dataURI, '_blank');
}
}
There are several issues:
getElementsByClassName()
.Example (untested):
<script type="text/javascript">
function hideTd(className){
var elements = document.getElementsByClassName(className);
for(var i = 0, length = elements.length; i < length; i++) {
if( elements[i].textContent == ''){
elements[i].style.display = 'none';
}
}
}
</script>
</head>
<body onload="hideTd('td');">
<table border="1">
<tr>
<td class="td">not empty</td>
</tr>
<tr>
<td class="td"></td>
</tr>
<tr>
<td class="td"></td>
</tr>
</table>
</body>
Note that getElementsByClassName()
is not available up to and including IE8.
Update:
Alternatively you can give the table an ID and use:
var elements = document.getElementById('tableID').getElementsByTagName('td');
to get all td
elements.
To hide the parent row, use the parentNode
property of the element:
elements[i].parentNode.style.display = "none";
You will need something more that a http request to interact with a WCF service UNLESS your WCF service has a REST interface. Either look for a SOAP web service API that runs on android or make your service RESTful. You will need .NET 3.5 SP1 to do WCF REST services:
help(input)
shows what keyboard shortcuts produce EOF, namely, Unix: Ctrl-D, Windows: Ctrl-Z+Return:
input([prompt]) -> string
Read a string from standard input. The trailing newline is stripped. If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError. On Unix, GNU readline is used if enabled. The prompt string, if given, is printed without a trailing newline before reading.
You could reproduce it using an empty file:
$ touch empty
$ python3 -c "input()" < empty
Traceback (most recent call last):
File "<string>", line 1, in <module>
EOFError: EOF when reading a line
You could use /dev/null
or nul
(Windows) as an empty file for reading. os.devnull
shows the name that is used by your OS:
$ python3 -c "import os; print(os.devnull)"
/dev/null
Note: input()
happily accepts input from a file/pipe. You don't need stdin
to be connected to the terminal:
$ echo abc | python3 -c "print(input()[::-1])"
cba
Either handle EOFError
in your code:
try:
reply = input('Enter text')
except EOFError:
break
Or configure your editor to provide a non-empty input when it runs your script e.g., by using a customized command line if it allows it: python3 "%f" < input_file
I don't like to create a new settings/
directory. I simply add files named settings_dev.py
and settings_production.py
so I don't have to edit the BASE_DIR
.
The approach below increase the default structure instead of changing it.
mysite/ # Project
conf/
locale/
en_US/
fr_FR/
it_IT/
mysite/
__init__.py
settings.py
settings_dev.py
settings_production.py
urls.py
wsgi.py
static/
admin/
css/ # Custom back end styles
css/ # Project front end styles
fonts/
images/
js/
sass/
staticfiles/
templates/ # Project templates
includes/
footer.html
header.html
index.html
myapp/ # Application
core/
migrations/
__init__.py
templates/ # Application templates
myapp/
index.html
static/
myapp/
js/
css/
images/
__init__.py
admin.py
apps.py
forms.py
models.py
models_foo.py
models_bar.py
views.py
templatetags/ # Application with custom context processors and template tags
__init__.py
context_processors.py
templatetags/
__init__.py
templatetag_extras.py
gulpfile.js
manage.py
requirements.txt
I think this:
settings.py
settings_dev.py
settings_production.py
is better than this:
settings/__init__.py
settings/base.py
settings/dev.py
settings/production.py
This concept applies to other files as well.
I usually place node_modules/
and bower_components/
in the project directory within the default static/
folder.
Sometime a vendor/
directory for Git Submodules but usually I place them in the static/
folder.
Simplest solution and workaround:
<input name="toRent" type="radio" (click)="setToRentControl(false)">
<input name="toRent" type="radio" (click)="setToRentControl(true)">
setToRentControl(value){
this.vm.toRent.updateValue(value);
alert(value); //true/false
}
Step 1 : Delete .iml file
Step 2 : Check if your Project Directory Contain any white spaces if so then Rename your project directory leaving space
ex:
Before : My Project
After rename : MyProject
and open Android Studio...
Just define your variables in global.js outside a function scope:
// global.js
var global1 = "I'm a global!";
var global2 = "So am I!";
// other js-file
function testGlobal () {
alert(global1);
}
To make sure that this works you have to include/link to global.js before you try to access any variables defined in that file:
<html>
<head>
<!-- Include global.js first -->
<script src="/YOUR_PATH/global.js" type="text/javascript"></script>
<!-- Now we can reference variables, objects, functions etc.
defined in global.js -->
<script src="/YOUR_PATH/otherJsFile.js" type="text/javascript"></script>
</head>
[...]
</html>
You could, of course, link in the script tags just before the closing <body>-tag if you do not want the load of js-files to interrupt the initial page load.
As I used ul:not(:first-child)
is a perfect solution.
div ul:not(:first-child) {
background-color: #900;
}
Why is this a perfect because by using ul:not(:first-child)
, we can apply CSS on inner elements. Like li, img, span, a
tags etc.
But when used others solutions:
div ul + ul {
background-color: #900;
}
and
div li~li {
color: red;
}
and
ul:not(:first-of-type) {}
and
div ul:nth-child(n+2) {
background-color: #900;
}
These restrict only ul level CSS. Suppose we cannot apply CSS on li
as `div ul + ul li'.
For inner level elements the first Solution works perfectly.
div ul:not(:first-child) li{
background-color: #900;
}
and so on ...
Call me lazy but coding a Converter seems like a lot of unnecessary work. I'm using Primefaces and, not having used a plain vanilla JSF2 listbox or dropdown menu before, I just assumed (being lazy) that the widget could handle complex objects, i.e. pass the selected object as is to its corresponding getter/setter like so many other widgets do. I was disappointed to find (after hours of head scratching) that this capability does not exist for this widget type without a Converter. In fact if you supply a setter for the complex object rather than for a String, it fails silently (simply doesn't call the setter, no Exception, no JS error), and I spent a ton of time going through BalusC's excellent troubleshooting tool to find the cause, to no avail since none of those suggestions applied. My conclusion: listbox/menu widget needs adapting that other JSF2 widgets do not. This seems misleading and prone to leading the uninformed developer like myself down a rabbit hole.
In the end I resisted coding a Converter and found through trial and error that if you set the widget value to a complex object, e.g.:
<p:selectOneListbox id="adminEvents" value="#{testBean.selectedEvent}">
... when the user selects an item, the widget can call a String setter for that object, e.g. setSelectedThing(String thingString) {...}
, and the String passed is a JSON String representing the Thing object. I can parse it to determine which object was selected. This feels a little like a hack, but less of a hack than a Converter.
You can see a complete example using java 8, recursion and streams -> Dijkstra algorithm with java
function TimeHelper_GetDateAndFormat() {
var date = new Date();
return MakeValid(date.getDate()).concat(
HtmlConstants_FRONT_SLASH,
MakeValid(date.getMonth() + 1),
HtmlConstants_FRONT_SLASH,
MakeValid(date.getFullYear()),
HtmlConstants_SPACE,
MakeValid(date.getHours()),
HtmlConstants_COLON,
MakeValid(date.getMinutes()),
HtmlConstants_COLON,
MakeValid(date.getSeconds()));
}
function MakeValid(timeRegion) {
return timeRegion !== undefined && timeRegion < 10 ? ("0" + timeRegion).toString() : timeRegion.toString();
}
private const string DATE_FORMAT = "dd/MM/yyyy HH:mm:ss";
public DateTime? JavaScriptDateParse(string dateString)
{
DateTime date;
return DateTime.TryParseExact(dateString, DATE_FORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None, out date) ? date : null;
}
visibility=hidden
is very useful, but it will still take up space on the page. You can also use
display=none
because that will not only hide the object, but make it so that it doesn't take up space until it is displayed. (Also keep in mind that display's opposite is "block," not "visible")
body:before {
content: " ";
width: 100%;
height: 100%;
position: fixed;
z-index: -1;
top: 0;
left: 0;
background: rgba(0, 0, 0, 0.5);
}
I had the problem a few weeks ago with a few discrete features which were formatted as 'object'. This solution seemed to work.
for col in discrete:
df[col] = pd.to_numeric(df[col], errors='coerce').astype(pd.Int64Dtype())
You can also use RedirectMatch directive to deny access to a folder.
To deny access to a folder, you can use the following RedirectMatch in htaccess :
RedirectMatch 403 ^/folder/?$
This will forbid an external access to /folder/ eg : http://example.com/folder/ will return a 403 forbidden error.
To deny access to everything inside the folder, You can use this :
RedirectMatch 403 ^/folder/.*$
This will block access to the entire folder eg : http://example.com/folder/anyURI will return a 403 error response to client.
This declaration:
char s[] = "hello";
Creates one object - a char
array of size 6, called s
, initialised with the values 'h', 'e', 'l', 'l', 'o', '\0'
. Where this array is allocated in memory, and how long it lives for, depends on where the declaration appears. If the declaration is within a function, it will live until the end of the block that it is declared in, and almost certainly be allocated on the stack; if it's outside a function, it will probably be stored within an "initialised data segment" that is loaded from the executable file into writeable memory when the program is run.
On the other hand, this declaration:
char *s ="hello";
Creates two objects:
char
s containing the values 'h', 'e', 'l', 'l', 'o', '\0'
, which has no name and has static storage duration (meaning that it lives for the entire life of the program); ands
, which is initialised with the location of the first character in that unnamed, read-only array.The unnamed read-only array is typically located in the "text" segment of the program, which means it is loaded from disk into read-only memory, along with the code itself. The location of the s
pointer variable in memory depends on where the declaration appears (just like in the first example).
You can use javascript's document.evaluate to run an XPath expression on the DOM. I think it's supported in one way or another in browsers back to IE 6.
MDN: https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate
IE supports selectNodes instead.
MSDN: https://msdn.microsoft.com/en-us/library/ms754523(v=vs.85).aspx
There are two approaches, you can code in JScript or VBScript which do have the construct or you can fudge it in your code.
Using JScript you'd use the following type of construct:
<script language="jscript" runat="server">
try {
tryStatements
}
catch(exception) {
catchStatements
}
finally {
finallyStatements
}
</script>
In your ASP code you fudge it by using on error resume next at the point you'd have a try and checking err.Number at the point of a catch like:
<%
' Turn off error Handling
On Error Resume Next
'Code here that you want to catch errors from
' Error Handler
If Err.Number <> 0 Then
' Error Occurred - Trap it
On Error Goto 0 ' Turn error handling back on for errors in your handling block
' Code to cope with the error here
End If
On Error Goto 0 ' Reset error handling.
%>
On Android 5.0 this has changed, you have to call setElevation(0) on your action bar. Note that if you're using the support library you must call it to that like so:
getSupportActionBar().setElevation(0);
It's unaffected by the windowContentOverlay style item, so no changes to styles are required
When launching a form inside an MDIForm
form you will need to use .CenterScreen
instead of .CenterParent
.
FrmLogin f = new FrmLogin();
f.MdiParent = this;
f.StartPosition = FormStartPosition.CenterScreen;
f.Show();
If you have a width in percent, you can do this :
video {_x000D_
width: 50% !important;_x000D_
height: auto !important;_x000D_
margin: 0 auto;_x000D_
display: block;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
_x000D_
<video controls>_x000D_
<source src="http://www.nasa.gov/downloadable/videos/sciencecasts-_total_eclipse_of_the_moon.mp4" type="video/mp4">_x000D_
Your browser does not support HTML5 video._x000D_
</video>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
SELECT id, 1 AS sort_order
FROM b
UNION
SELECT id, 2 AS sort_order
FROM a
MINUS
SELECT id, 2 AS sort_order
FROM b
ORDER BY 2;
In XML
use:
android:editable="false"
As an example:
<EditText
android:id="@+id/EditText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:editable="false" />
myfun(*some_tuple)
does exactly what you request. The *
operator simply unpacks the tuple (or any iterable) and passes them as the positional arguments to the function. Read more about unpacking arguments.
I recently used ez_setup.py
as well and I did a tutorial on how to install it. The tutorial has snapshots and simple to follow. You can find it below:
Installing easy_install Using ez_setup.py
I hope you find this helpful.
condition1 = False
condition2 = False
val = -1
#here is the function getstuff is not defined, i hope you define it before
#calling it into while loop code
while condition1 and condition2 is False and val == -1:
#as you can see above , we can write that in a simplified syntax.
val,something1,something2 = getstuff()
if something1 == 10:
condition1 = True
elif something2 == 20:
# here you don't have to use "if" over and over, if have to then write "elif" instead
condition2 = True
# ihope it can be helpfull
I think this is the easy way to open a URL using this function
webbrowser.open_new_tab(url)
This should work in most cases.
SELECT * FROM myTable WHERE concat('',col1 * 1) = col1
It doesn't work for non-standard numbers like
1e4
1.2e5
123.
(trailing decimal)Here's how I would write the form and handle the getting of the checked radio.
Using a form called myForm:
<form id='myForm'>
<input type='radio' name='radio1' class='radio1' value='val1' />
<input type='radio' name='radio1' class='radio1' value='val2' />
...
</form>
Get the value from the form:
$('#myForm .radio1:checked').val();
If you're not posting the form, I would simplify it further by using:
<input type='radio' class='radio1' value='val1' />
<input type='radio' class='radio1' value='val2' />
Then getting the checked value becomes:
$('.radio1:checked').val();
Having a class name on the input allows me to easily style the inputs...
Running this on the command line should fix it
/Applications/Postgres.app/Contents/Versions/9.4/bin/createdb <Mac OSX Username Here>
What you're doing is appending a "1" (the string) to your URL. If you want page 1.html link to page 2.html you need to take the 1 out of the string, add one to it, then reassemble the string.
Why not do something like this:
var url = 'http://mywebsite.com/1.html';
var pageNum = parseInt( url.split("/").pop(),10 );
var nextPage = 'http://mywebsite.com/'+(pageNum+1)+'.html';
nextPage will contain the url http://mywebsite.com/2.html in this case. Should be easy to put in a function if needed.
Use
git cherry-pick <commit-hash>
So this will pick your behind commit to git location you are on.
If you want to use something that is more descriptive than a dumb array without resorting to using a DataSet then the following might prove useful. It still isn't strongly-typed, but at least it is checked by the compiler and will handle being refactored quite well.
Dim previousAllowUserToAddRows = dgvHistoricalInfo.AllowUserToAddRows
dgvHistoricalInfo.AllowUserToAddRows = True
Dim newTimeRecord As DataGridViewRow = dgvHistoricalInfo.Rows(dgvHistoricalInfo.NewRowIndex).Clone
With record
newTimeRecord.Cells(dgvcDate.Index).Value = .Date
newTimeRecord.Cells(dgvcHours.Index).Value = .Hours
newTimeRecord.Cells(dgvcRemarks.Index).Value = .Remarks
End With
dgvHistoricalInfo.Rows.Add(newTimeRecord)
dgvHistoricalInfo.AllowUserToAddRows = previousAllowUserToAddRows
It is worth noting that the user must have AllowUserToAddRows
permission or this won't work. That is why I store the existing value, set it to true, do my work, and then reset it to how it was.
Following are the results when we use both [MaxLength]
and [StringLength]
attributes, in EF code first
. If both are used, [MaxLength]
wins the race. See the test result in studentname
column in below class
public class Student
{
public Student () {}
[Key]
[Column(Order=1)]
public int StudentKey { get; set; }
//[MaxLength(50),StringLength(60)] //studentname column will be nvarchar(50)
//[StringLength(60)] //studentname column will be nvarchar(60)
[MaxLength(50)] //studentname column will be nvarchar(50)
public string StudentName { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; }
}
Guids are statistically unique. The odds of two different clients generating the same Guid are infinitesimally small (assuming no bugs in the Guid generating code). You may as well worry about your processor glitching due to a cosmic ray and deciding that 2+2=5 today.
Multiple threads allocating new guids will get unique values, but you should get that the function you are calling is thread safe. Which environment is this in?
Just create new package and move Classes to created package.
(default package) means that is no package.
From the answer here, spark.sql.shuffle.partitions
configures the number of partitions that are used when shuffling data for joins or aggregations.
spark.default.parallelism
is the default number of partitions in RDD
s returned by transformations like join
, reduceByKey
, and parallelize
when not set explicitly by the user. Note that spark.default.parallelism
seems to only be working for raw RDD
and is ignored when working with dataframes.
If the task you are performing is not a join or aggregation and you are working with dataframes then setting these will not have any effect. You could, however, set the number of partitions yourself by calling df.repartition(numOfPartitions)
(don't forget to assign it to a new val
) in your code.
To change the settings in your code you can simply do:
sqlContext.setConf("spark.sql.shuffle.partitions", "300")
sqlContext.setConf("spark.default.parallelism", "300")
Alternatively, you can make the change when submitting the job to a cluster with spark-submit
:
./bin/spark-submit --conf spark.sql.shuffle.partitions=300 --conf spark.default.parallelism=300
$ a=(1 2 3 4)
$ echo ${#a[@]}
4
It is worth noting that @Marius's second answer could be used as pure Javascript solution.
document.getElementById('elementId').tagName
I tried many fixes, but what worked for me was to delete a missing target listed in the build tab of the build scheme. You can get to it by opening the edit window of the current scheme.
Edit: My UI testing target was not working as well, and the solution I found was to delete it and generate it again.
Google changed how much crash reports you actually get. Previously you only got manual reported bug reports.
Since the last developer conference and the introducation of Android Vitals you also get crash reports from users which have enabled to share diagnostics data.
You'll see all crashes collected from Android devices whose users have opted in to automatically share usage and diagnostics data. Data is available for the previous two months.
Use #include <windows.h>
instead of #include <windef.h>
.
From the windows.h
wikipedia page:
There are a number of child header files that are automatically included with
windows.h
. Many of these files cannot simply be included by themselves (they are not self-contained), because of dependencies.
windef.h
is one of the files automatically included with windows.h
.
I think a solution is to put count in back ticks
.filter("`count` >= 2")
There might be a problem with your DNS servers of the ISP. A computer by default uses the ISP's DNS servers. You can manually configure your DNS servers. It is free and usually better than your ISP.
Preferred DNS server : 8.8.8.8
Alternate DNS server : 8.8.4.4
Preferred DNS server : 208.67.222.222
Alternate DNS server : 208.67.220.220
When your native query is based on joins, in that case you can get the result as list of objects and process it.
one simple example.
@Autowired
EntityManager em;
String nativeQuery = "select name,age from users where id=?";
Query query = em.createNativeQuery(nativeQuery);
query.setParameter(1,id);
List<Object[]> list = query.getResultList();
for(Object[] q1 : list){
String name = q1[0].toString();
//..
//do something more on
}
I would rather include the factory as dependencies on the controllers than inject them with their own line of code: http://jsfiddle.net/XqDxG/550/
myModule.factory('mySharedService', function($rootScope) {
return sharedService = {thing:"value"};
});
function ControllerZero($scope, mySharedService) {
$scope.thing = mySharedService.thing;
ControllerZero.$inject = ['$scope', 'mySharedService'];
checkout stetho and https://github.com/uPhyca/stetho-realm Video tutorial here: https://www.youtube.com/watch?v=9pFJz5VexRw
Either:
debugPrint("Path to realm file: " + realm.configuration.fileURL!.absoluteString)
Step 1: Have a constant called dev somewhere. Let's say Constant file
public class Constants {
public static var dev: Bool = true
}
Step 2: Create another class called RealmFunctions.swift
import RealmSwift
func realmAndPath() -> Realm {
if Constants.dev {
// location of my desktop
let testRealmURL = NSURL(fileURLWithPath: "/Users/#####/Desktop/TestRealm.realm")
return try! Realm(fileURL: testRealmURL)
} else {
return try! Realm()
}
}
Step 3: finally in your view controller:
let realm = realmAndPath()
thanks to Stewart Lynch for the original answer
SimpleDateFormat("MM-dd-yyyy");
instead of
SimpleDateFormat("mm-dd-yyyy");
because MM points Month
, mm points minutes
SimpleDateFormat sm = new SimpleDateFormat("MM-dd-yyyy");
String strDate = sm.format(myDate);
The reason the ImageView's dimentions are 0 is because when you are querying them, the view still haven't performed the layout and measure steps. You only told the view how it would "behave" in the layout, but it still didn't calculated where to put each view.
How do you decide the size to give to the image view? Can't you simply use one of the scaling options natively implemented?
-O3 option turns on more expensive optimizations, such as function inlining, in addition to all the optimizations of the lower levels ‘-O2’ and ‘-O1’. The ‘-O3’ optimization level may increase the speed of the resulting executable, but can also increase its size. Under some circumstances where these optimizations are not favorable, this option might actually make a program slower.
Your array.xml is not right. change it to like this
Here is array.xml file
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="testArray">
<item>first</item>
<item>second</item>
<item>third</item>
<item>fourth</item>
<item>fifth</item>
</string-array>
</resources>
Use toString() when you want to present information to a user (including a developer looking at a log). Never rely in your code on toString()
giving a specific value. Never test it against a specific string. If your code breaks when someone correctly changes the toString()
return, then it was already broken.
If you need to get the exact name used to declare the enum constant, you should use name() as toString
may have been overridden.
I think your best bet if you want both text field and label to hide simultaneously is assign each with a class and hide them like this:
jQuery(".labelClass, .inputClass").hide();
Angularjs $http wrap base on XMLHttpRequest. As long as at the header content set following code will do.
"Content-Type": "text/xml; charset=utf-8"
For example:
function callSoap(){
var url = "http://www.webservicex.com/stockquote.asmx";
var soapXml = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://www.webserviceX.NET/\"> "+
"<soapenv:Header/> "+
"<soapenv:Body> "+
"<web:GetQuote> "+
"<web:symbol></web:symbol> "+
"</web:GetQuote> "+
"</soapenv:Body> "+
"</soapenv:Envelope> ";
return $http({
url: url,
method: "POST",
data: soapXml,
headers: {
"Content-Type": "text/xml; charset=utf-8"
}
})
.then(callSoapComplete)
.catch(function(message){
return message;
});
function callSoapComplete(data, status, headers, config) {
// Convert to JSON Ojbect from xml
// var x2js = new X2JS();
// var str2json = x2js.xml_str2json(data.data);
// return str2json;
return data.data;
}
}
Let's start by eliminating StringTokenizer
. It is getting old and doesn't even support regular expressions. Its documentation states:
StringTokenizer
is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use thesplit
method ofString
or thejava.util.regex
package instead.
So let's throw it out right away. That leaves split()
and Scanner
. What's the difference between them?
For one thing, split()
simply returns an array, which makes it easy to use a foreach loop:
for (String token : input.split("\\s+") { ... }
Scanner
is built more like a stream:
while (myScanner.hasNext()) {
String token = myScanner.next();
...
}
or
while (myScanner.hasNextDouble()) {
double token = myScanner.nextDouble();
...
}
(It has a rather large API, so don't think that it's always restricted to such simple things.)
This stream-style interface can be useful for parsing simple text files or console input, when you don't have (or can't get) all the input before starting to parse.
Personally, the only time I can remember using Scanner
is for school projects, when I had to get user input from the command line. It makes that sort of operation easy. But if I have a String
that I want to split up, it's almost a no-brainer to go with split()
.
To solve such kind of problems I created library in swift which is called Atributika.
let str = "<r>first</r><g>second</g><b>third</b>".style(tags:
Style("r").foregroundColor(.red),
Style("g").foregroundColor(.green),
Style("b").foregroundColor(.blue)).attributedString
label.attributedText = str
You can find it here https://github.com/psharanda/Atributika
EDIT: Milhous's answer seems to be the officially supported way to do this as of 10.5. Earlier version of OS X and even 10.5 and up should still work using the following instructions though.
Open the command line (Terminal)
Navigate to your Eclipse installation folder, for instance:
cd /Applications/eclipse/
cd /Developer/Eclipse/Eclipse.app/Contents/MacOS/eclipse
cd /Applications/eclipse/Eclipse.app/Contents/MacOS/eclipse
cd /Users/<usernamehere>/eclipse/jee-neon/Eclipse.app/Contents/MacOS
Launch Eclipse: ./eclipse &
This last command will launch eclipse and immediately background the process.
Rinse and repeat to open as many unique instances of Eclipse as you want.
You might have to change the Tomcat server ports in order to run your project in different/multiple Tomcat instances, see Tomcat Server Error - Port 8080 already in use
$('#userid').change(function(){
//fire your ajax call
});
$('#userid').val(10).change();
Object doesn't support this property or method.
Think of it like if anything after the dot is called on an object. It's like a chain.
An object is a class instance. A class instance supports some properties defined in that class type definition. It exposes whatever intelli-sense in VBE tells you (there are some hidden members but it's not related to this). So after each dot .
you get intelli-sense (that white dropdown) trying to help you pick the correct action.
(you can start either way - front to back or back to front, once you understand how this works you'll be able to identify where the problem occurs)
Type this much anywhere in your code area
Dim a As Worksheets
a.
you get help from VBE, it's a little dropdown called Intelli-sense
It lists all available actions that particular object exposes to any user. You can't see the .Selection
member of the Worksheets()
class. That's what the error tells you exactly.
Object doesn't support this property or method.
If you look at the example on MSDN
Worksheets("GRA").Activate
iAreaCount = Selection.Areas.Count
It activates
the sheet first then calls the Selection...
it's not connected together because Selection
is not a member of Worksheets()
class. Simply, you can't prefix the Selection
What about
Sub DisplayColumnCount()
Dim iAreaCount As Integer
Dim i As Integer
Worksheets("GRA").Activate
iAreaCount = Selection.Areas.Count
If iAreaCount <= 1 Then
MsgBox "The selection contains " & Selection.Columns.Count & " columns."
Else
For i = 1 To iAreaCount
MsgBox "Area " & i & " of the selection contains " & _
Selection.Areas(i).Columns.Count & " columns."
Next i
End If
End Sub
from HERE
I use jupyter notebooks daily and had never experienced this issue before... until today. I had the notebook open all day but it wasn't running anything and then for no apparent reason stopped auto-saving with the '_xsrf' argument missing from POST
error message in the top right. FYI - this is a python3 notebook.
I don't know the cause of this problem but I have recently upgraded my python3 version to 3.7.2 and upgraded all of my site-packages to their latest version as of a few days ago which could possibly be the cause.
As for a solution, as suggested in the comment by @AlexK, I opened the same notebook in a new window (different browser in fact), using
jupyter notebook list
in the terminal to get the URL with login token.
This resulted in me having the notebook open and savable again but the information I had entered since the last successful auto-save was missing. Thankfully, my broken instance was still open and working apart from saving so I was able to simply copy and paste the information across then hit save. So, keep the broken instance open if you try this!
At the risk of being years late and off topic - and notwithstanding @Marc's excellent insight, in Swift it looks like:
let basename = NSURL(string: "path/to/file.ext")?.URLByDeletingPathExtension?.lastPathComponent
awk works well if you your server has it
var="text,text,text,text"
num=$(echo "${var}" | awk -F, '{print NF-1}')
echo "${num}"
combo1.DisplayMember = "Text";
combo1.ValueMember = "Value";
combo1.Items.Add(new { Text = "someText"), Value = "someValue") });
dynamic item = combo1.Items[combo1.SelectedIndex];
var itemValue = item.Value;
var itemText = item.Text;
Unfortunatly "combo1.SelectedValue" does not work, i did not want to bind my combobox with any source, so i came up with this solution. Maybe it will help someone.
Sometimes is useful to override method onBackPressed() because in case you work with fragments and you're changing between them if you push backbutton they return to the previous fragment.
var classname=$('#div1').attr('class')
As @Roko mentioned you can do this in multiple ways.
1.Using the jQuery first-child selector - SnoopCode
$(document).ready(function(){
$(".alldivs onediv:first-child").css("background-color","yellow");
}
Using jQuery eq Selector - SnoopCode
$( "body" ).find( "onediv" ).eq(1).addClass( "red" );
Using jQuery Id Selector - SnoopCode
$(document).ready(function(){
$("#div1").css("background-color: red;");
});
About all you can do is search DNS and ensure the domain that is in the email address has an MX record, other than that there is no reliable way of dealing with this.
Some servers may work with the rcpt-to method where you talk to the SMTP server, but it depends entirely on the configuration of the server. Another issue may be an overloaded server may return a 550 code saying user is unknown, but this is a temporary error, there is a permanent error (451 i think?) that can be returned. This depends entirely on the configuration of the server.
I personally would check for the DNS MX record, then send an email verification if the MX record exists.
It's been a little while since I coded with selenium, but your code looks ok to me. One thing to note is that if the element is not found, but the timeout is passed, I think the code will continue to execute. So you can do something like this:
boolean exists = driver.findElements(By.xpath("//*[@id='someID']")).size() != 0
What does the above boolean return? And are you sure selenium actually navigates to the expected page? (That may sound like a silly question but are you actually watching the pages change... selenium can be run remotely you know...)
You're making this a little more complicated than it has to be. Let's start with the end of your example:
String parameterString = "";
if ( condition ) parameterString = appendWithDelimiter( parameterString, "elementName", "," );
if ( anotherCondition ) parameterString = appendWithDelimiter( parameterString, "anotherElementName", "," );
With the small change of using a StringBuilder instead of a String, this becomes:
StringBuilder parameterString = new StringBuilder();
if (condition) parameterString.append("elementName").append(",");
if (anotherCondition) parameterString.append("anotherElementName").append(",");
...
When you're done (I assume you have to check a few other conditions as well), just make sure you remove the tailing comma with a command like this:
if (parameterString.length() > 0)
parameterString.deleteCharAt(parameterString.length() - 1);
And finally, get the string you want with
parameterString.toString();
You could also replace the "," in the second call to append with a generic delimiter string that can be set to anything. If you have a list of things you know you need to append (non-conditionally), you could put this code inside a method that takes a list of strings.
The table data on the hot standby slave server is modified while a long running query is running. A solution (PostgreSQL 9.1+) to make sure the table data is not modified is to suspend the replication and resume after the query:
select pg_xlog_replay_pause(); -- suspend
select * from foo; -- your query
select pg_xlog_replay_resume(); --resume
Just place "javascript:void(0)", in place of "#" in href tag
<a href="javascript:void(0);" onclick="callmymethod(24)">Call</a>
See https://stackoverflow.com/a/15662720/687315. As a workaround, you can listen for the afterPrint
event on the window (Firefox and IE) and listen for mouse movement on the document (indicating that the user has closed the print dialog and returned to the page) after the window.mediaMatch
API indicates that the media no longer matches "print" (Firefox and Chrome).
Keep in mind that the user may or may not have actually printed the document. Also, if you call window.print()
too often in Chrome, the user may not have even been prompted to print.
There is actually a clever way to do this that is useful for any list of tuples where the size of each tuple is 2: you can convert your list into a single dictionary.
For example,
test = [("hi", 1), ("there", 2)]
test = dict(test)
print test["hi"] # prints 1
No, but the 32-bit version runs just fine on 64-bit Windows.
Make sure the client computer has the same or higher version of the .NET framework that you built your program to.
I think I just discovered a way to apply overlapping conditions in the expected way using VBA. After hours of trying out different approaches I found that what worked was changing the "Applies to" range for the conditional format rule, after every single one was created!
This is my working example:
Sub ResetFormatting()
' ----------------------------------------------------------------------------------------
' Written by..: Julius Getz Mørk
' Purpose.....: If conditional formatting ranges are broken it might cause a huge increase
' in duplicated formatting rules that in turn will significantly slow down
' the spreadsheet.
' This macro is designed to reset all formatting rules to default.
' ----------------------------------------------------------------------------------------
On Error GoTo ErrHandler
' Make sure we are positioned in the correct sheet
WS_PROMO.Select
' Disable Events
Application.EnableEvents = False
' Delete all conditional formatting rules in sheet
Cells.FormatConditions.Delete
' CREATE ALL THE CONDITIONAL FORMATTING RULES:
' (1) Make negative values red
With Cells(1, 1).FormatConditions.add(xlCellValue, xlLess, "=0")
.Font.Color = -16776961
.StopIfTrue = False
End With
' (2) Highlight defined good margin as green values
With Cells(1, 1).FormatConditions.add(xlCellValue, xlGreater, "=CP_HIGH_MARGIN_DEFINITION")
.Font.Color = -16744448
.StopIfTrue = False
End With
' (3) Make article strategy "D" red
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""D""")
.Font.Bold = True
.Font.Color = -16776961
.StopIfTrue = False
End With
' (4) Make article strategy "A" blue
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""A""")
.Font.Bold = True
.Font.Color = -10092544
.StopIfTrue = False
End With
' (5) Make article strategy "W" green
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""W""")
.Font.Bold = True
.Font.Color = -16744448
.StopIfTrue = False
End With
' (6) Show special cost in bold green font
With Cells(1, 1).FormatConditions.add(xlCellValue, xlNotEqual, "=0")
.Font.Bold = True
.Font.Color = -16744448
.StopIfTrue = False
End With
' (7) Highlight duplicate heading names. There can be none.
With Cells(1, 1).FormatConditions.AddUniqueValues
.DupeUnique = xlDuplicate
.Font.Color = -16383844
.Interior.Color = 13551615
.StopIfTrue = False
End With
' (8) Make heading rows bold with yellow background
With Cells(1, 1).FormatConditions.add(Type:=xlExpression, Formula1:="=IF($B8=""H"";TRUE;FALSE)")
.Font.Bold = True
.Interior.Color = 13434879
.StopIfTrue = False
End With
' Modify the "Applies To" ranges
Cells.FormatConditions(1).ModifyAppliesToRange Range("O8:P507")
Cells.FormatConditions(2).ModifyAppliesToRange Range("O8:O507")
Cells.FormatConditions(3).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(4).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(5).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(6).ModifyAppliesToRange Range("E8:E507")
Cells.FormatConditions(7).ModifyAppliesToRange Range("A7:AE7")
Cells.FormatConditions(8).ModifyAppliesToRange Range("B8:L507")
ErrHandler:
Application.EnableEvents = False
End Sub
In Swift 4 You can also constrain the sequence elements to Numeric protocol to return the sum of all elements in the sequence as follow
extension Sequence where Element: Numeric {
/// Returns the sum of all elements in the collection
func sum() -> Element { return reduce(0, +) }
}
edit/update:
Xcode 10.2 • Swift 5 or later
We can simply constrain the sequence elements to the new AdditiveArithmetic protocol to return the sum of all elements in the collection
extension Sequence where Element: AdditiveArithmetic {
func sum() -> Element {
return reduce(.zero, +)
}
}
Xcode 11 • Swift 5.1 or later
extension Sequence where Element: AdditiveArithmetic {
func sum() -> Element { reduce(.zero, +) }
}
let numbers = [1,2,3]
numbers.sum() // 6
let doubles = [1.5, 2.7, 3.0]
doubles.sum() // 7.2
To sum a property of a custom object we can extend Sequence to take a predicate to return a value that conforms to AdditiveArithmetic
:
extension Sequence {
func sum<T: AdditiveArithmetic>(_ predicate: (Element) -> T) -> T { reduce(.zero) { $0 + predicate($1) } }
}
Usage:
struct Product {
let id: String
let price: Decimal
}
let products: [Product] = [.init(id: "abc", price: 21.9),
.init(id: "xyz", price: 19.7),
.init(id: "jkl", price: 2.9)
]
products.sum(\.price) // 44.5
In English:
ContentType
: When sending data to the server, use this content type. Default is application/x-www-form-urlencoded; charset=UTF-8
, which is fine for most cases.Accepts
: The content type sent in the request header that tells the server what kind of response it will accept in return. Depends on DataType
.DataType
: The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response. Can be text, xml, html, script, json, jsonp
.<html>
<head>
<meta charset="UTF-8">
<title>LoginDB</title>
</head>
<body>
<?php
$con= mysqli_connect("localhost", "root", "", "detail");
<!-- detail is the database in MySqli Database -->
if(!$con)
{
die('not connected');
}
$con= mysqli_query($con, "select * from signup");
<!-- signup is the table in the detail_Database -->
?>
<div>
<td>Login Page Database</td>
<table border="1">
<th> First Name</th>
<th>Last Name</th>
<th>UserName</th>
<th>Password</th>
<th>Gender</th>
<th>D.O.B.</th>
<th>Phone Number</th>
<th>Address</th>
</tr>
<?php
while($row= mysqli_fetch_array($con))
<!-- Fetch each row from signup Table -->
{
?>
<tr>
<td><?php echo $row['FirstName']; ?></td>
<td><?php echo $row['LastName']; ?></td>
<td><?php echo $row['Username']; ?></td>
<td><?php echo $row['Password'] ;?></td>
<td><?php echo $row['Gender'] ;?></td>
<td><?php echo $row['DOB'] ;?></td>
<td><?php echo $row['PhoneNumber'] ;?></td>
<td><?php echo $row['Address'] ;?></td>
</tr>
<?php
}
?>
</table>
</div>
</body>
</html>
Have a look at iconv()
or mb_convert_encoding()
.
Just by the way: why don't utf8_encode()
and utf8_decode()
work for you?
utf8_decode — Converts a string with ISO-8859-1 characters encoded with UTF-8 to single-byte ISO-8859-1
utf8_encode — Encodes an ISO-8859-1 string to UTF-8
So essentially
$utf8 = 'ÄÖÜ'; // file must be UTF-8 encoded
$iso88591_1 = utf8_decode($utf8);
$iso88591_2 = iconv('UTF-8', 'ISO-8859-1', $utf8);
$iso88591_2 = mb_convert_encoding($utf8, 'ISO-8859-1', 'UTF-8');
$iso88591 = 'ÄÖÜ'; // file must be ISO-8859-1 encoded
$utf8_1 = utf8_encode($iso88591);
$utf8_2 = iconv('ISO-8859-1', 'UTF-8', $iso88591);
$utf8_2 = mb_convert_encoding($iso88591, 'UTF-8', 'ISO-8859-1');
all should do the same - with utf8_en/decode()
requiring no special extension, mb_convert_encoding()
requiring ext/mbstring and iconv()
requiring ext/iconv.
On the contrary of @Thomas Eding answer:
If I forget to declare myVar
in my code, then I'll get myVar is not defined
.
Let's take a real example:
I've a variable name, but I am not sure if it is declared somewhere or not.
Then @Anurag's answer will help:
var myVariableToCheck = 'myVar';
if (window[myVariableToCheck] === undefined)
console.log("Not declared or declared, but undefined.");
// Or you can check it directly
if (window['myVar'] === undefined)
console.log("Not declared or declared, but undefined.");
Use a DataTrigger
:
<DataGrid ItemsSource="{Binding YourItemsSource}">
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Style.Triggers>
<DataTrigger Binding="{Binding State}" Value="State1">
<Setter Property="Background" Value="Red"></Setter>
</DataTrigger>
<DataTrigger Binding="{Binding State}" Value="State2">
<Setter Property="Background" Value="Green"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
</DataGrid>
import csv first and use csv.DictReader its easy to process...
A bit decent web application consists of a mix of design patterns. I'll mention only the most important ones.
The core (architectural) design pattern you'd like to use is the Model-View-Controller pattern. The Controller is to be represented by a Servlet which (in)directly creates/uses a specific Model and View based on the request. The Model is to be represented by Javabean classes. This is often further dividable in Business Model which contains the actions (behaviour) and Data Model which contains the data (information). The View is to be represented by JSP files which have direct access to the (Data) Model by EL (Expression Language).
Then, there are variations based on how actions and events are handled. The popular ones are:
Request (action) based MVC: this is the simplest to implement. The (Business) Model works directly with HttpServletRequest
and HttpServletResponse
objects. You have to gather, convert and validate the request parameters (mostly) yourself. The View can be represented by plain vanilla HTML/CSS/JS and it does not maintain state across requests. This is how among others Spring MVC, Struts and Stripes works.
Component based MVC: this is harder to implement. But you end up with a simpler model and view wherein all the "raw" Servlet API is abstracted completely away. You shouldn't have the need to gather, convert and validate the request parameters yourself. The Controller does this task and sets the gathered, converted and validated request parameters in the Model. All you need to do is to define action methods which works directly with the model properties. The View is represented by "components" in flavor of JSP taglibs or XML elements which in turn generates HTML/CSS/JS. The state of the View for the subsequent requests is maintained in the session. This is particularly helpful for server-side conversion, validation and value change events. This is how among others JSF, Wicket and Play! works.
As a side note, hobbying around with a homegrown MVC framework is a very nice learning exercise, and I do recommend it as long as you keep it for personal/private purposes. But once you go professional, then it's strongly recommended to pick an existing framework rather than reinventing your own. Learning an existing and well-developed framework takes in long term less time than developing and maintaining a robust framework yourself.
In the below detailed explanation I'll restrict myself to request based MVC since that's easier to implement.
First, the Controller part should implement the Front Controller pattern (which is a specialized kind of Mediator pattern). It should consist of only a single servlet which provides a centralized entry point of all requests. It should create the Model based on information available by the request, such as the pathinfo or servletpath, the method and/or specific parameters. The Business Model is called Action
in the below HttpServlet
example.
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
Action action = ActionFactory.getAction(request);
String view = action.execute(request, response);
if (view.equals(request.getPathInfo().substring(1)) {
request.getRequestDispatcher("/WEB-INF/" + view + ".jsp").forward(request, response);
}
else {
response.sendRedirect(view); // We'd like to fire redirect in case of a view change as result of the action (PRG pattern).
}
}
catch (Exception e) {
throw new ServletException("Executing action failed.", e);
}
}
Executing the action should return some identifier to locate the view. Simplest would be to use it as filename of the JSP. Map this servlet on a specific url-pattern
in web.xml
, e.g. /pages/*
, *.do
or even just *.html
.
In case of prefix-patterns as for example /pages/*
you could then invoke URL's like http://example.com/pages/register, http://example.com/pages/login, etc and provide /WEB-INF/register.jsp
, /WEB-INF/login.jsp
with the appropriate GET and POST actions. The parts register
, login
, etc are then available by request.getPathInfo()
as in above example.
When you're using suffix-patterns like *.do
, *.html
, etc, then you could then invoke URL's like http://example.com/register.do, http://example.com/login.do, etc and you should change the code examples in this answer (also the ActionFactory
) to extract the register
and login
parts by request.getServletPath()
instead.
The Action
should follow the Strategy pattern. It needs to be defined as an abstract/interface type which should do the work based on the passed-in arguments of the abstract method (this is the difference with the Command pattern, wherein the abstract/interface type should do the work based on the arguments which are been passed-in during the creation of the implementation).
public interface Action {
public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception;
}
You may want to make the Exception
more specific with a custom exception like ActionException
. It's just a basic kickoff example, the rest is all up to you.
Here's an example of a LoginAction
which (as its name says) logs in the user. The User
itself is in turn a Data Model. The View is aware of the presence of the User
.
public class LoginAction implements Action {
public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
String username = request.getParameter("username");
String password = request.getParameter("password");
User user = userDAO.find(username, password);
if (user != null) {
request.getSession().setAttribute("user", user); // Login user.
return "home"; // Redirect to home page.
}
else {
request.setAttribute("error", "Unknown username/password. Please retry."); // Store error message in request scope.
return "login"; // Go back to redisplay login form with error.
}
}
}
The ActionFactory
should follow the Factory method pattern. Basically, it should provide a creational method which returns a concrete implementation of an abstract/interface type. In this case, it should return an implementation of the Action
interface based on the information provided by the request. For example, the method and pathinfo (the pathinfo is the part after the context and servlet path in the request URL, excluding the query string).
public static Action getAction(HttpServletRequest request) {
return actions.get(request.getMethod() + request.getPathInfo());
}
The actions
in turn should be some static/applicationwide Map<String, Action>
which holds all known actions. It's up to you how to fill this map. Hardcoding:
actions.put("POST/register", new RegisterAction());
actions.put("POST/login", new LoginAction());
actions.put("GET/logout", new LogoutAction());
// ...
Or configurable based on a properties/XML configuration file in the classpath: (pseudo)
for (Entry entry : configuration) {
actions.put(entry.getKey(), Class.forName(entry.getValue()).newInstance());
}
Or dynamically based on a scan in the classpath for classes implementing a certain interface and/or annotation: (pseudo)
for (ClassFile classFile : classpath) {
if (classFile.isInstanceOf(Action.class)) {
actions.put(classFile.getAnnotation("mapping"), classFile.newInstance());
}
}
Keep in mind to create a "do nothing" Action
for the case there's no mapping. Let it for example return directly the request.getPathInfo().substring(1)
then.
Those were the important patterns so far.
To get a step further, you could use the Facade pattern to create a Context
class which in turn wraps the request and response objects and offers several convenience methods delegating to the request and response objects and pass that as argument into the Action#execute()
method instead. This adds an extra abstract layer to hide the raw Servlet API away. You should then basically end up with zero import javax.servlet.*
declarations in every Action
implementation. In JSF terms, this is what the FacesContext
and ExternalContext
classes are doing. You can find a concrete example in this answer.
Then there's the State pattern for the case that you'd like to add an extra abstraction layer to split the tasks of gathering the request parameters, converting them, validating them, updating the model values and execute the actions. In JSF terms, this is what the LifeCycle
is doing.
Then there's the Composite pattern for the case that you'd like to create a component based view which can be attached with the model and whose behaviour depends on the state of the request based lifecycle. In JSF terms, this is what the UIComponent
represent.
This way you can evolve bit by bit towards a component based framework.
Direct answer: No
But you can simulate reference with wrappers.
And do the following:
void changeString( _<String> str ) {
str.s("def");
}
void testRef() {
_<String> abc = new _<String>("abc");
changeString( abc );
out.println( abc ); // prints def
}
Out
void setString( _<String> ref ) {
str.s( "def" );
}
void testOut(){
_<String> abc = _<String>();
setString( abc );
out.println(abc); // prints def
}
And basically any other type such as:
_<Integer> one = new <Integer>(1);
addOneTo( one );
out.println( one ); // May print 2
My DBA asked me when I asked about the best way to store GUIDs for my objects why I needed to store 16 bytes when I could do the same thing in 4 bytes with an Integer. Since he put that challenge out there to me I thought now was a good time to mention it. That being said...
You can store a guid as a CHAR(16) binary if you want to make the most optimal use of storage space.
Easy Git has a nice page comparing actual usage of Git and SVN which will give you an idea of what things Git can do (or do more easily) compared to SVN. (Technically, this is based on Easy Git, which is a lightweight wrapper on top of Git.)
You are probably missing tesseract-ocr
from your machine. Check the installation instructions here: https://github.com/tesseract-ocr/tesseract/wiki
On a Mac, you can just install using homebrew:
brew install tesseract
It should run fine after that
There's no need to use a regular expression to dissect a URL. PHP has built-in functions for this, pathinfo() and parse_url().
That happens because you're setting the src of the ImageView
instead of the background.
Use this instead:
qImageView.setBackgroundResource(R.drawable.thumbs_down);
Here's a thread that talks about the differences between the two methods.
As mentioned here, this feature is not currently supported.
In my case, the problem turned out to be that the keyfile was behind a 301 Moved Permanently redirect, which the curl command failed to follow. I fixed it by using wget
instead:
wget URL
sudo apt-key add FILENAME
...where FILENAME is the file name that wget
outputs after it downloads the file.
Update: Alternatively, you can use curl -L
to make curl follow redirects.
As You're getting values from textfield as jTextField3.getText();
.
As it is a textField
it will return you string format as its format says:
String getText()
Returns the text contained in this TextComponent.
So, convert your String
to Integer
as:
int jml = Integer.parseInt(jTextField3.getText());
instead of directly setting
int jml = jTextField3.getText();
The directory where st.rb
lives is most likely not on your load path.
Assuming that st.rb
is located in a directory called lib
relative to where you invoke irb
, you can add that lib
directory to the list of directories that ruby uses to load classes or modules with this:
$: << 'lib'
For example, in order to call the module called 'foobar' (foobar.rb) that lives in the lib
directory, I would need to first add the lib
directory to the list of load path. Here, I am just appending the lib
directory to my load path:
irb(main):001:0> require 'foobar'
LoadError: no such file to load -- foobar
from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in `gem_original_require'
from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in `require'
from (irb):1
irb(main):002:0> $:
=> ["/usr/lib/ruby/gems/1.8/gems/spoon-0.0.1/lib", "/usr/lib/ruby/gems/1.8/gems/interactive_editor-0.0.10/lib", "/usr/lib/ruby/site_ruby/1.8", "/usr/lib/ruby/site_ruby/1.8/i386-cygwin", "/usr/lib/ruby/site_ruby", "/usr/lib/ruby/vendor_ruby/1.8", "/usr/lib/ruby/vendor_ruby/1.8/i386-cygwin", "/usr/lib/ruby/vendor_ruby", "/usr/lib/ruby/1.8", "/usr/lib/ruby/1.8/i386-cygwin", "."]
irb(main):004:0> $: << 'lib'
=> ["/usr/lib/ruby/gems/1.8/gems/spoon-0.0.1/lib", "/usr/lib/ruby/gems/1.8/gems/interactive_editor-0.0.10/lib", "/usr/lib/ruby/site_ruby/1.8", "/usr/lib/ruby/site_ruby/1.8/i386-cygwin", "/usr/lib/ruby/site_ruby", "/usr/lib/ruby/vendor_ruby/1.8", "/usr/lib/ruby/vendor_ruby/1.8/i386-cygwin", "/usr/lib/ruby/vendor_ruby", "/usr/lib/ruby/1.8", "/usr/lib/ruby/1.8/i386-cygwin", ".", "lib"]
irb(main):005:0> require 'foobar'
=> true
EDIT
Sorry, I completely missed the fact that you are using ruby 1.9.x. All accounts report that your current working directory has been removed from LOAD_PATH
for security reasons, so you will have to do something like in irb
:
$: << "."
Some of the problems:
for i in range[6]:
for j in range[6]:
should be:
range(6)
For changing the Title of a form at runtime we can code as below
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
this.Text = "This Is My Title";
}
}
A simpler way to think about it, perhaps: when main returns, your process will not exit if there are non-daemon threads still running.
A bit of advice: Clean shutdown is easy to get wrong when threads and synchronization are involved - if you can avoid it, do so. Use daemon threads whenever possible.
This worked for me. adding two dots and slash.
body{
background: url(../images/yourimage.png);
}
A very simple method is to use apkanalyzer.
apkanalyzer manifest application-id "${_path_to_apk}"
For Laravel 5.5 or above just use the built in helper
$timestamp = now();
If you want a unix timestamp, you can also try this:
$unix_timestamp = now()->timestamp;
This worked for me:
$(window).scroll(function() {
buffer = 40 // # of pixels from bottom of scroll to fire your function. Can be 0
if ($(".myDiv").prop('scrollHeight') - $(".myDiv").scrollTop() <= $(".myDiv").height() + buffer ) {
doThing();
}
});
Must use jQuery 1.6 or higher
A call to EntityManager.flush();
will force the data to be persist in the database immediately as EntityManager.persist()
will not (depending on how the EntityManager is configured : FlushModeType (AUTO or COMMIT) by default it's set to AUTO and a flush will be done automatically by if it's set to COMMIT the persitence of the data to the underlying database will be delayed when the transaction is commited).
I use this command:
mount -o rw,remount /system
You can use the following function:
DESCRIBE TABLE <itab-Name> LINES <variable>
After the call, variable contains the number of rows of the internal table .
There are a few alternate ways to figure out the currently used python in Linux is:
which python
command.command -v python
commandtype python
commandSimilarly On Windows with Cygwin will also result the same.
kuvivek@HOSTNAME ~
$ which python
/usr/bin/python
kuvivek@HOSTNAME ~
$ whereis python
python: /usr/bin/python /usr/bin/python3.4 /usr/lib/python2.7 /usr/lib/python3.4 /usr/include/python2.7 /usr/include/python3.4m /usr/share/man/man1/python.1.gz
kuvivek@HOSTNAME ~
$ which python3
/usr/bin/python3
kuvivek@HOSTNAME ~
$ command -v python
/usr/bin/python
kuvivek@HOSTNAME ~
$ type python
python is hashed (/usr/bin/python)
If you are already in the python shell. Try anyone of these. Note: This is an alternate way. Not the best pythonic way.
>>> import os
>>> os.popen('which python').read()
'/usr/bin/python\n'
>>>
>>> os.popen('type python').read()
'python is /usr/bin/python\n'
>>>
>>> os.popen('command -v python').read()
'/usr/bin/python\n'
>>>
>>>
If you are not sure of the actual path of the python command and is available in your system, Use the following command.
pi@osboxes:~ $ which python
/usr/bin/python
pi@osboxes:~ $ readlink -f $(which python)
/usr/bin/python2.7
pi@osboxes:~ $
pi@osboxes:~ $ which python3
/usr/bin/python3
pi@osboxes:~ $
pi@osboxes:~ $ readlink -f $(which python3)
/usr/bin/python3.7
pi@osboxes:~ $
try to use this one.
$(document).ready(function(){
$.ajax({
url: "yourPageWhereToLoadData.php",
success: function(data){
$("#dialog").html(data);
}
});
$("#dialog").dialog(
{
bgiframe: true,
autoOpen: false,
height: 100,
modal: true
}
);
});
This is work for me: Drwable->New->Drawable Resource File->create xml file
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#e0e0e0" />
<stroke android:width="2dp" android:color="#a4b0ba" />
</shape>
Database first and model first has no real differences. Generated code are the same and you can combine this approaches. For example, you can create database using designer, than you can alter database using sql script and update your model.
When you using code first you can't alter model without recreation database and losing all data. IMHO, this limitation is very strict and does not allow to use code first in production. For now it is not truly usable.
Second minor disadvantage of code first is that model builder require privileges on master database. This doesn't affect you if you using SQL Server Compact database or if you control database server.
Advantage of code first is very clean and simple code. You have full control of this code and can easily modify and use it as your view model.
I can recommend to use code first approach when you creating simple standalone application without versioning and using model\database first in projects that requires modification in production.
d= {'george':16,'amber':19}
dict((v,k) for k,v in d.items()).get(16)
The output is as follows:
-> prints george
The right way to do it:
In .NET Core you can inject the IConfiguration
as a parameter into your Class constructor, and it will be available.
public class MyClass
{
private IConfiguration configuration;
public MyClass(IConfiguration configuration)
{
ConnectionString = new configuration.GetValue<string>("ConnectionString");
}
Now, when you want to create an instance of your class, since your class gets injected the IConfiguration
, you won't be able to just do new MyClass()
, because it needs a IConfiguration
parameter injected into the constructor, so, you will need to inject your class as well to the injecting chain, which means two simple steps:
1) Add your Class/es - where you want to use the IConfiguration
, to the IServiceCollection
at the ConfigureServices()
method in Startup.cs
services.AddTransient<MyClass>();
2) Define an instance - let's say in the Controller
, and inject it using the constructor:
public class MyController : ControllerBase
{
private MyClass _myClass;
public MyController(MyClass myClass)
{
_myClass = myClass;
}
Now you should be able to enjoy your _myClass.configuration
freely...
Another option:
If you are still looking for a way to have it available without having to inject the classes into the controller, then you can store it in a static class
, which you will configure in the Startup.cs
, something like:
public static class MyAppData
{
public static IConfiguration Configuration;
}
And your Startup
constructor should look like this:
public Startup(IConfiguration configuration)
{
Configuration = configuration;
MyAppData.Configuration = configuration;
}
Then use MyAppData.Configuration
anywhere in your program.
Don't confront me why the first option is the right way, I can just see experienced developers always avoid garbage data along their way, and it's well understood that it's not the best practice to have loads of data available in memory all the time, neither is it good for performance and nor for development, and perhaps it's also more secure to only have with you what you need.
case 'users.online' || 'users.location' || ...
is exactly the same as:
case True:
and that case
will be chosen for any value of $p
, unless $p
is the empty string.
||
Does not have any special meaning inside a case
statement, you are not comparing $p
to each of those strings, you are just checking to see if it's not False
.
JsonPath jsonPathEvaluator = response.jsonPath();
return jsonPathEvaluator.get("user_id").toString();
You did not need
Options Indexes FollowSymLinks MultiViews Includes ExecCGI
AllowOverride All
Order Allow,Deny
Allow from all
Require all granted
the only thing what you need is...
Require all granted
...inside the directory section.
See Apache 2.4 upgrading side:
void main ()
{
int temp,integer,count=0,i,cnd=0;
char ascii[10]={0};
printf("enter a number");
scanf("%d",&integer);
if(integer>>31)
{
/*CONVERTING 2's complement value to normal value*/
integer=~integer+1;
for(temp=integer;temp!=0;temp/=10,count++);
ascii[0]=0x2D;
count++;
cnd=1;
}
else
for(temp=integer;temp!=0;temp/=10,count++);
for(i=count-1,temp=integer;i>=cnd;i--)
{
ascii[i]=(temp%10)+0x30;
temp/=10;
}
printf("\n count =%d ascii=%s ",count,ascii);
}
To get largest size of the image
https://graph.facebook.com/{userID}?fields=picture.width(720).height(720)
or anything else you need as size. Based on experience, type=large is not the largest result you can obtain.
You can use the css property object-fit
.
.cover {_x000D_
object-fit: cover;_x000D_
width: 50px;_x000D_
height: 100px;_x000D_
}
_x000D_
<img src="http://i.stack.imgur.com/2OrtT.jpg" class="cover" width="242" height="363" />
_x000D_
There's a polyfill for IE: https://github.com/anselmh/object-fit
Found an article titled "MYSQL WITH NOLOCK"
https://web.archive.org/web/20100814144042/http://sqldba.org/articles/22-mysql-with-nolock.aspx
in MS SQL Server you would do the following:
SELECT * FROM TABLE_NAME WITH (nolock)
and the MYSQL equivalent is
SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ;
SELECT * FROM TABLE_NAME ;
SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ ;
EDIT
Michael Mior suggested the following (from the comments)
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ;
SELECT * FROM TABLE_NAME ;
COMMIT ;
You are looking for np.matmul(X, y)
. In Python 3.5+ you can use X @ y
.
I am try to convert Object type variable into string using this line of code
try this to convert object value to string:
Java Code
Object dataobject=value;
//convert object into String
String convert= String.valueOf(dataobject);
Using keyword arguments is the same thing as normal arguments except order doesn't matter. For example the two functions calls below are the same:
def foo(bar, baz):
pass
foo(1, 2)
foo(baz=2, bar=1)
To check a remote SSH server prior to the first connection, you can give a look at www.server-stats.net/ssh/ to see all SHH keys for the server, as well as from when the key is known.
That's not like an SSL certificate, but definitely a must-do before connecting to any SSH server for the first time.
What is the difference between web service and WCF?
Web service use only HTTP protocol while transferring data from one application to other application.
But WCF supports more protocols for transporting messages than ASP.NET Web services. WCF supports sending messages by using HTTP, as well as the Transmission Control Protocol (TCP), named pipes, and Microsoft Message Queuing (MSMQ).
To develop a service in Web Service, we will write the following code
[WebService]
public class Service : System.Web.Services.WebService
{
[WebMethod]
public string Test(string strMsg)
{
return strMsg;
}
}
To develop a service in WCF, we will write the following code
[ServiceContract]
public interface ITest
{
[OperationContract]
string ShowMessage(string strMsg);
}
public class Service : ITest
{
public string ShowMessage(string strMsg)
{
return strMsg;
}
}
Web Service is not architecturally more robust. But WCF is architecturally more robust and promotes best practices.
Web Services use XmlSerializer but WCF uses DataContractSerializer. Which is better in performance as compared to XmlSerializer?
For internal (behind firewall) service-to-service calls we use the net:tcp binding, which is much faster than SOAP.
WCF is 25%—50% faster than ASP.NET Web Services, and approximately 25% faster than .NET Remoting.
When would I opt for one over the other?
WCF is used to communicate between other applications which has been developed on other platforms and using other Technology.
For example, if I have to transfer data from .net platform to other application which is running on other OS (like Unix or Linux) and they are using other transfer protocol (like WAS, or TCP) Then it is only possible to transfer data using WCF.
Here is no restriction of platform, transfer protocol of application while transferring the data between one application to other application.
Security is very high as compare to web service
The problem is the TypeError
gets raised 'before' assertRaises
gets called since the arguments to assertRaises
need to be evaluated before the method can be called. You need to pass a lambda
expression like:
self.assertRaises(TypeError, lambda: self.testListNone[:1])
import * as fs from 'fs';
import * as path from 'path';
fs.readFile(path.join(__dirname, "filename.txt"), (err, data) => {
if (err) throw err;
console.log(data);
})
EDIT:
consider the project structure:
../readfile/
+-- filename.txt
+-- src
+-- index.js
+-- index.ts
consider the index.ts
:
import * as fs from 'fs';
import * as path from 'path';
function lookFilesInDirectory(path_directory) {
fs.stat(path_directory, (err, stat) => {
if (!err) {
if (stat.isDirectory()) {
console.log(path_directory)
fs.readdirSync(path_directory).forEach(file => {
console.log(`\t${file}`);
});
console.log();
}
}
});
}
let path_view = './';
lookFilesInDirectory(path_view);
lookFilesInDirectory(path.join(__dirname, path_view));
if you have in the readfile folder and run tsc src/index.ts && node src/index.js
, the output will be:
./
filename.txt
src
/home/andrei/scripts/readfile/src/
index.js
index.ts
that is, it depends on where you run the node.
the __dirname is directory name of the current module.
I'm a bit late to the party, but bumped in to this issue whilst working with the openidc auth module.
I ended up noticing that cookies were not being cleared properly, and I had at least 10 mod_auth_openidc_state_... cookies, all of which would be sent by my browser whenever I made a request.
If this sounds familiar to you, double check your cookies!