However, avpicture_get_size is defined.
No, as the header (<libavcodec/avcodec.h>
) just declares it.
The definition is in the library itself.
So you might like to add the linker option to link libavcodec
when invoking gcc:
-lavcodec
Please also note that libraries need to be specified on the command line after the files needing them:
gcc -I$HOME/ffmpeg/include program.c -lavcodec
Not like this:
gcc -lavcodec -I$HOME/ffmpeg/include program.c
Referring to Wyzard's comment, the complete command might look like this:
gcc -I$HOME/ffmpeg/include program.c -L$HOME/ffmpeg/lib -lavcodec
For libraries not stored in the linkers standard location the option -L
specifies an additional search path to lookup libraries specified using the -l
option, that is libavcodec.x.y.z
in this case.
For a detailed reference on GCC's linker option, please read here.
There can be multiple root causes for this exception. For me, my mockMvc wasn't getting auto-configured. I solved this exception by using @WebMvcTest(MyController.class)
at the class level. This annotation will disable full auto-configuration and instead apply only configuration relevant to MVC tests.
An alternative to this is, If you are looking to load your full application configuration and use MockMVC, you should consider @SpringBootTest
combined with @AutoConfigureMockMvc
rather than @WebMvcTest
The only thing worked for me:
1) Delete Derived Data with CleanMyMac: System Junk -> Xcode Junk -> Xcode Derived Data
Deleting Derived Data with CleanMyMac
2) Then in Xcode: Product -> Clean
The content you're scraping is encoded in unicode rather than ascii text, and you're getting a character that doesn't convert to ascii. The right 'translation' depends on what the original web page thought it was. Python's unicode page gives the background on how it works.
Are you trying to print the result or stick it in a file? The error suggests it's writing the data that's causing the problem, not reading it. This question is a good place to look for the fixes.
Either run in SQL:
ALTER TABLE tableName
ADD PRIMARY KEY (id) ---or Drugid, whichever you want it to be PK
or use the PHPMyAdmin interface (Table Structure)
This untested, but I think you may be able to try something like this:
$('#listItem').not('span').text();
You may already find your answer because it was some time ago you asked. But I tried to do something similar when coding ror. I wanted to run "rails server" in a new cmd window so I don't have to open a new cmd and then find my path again.
What I found out was to use the K switch like this:
start cmd /k echo Hello, World!
start before "cmd" will open the application in a new window and "/K" will execute "echo Hello, World!" after the new cmd is up.
You can also use the /C switch for something similar.
start cmd /C pause
This will then execute "pause" but close the window when the command is done. In this case after you pressed a button. I found this useful for "rails server", then when I shutdown my dev server I don't have to close the window after.
Use the following in your batch file:
start cmd.exe /c "more-batch-commands-here"
or
start cmd.exe /k "more-batch-commands-here"
/c Carries out the command specified by string and then terminates
/k Carries out the command specified by string but remains
The /c
and /k
options controls what happens once your command finishes running. With /c
the terminal window will close automatically, leaving your desktop clean. With /k
the terminal window will remain open. It's a good option if you want to run more commands manually afterwards.
Consult the cmd.exe documentation using cmd /?
for more details.
The proper formatting of the command string becomes more complicated when using arguments with spaces. See the examples below. Note the nested double quotes in some examples.
Run a program and pass a filename parameter:
CMD /c write.exe c:\docs\sample.txt
Run a program and pass a filename which contains whitespace:
CMD /c write.exe "c:\sample documents\sample.txt"
Spaces in program path:
CMD /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""
Spaces in program path + parameters:
CMD /c ""c:\Program Files\demo.cmd"" Parameter1 Param2
CMD /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""
Launch demo1 and demo2:
CMD /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""
Source: http://ss64.com/nt/cmd.html
Maybe you forgot to change the permissions of app/cache app/log
I'm using Ubuntu so
sudo chmod -R 777 app/cache
sudo chmod -R 777 app/logs
sudo setfacl -dR -m u::rwX app/cache app/logs
Hope it helps..
First you should create a div
with id='footer'
after your content
div and then simply do this.
Your HTML should look like this:
<html>
<body>
<div id="content">
...
</div>
<div id="footer"></div>
</body>
</html>
And the CSS:
?html, body {
height: 100%;
}
#content {
height: 100%;
}
#footer {
clear: both;
}
Two suggestions to solving this problem:
SOLUTION 1: <div style="white-space:pre;">{database text}</div>
or <pre>{database text}</pre>
This is good solution if your text has no html tags or css properties. Also allows to maintain tabs for example.
SOLUTION 2: Replace \n
with <p></p> or <br/>
This is a solution if you would just like to add break-lines, without losing other text properties or formatting.
An example in php would be $text = str_replace("\n","<br />",$database_text);
You can also use <p></p>
or <div></div>
, but this requires a bit more text parsing.
You can do this without importing os or other libs.
If you want to get the path of current python script, use: __file__
If you want to get only the filename without .py extension, use this:
__file__.rsplit("/", 1)[1].split('.')[0]
The above did not work for me but this did
<%= link_to "text_to_show_in_url", action_controller_path(:gender => "male", :param2=> "something_else") %>
It seems using pandas Timestamp is the fastest
import pandas as pd
N = 1000
l = ['Jun 1 2005 1:33PM'] * N
list(pd.to_datetime(l, format=format))
%timeit _ = list(pd.to_datetime(l, format=format))
1.58 ms ± 21.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Other solutions
from datetime import datetime
%timeit _ = list(map(lambda x: datetime.strptime(x, format), l))
9.41 ms ± 95.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
from dateutil.parser import parse
%timeit _ = list(map(lambda x: parse(x), l))
73.8 ms ± 1.14 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
If the string is ISO8601 string please use csio8601
import ciso8601
l = ['2014-01-09'] * N
%timeit _ = list(map(lambda x: ciso8601.parse_datetime(x), l))
186 µs ± 4.13 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
Set setHasMenuOptions(true) works if application has a theme with Actionbar such as Theme.MaterialComponents.DayNight.DarkActionBar
or Activity
has it's own Toolbar, otherwise onCreateOptionsMenu
in fragment does not get called.
If you want to use standalone Toolbar
you either need to get activity and set your Toolbar
as support action bar with
(requireActivity() as? MainActivity)?.setSupportActionBar(toolbar)
which lets your fragment onCreateOptionsMenu to be called.
Other alternative is, you can inflate your Toolbar
's own menu with toolbar.inflateMenu(R.menu.YOUR_MENU)
and item listener with
toolbar.setOnMenuItemClickListener {
// do something
true
}
In [34]: import pandas as pd
In [35]: import numpy as np
In [36]: df = pd.DataFrame([1,2,3,4], columns=["data"])
In [37]: df
Out[37]:
data
0 1
1 2
2 3
3 4
In [38]: df["desired_output"] = np.where(df["data"] <2.5, "False", "True")
In [39]: df
Out[39]:
data desired_output
0 1 False
1 2 False
2 3 True
3 4 True
For Spark 1.5 or later, you can use the functions package:
from pyspark.sql.functions import *
newDf = df.withColumn('address', regexp_replace('address', 'lane', 'ln'))
Quick explanation:
withColumn
is called to add (or replace, if the name exists) a column to the data frame. regexp_replace
will generate a new column by replacing all substrings that match the pattern.Here is a handy function you can use to help with identifying your opencv matrices at runtime. I find it useful for debugging, at least.
string type2str(int type) {
string r;
uchar depth = type & CV_MAT_DEPTH_MASK;
uchar chans = 1 + (type >> CV_CN_SHIFT);
switch ( depth ) {
case CV_8U: r = "8U"; break;
case CV_8S: r = "8S"; break;
case CV_16U: r = "16U"; break;
case CV_16S: r = "16S"; break;
case CV_32S: r = "32S"; break;
case CV_32F: r = "32F"; break;
case CV_64F: r = "64F"; break;
default: r = "User"; break;
}
r += "C";
r += (chans+'0');
return r;
}
If M
is a var of type Mat
you can call it like so:
string ty = type2str( M.type() );
printf("Matrix: %s %dx%d \n", ty.c_str(), M.cols, M.rows );
Will output data such as:
Matrix: 8UC3 640x480
Matrix: 64FC1 3x2
Its worth noting that there are also Matrix methods Mat::depth()
and Mat::channels()
. This function is just a handy way of getting a human readable interpretation from the combination of those two values whose bits are all stored in the same value.
Use datetime.datetime.fromtimestamp
:
>>> import datetime
>>> s = 1236472051807 / 1000.0
>>> datetime.datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S.%f')
'2009-03-08 09:27:31.807000'
%f
directive is only supported by datetime.datetime.strftime
, not by time.strftime
.
UPDATE Alternative using %
, str.format
:
>>> import time
>>> s, ms = divmod(1236472051807, 1000) # (1236472051, 807)
>>> '%s.%03d' % (time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'
>>> '{}.{:03d}'.format(time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'
class() exactly works like Javascript's typeof operator.
To get more details about variables you can use whos command or whos() function.
Here is the example code executed on MATLAB R2017a's Command Window.
>> % Define a number
>> num = 67
num =
67
>> % Get type of variable num
>> class(num)
ans =
'double'
>> % Define character vector
>> myName = 'Rishikesh Agrawani'
myName =
'Rishikesh Agrwani'
>> % Check type of myName
>> class(myName)
ans =
'char'
>> % Define a cell array
>> cellArr = {'This ', 'is ', 'a ', 'big chance to learn ', 'MATLAB.'}; % Cell array
>>
>> class(cellArr)
ans =
'cell'
>> % Get more details including type
>> whos num
Name Size Bytes Class Attributes
num 1x1 8 double
>> whos myName
Name Size Bytes Class Attributes
myName 1x17 34 char
>> whos cellArr
Name Size Bytes Class Attributes
cellArr 1x5 634 cell
>> % Another way to use whos i.e using whos(char_vector)
>> whos('cellArr')
Name Size Bytes Class Attributes
cellArr 1x5 634 cell
>> whos('num')
Name Size Bytes Class Attributes
num 1x1 8 double
>> whos('myName')
Name Size Bytes Class Attributes
myName 1x17 34 char
>>
I have successfully run our app, which requires Google Maps API 2, on an AndroVM virtual machine.
AndroVM does not come with Google Maps or Google Play installed, but provides a modified copy of the Cyanogen Gapps archive, which is a set of the proprietary Google apps installed on most Android devices.
The instructions, copied from the AndroVM FAQ:
How can I install Google Apps (including the Market/Play app) ?
- Download Google Apps : gapps-jb-20121011-androvm.tgz [basically the /system directory from the Cyanogen gapps archive without the GoogleTTS app which crashes on AndroVM]
- Untar the gapps…tgz file on your host – you’ll have a system directory created
- Get the management IP address of your AndroVM (“AndroVM Configuration” tool) and do “adb connect x.y.z.t”
- do “adb root”
- reconnect with “adn connect x.y.z.t”
- do “adb remount”
- do “adb push system/ /system/”
Your VM will reboot and you should have google apps including Market/Play.
You won’t have some Google Apps, like Maps, but they can be downloaded from the Market/Play.
So follow those instructions, then just install Google Maps using Google Play!
Some great side effects of using a VM rather than the emulator:
The only bump in the road so far has been lack of multi-touch gestures, which is a bummer for a mapping app! I plan to work around this with a hidden UI mechanism, so not such a huge problem.
Files.exists()
Files.createDirectory()
Files.copy()
Overwriting Existing Files: Files.move()
Files.delete()
Files.walkFileTree() enter link description here
It's too late but hope it helps. Most of the answers are not pointing into the right direction. There are two simple flags for such thing.
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
From Android docs:
public static final int FLAG_ACTIVITY_CLEAR_TASK Added in API level 11
If set in an Intent passed to Context.startActivity(), this flag will cause any existing task that would be associated with the
activity to be cleared before the activity is started. That is, the activity becomes the new root of an otherwise empty task, and any old activities are finished. This can only be used in conjunction with FLAG_ACTIVITY_NEW_TASK.
HTML
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary btn-lg">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
JS
$('button').click(function(){
$('#myModal').modal('show');
});
The problem is that you assigned a fixed width to your .wrap DIV. The DIV itself is centered (you can see that when you add a border to it) but the DIV is just too wide. In other words the content does not fill the whole width of the DIV.
To solve the problem you have to make sure, that the .wrap DIV is only as wide as it's content.
To achieve that you have to remove the floating in the content elements and set the display
property of the block levels elements to inline
:
#partners .wrap {
display: inline;
}
.wrap { margin: 0 auto; position: relative;}
#partners h2 {
color: #A6A5A5;
font-weight: normal;
margin: 2px 15px 0 0;
display: inline;
}
#partners ul {
display: inline;
}
#partners li {display: inline}
ul { list-style-position: outside; list-style-type: none; }
Well, you have to set your dialog's height and width before to show this ( dialog.show() )
so, do something like this:
dialog.getWindow().setLayout(width, height);
//then
dialog.show()
Getting this code, i made it some changes:
dialog.getWindow().setLayout((int)(MapGeaGtaxiActivity.this.getWindow().peekDecorView().getWidth()*0.9),(int) (MapGeaGtaxiActivity.this.getWindow().peekDecorView().getHeight()*0.9));
however, dialog size's could change when the device change its position. Perhaps you need to handle by your own when metrics changes. PD: peekDecorView, implies that layout in activity is properly initialized otherwise you may use
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = metrics.heightPixels;
int wwidth = metrics.widthPixels;
in order to get screen size
Every time I Google how to do this I end up reading this same thread, but it doesn't get me where I need to be, so hopefully this will help my future self and others too.
I started a new local project that I want to push to my repo (BitBucket). Here is what I did:
git init
git add .
git commit -m "Initial commit"
new_project
git remote add origin [email protected]:AndrewFox/new_project.git
git push origin master -f
The -f
flag is to force the push, otherwise it will identify that the two repo's are different and fail.
You can Try this,
$newfilename= date('dmYHis').str_replace(" ", "", basename($_FILES["file"]["name"]));
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);
See answer here: Custom arrows without image: Android
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="32dp"
android:height="24dp"
android:viewportWidth="32.0"
android:viewportHeight="24.0">
<path android:fillColor="#e4e4e8"
android:pathData="M0 0 h32 l-16 24 Z"/>
</vector>
I use zsh-autoenv which is based off autoenv.
zsh-autoenv automatically sources (known/whitelisted)
.autoenv.zsh
files, typically used in project root directories. It handles "enter" and leave" events, nesting, and stashing of variables (overwriting and restoring).
Here is an example:
; cd dtree
Switching to virtual environment: Development tree utiles
;dtree(feature/task24|?); cat .autoenv.zsh
# Autoenv.
echo -n "Switching to virtual environment: "
printf "\e[38;5;93m%s\e[0m\n" "Development tree utiles"
workon dtree
# eof
dtree(feature/task24|?); cat .autoenv_leave.zsh
deactivate
So when I leave the dtree
directory, the virtual environment is automatically exited.
"Development tree utiles"
is just a name… No hidden mean linking to the Illuminati in here.
(Repeating here my answer elsewhere.)
In theory, linux (the kernel underlying android) has mac80211_hwsim driver, which simulates WiFi. It can be used to set up several WiFi devices (an acces point, and another WiFi device, and so on), which would make up a WiFi network.
It's useful for testing WiFi programs under linux. Possibly, even under user-mode linux or other isolated virtual "boxes" with linux.
In theory, this driver could be used for tests in the android systems where you don't have a real WiFi device (or don't want to use it), and also in some kind of android emulators. Perhaps, one can manage to use this driver in android-x86, or--for testing--in android-x86 run in VirtualBox.
axios.put(url,{body},{headers:{}})
example:
const body = {title: "what!"}
const api = {
apikey: "safhjsdflajksdfh",
Authorization: "Basic bwejdkfhasjk"
}
axios.put('https://api.xxx.net/xx', body, {headers: api})
Similar to the second solution, less code:
declare @date datetime = '2014-03-31'
SELECT DATEDIFF(week,0,@date) - (DATEDIFF(week,0,DATEADD(dd, -DAY(@date)+1, @date))-1)
Solution 1: Sometimes the build fails because, the target folder cannot be deleted. (It might be open in the backend due to the previous builds.)
-> Open Task Manager
-> In the Process tab
-> Do "End Process" for the running "java.exe" processess
Solution 2:
-> Restart eclipse
-> Perform Maven Build with command : clean install -DSkipTests
I guess best way to do this is ...
int main()
{
char str[100];
scanf("[^EOF]",str);
printf("%s",str);
return 0;
}
This can happen if a comma is missing. I ran into it when I had a list of two-tuples, each of which consisted of a string in the first position, and a list in the second. I erroneously omitted the comma after the first component of a tuple in one case, and the interpreter thought I was trying to index the first component.
Because by default jQuery serializes objects passed as the data
parameter to $.ajax
. It uses $.param
to convert the data to a query string.
From the jQuery docs for $.ajax
:
[the
data
argument] is converted to a query string, if not already a string
If you want to send JSON, you'll have to encode it yourself:
data: JSON.stringify(arr);
Note that JSON.stringify
is only present in modern browsers. For legacy support, look into json2.js
you could use a one liner option
<div ng-repeat="key in keywords">
<button ng-click="keywords.splice($index, 1)">
{{key.name}}
</button>
</div>
$index
is used by angular to show current index of the array inside ng-repeat
If you right-click on your project, there should be an option under "maven" to "enable dependency management". That's it.
You might be just missing the column list, as the message says
SET IDENTITY_INSERT [MyDB].[dbo].[Equipment] ON
INSERT INTO [MyDB].[dbo].[Equipment]
(COL1,
COL2)
SELECT COL1,
COL2
FROM [MyDBQA].[dbo].[Equipment]
SET IDENTITY_INSERT [MyDB].[dbo].[Equipment] OFF
why dont you do something like:
re = /^[a-z0-9 ]$/i;
var isValid = re.test(yourInput);
to check if your input contain any special char
Simplest example would consist of:
Composing XML SOAP message similar to this
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetInfoByZIP xmlns="http://www.webserviceX.NET">
<USZip>string</USZip>
</GetInfoByZIP>
</soap:Body>
</soap:Envelope>
POSTing message to webservice url using XHR
Parsing webservice's XML SOAP response similar to this
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetInfoByZIPResponse xmlns="http://www.webserviceX.NET">
<GetInfoByZIPResult>
<NewDataSet xmlns="">
<Table>
<CITY>...</CITY>
<STATE>...</STATE>
<ZIP>...</ZIP>
<AREA_CODE>...</AREA_CODE>
<TIME_ZONE>...</TIME_ZONE>
</Table>
</NewDataSet>
</GetInfoByZIPResult>
</GetInfoByZIPResponse>
</soap:Body>
</soap:Envelope>
Presenting results to user.
But it's a lot of hassle without external JavaScript libraries.
I have posted the following walkthrough for adding some fake word-wrapping to an SVG "text" element here:
You just need to add a simple JavaScript function, which splits your string into shorter "tspan" elements. Here's an example of what it looks like:
Hope this helps !
You can think DataFrame as a dict of Series. df[key]
try to select the column index by key
and returns a Series object.
However slicing inside of [] slices the rows, because it's a very common operation.
You can read the document for detail:
http://pandas.pydata.org/pandas-docs/stable/indexing.html#basics
Had the exact same problem that is described herein. No matter what I did, following the above examples, to change the location of my WSDL file (in our case from a web server), it was still referencing the original location embedded within the source tree of the server process.
After MANY hours trying to debug this, I noticed that the Exception was always being thrown from the exact same line (in my case 41). Finally this morning, I decided to just send my source client code to our trade partner so they can at least understand how the code looks, but perhaps build their own. To my shock and horror I found a bunch of class files mixed in with my .java files within my client source tree. How bizarre!! I suspect these were a byproduct of the JAX-WS client builder tool.
Once I zapped those silly .class files and performed a complete clean and rebuild of the client code, everything works perfectly!! Redonculous!!
YMMV, Andrew
There seems to be no way to place buttons (drawings, images) within cells in a way that would allow them to be linked to Apps Script functions.
This being said, there are some things that you can indeed do:
You can place images within cells using IMAGE(URL)
, but they cannot be linked to Apps Script functions.
You can place images within cells and link them to URLs using:
=HYPERLINK("http://example.com"; IMAGE("http://example.com/myimage.png"; 1))
You can create drawings as described in the answer of @Eduardo and they can be linked to Apps Script functions, but they will be stand-alone items that float freely "above" the spreadsheet and cannot be positioned in cells. They cannot be copied from cell to cell and they do not have a row or col position that the script function could read.
update your CSS to the following: this should fix
.page {
width: 280px;
border:solid 1px blue;
overflow-x: auto;
}
From the TypeScript site: https://github.com/Microsoft/TypeScript/issues/6471
The recommended practice is to write the props type as {children?: any}
That worked for me. The child node can be many different things, so explicit typing can miss cases.
There's a longer discussion on the followup issue here: https://github.com/Microsoft/TypeScript/issues/13618, but the any approach still works.
You can try this.
Workbooks("Tire.xls").Activate
ThisWorkbook.Sheets("Sheet1").Select
Cells(2,24).value=24
What you are trying to do is not possible. The reason for this is that in a POSIX system (Linux, OSX, etc), a child process cannot modify the environment of a parent process. This includes modifying the parent process's working directory and environment variables.
When you are on the commandline and you go to execute your Node script, your current process (bash
, zsh
, whatever) spawns a new process which has it's own environment, typically a copy of your current environment (it is possible to change this via system calls; but that's beyond the scope of this reply), allowing that process to do whatever it needs to do in complete isolation. When the subprocess exits, control is handed back to your shell's process, where the environment hasn't been affected.
There are a lot of reasons for this, but for one, imagine that you executed a script in the background (via ./foo.js &
) and as it ran, it started changing your working directory or overriding your PATH
. That would be a nightmare.
If you need to perform some actions that require changing your working directory of your shell, you'll need to write a function in your shell. For example, if you're running Bash, you could put this in your ~/.bash_profile
:
do_cool_thing() {
cd "/Users"
echo "Hey, I'm in $PWD"
}
and then this cool thing is doable:
$ pwd
/Users/spike
$ do_cool_thing
Hey, I'm in /Users
$ pwd
/Users
If you need to do more complex things in addition, you could always call out to your nodejs script from that function.
This is the only way you can accomplish what you're trying to do.
Along with JFileChooser is possible use this:
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
for have a Look and Feel like Windows.
for others settings, view here: https://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html#available
It will be solved with this line in -(void)viewDidLoad:
self.navigationItem.backBarButtonItem.tintColor = UIColor.whiteColor;
maybe like this - all last month DATE(recDate) BETWEEN DATE_ADD(LAST_DAY(DATE_SUB(CURDATE(), INTERVAL 2 MONTH)), INTERVAL 1 DAY) AND LAST_DAY(DATE_SUB(CURDATE(), INTERVAL 1 MONTH) )
This won't do what you are expecting:
<img src="image1.gif" alt="image2.gif" />
The ALT attribute is text-only--it won't do anything special if you give it an image URL.
If you want to initially display a low res image, then replace it with a high res image, you could do some javascript coding to swap out the images. Or, perhaps load the image into a div which has a background pattern filled with the low res image. Then, when the high res image loads, it'll load overtop the background.
Unfortunately, there's no direct way to do this.
Your second attempt will create a link to image2, but actually display image1.
<a href="image2.gif" ><img src="image1.gif"/></a>
If you want to popup a higher res version, @Sam's suggestion is a good idea.
This CSS might work for you (it works for me in Firefox 3):
<html>
<head>
<style>
.lowres { background-image: url('low-res.png');}
</style>
</head>
<body>
<div class="lowres" style="height:500px; width:500px">
<img src="hi-res.png" />
</div>
</body>
</html>
In that example, you have to set the div height/width to that of the image. It will actually load both images simultaneously, but presuming the low-res one loads quick, you might see it first while the hi-res image downloads.
  is the answer.
However, they won't be as functional as you might expect if you are used to using horizontal tabulations in word-processors e.g. Word, Wordperfect, Open Office, Wordworth, etc. They are fixed width, and they cannot be customised.
CSS gives you far greater control and provides an alternative until the W3C provide an official solution.
Example:
padding-left:4em
..or..
margin-left:4em
..as appropriate
It depends on which character set you want to use.
You could set up some tab tags and use them similar to how you would use h tags.
<style>
tab1 { padding-left: 4em; }
tab2 { padding-left: 8em; }
tab3 { padding-left: 12em; }
tab4 { padding-left: 16em; }
tab5 { padding-left: 20em; }
tab6 { padding-left: 24em; }
tab7 { padding-left: 28em; }
tab8 { padding-left: 32em; }
tab9 { padding-left: 36em; }
tab10 { padding-left: 40em; }
tab11 { padding-left: 44em; }
tab12 { padding-left: 48em; }
tab13 { padding-left: 52em; }
tab14 { padding-left: 56em; }
tab15 { padding-left: 60em; }
tab16 { padding-left: 64em; }
</style>
...and use them like so:
<!DOCTYPE html>_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
<title>Tabulation example</title>_x000D_
_x000D_
<style type="text/css">_x000D_
dummydeclaration { padding-left: 4em; } /* Firefox ignores first declaration for some reason */_x000D_
tab1 { padding-left: 4em; }_x000D_
tab2 { padding-left: 8em; }_x000D_
tab3 { padding-left: 12em; }_x000D_
tab4 { padding-left: 16em; }_x000D_
tab5 { padding-left: 20em; }_x000D_
tab6 { padding-left: 24em; }_x000D_
tab7 { padding-left: 28em; }_x000D_
tab8 { padding-left: 32em; }_x000D_
tab9 { padding-left: 36em; }_x000D_
tab10 { padding-left: 40em; }_x000D_
tab11 { padding-left: 44em; }_x000D_
tab12 { padding-left: 48em; }_x000D_
tab13 { padding-left: 52em; }_x000D_
tab14 { padding-left: 56em; }_x000D_
tab15 { padding-left: 60em; }_x000D_
tab16 { padding-left: 64em; }_x000D_
_x000D_
</style>_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<p>Non tabulated text</p>_x000D_
_x000D_
<p><tab1>Tabulated text</tab1></p>_x000D_
<p><tab2>Tabulated text</tab2></p>_x000D_
<p><tab3>Tabulated text</tab3></p>_x000D_
<p><tab3>Tabulated text</tab3></p>_x000D_
<p><tab2>Tabulated text</tab2></p>_x000D_
<p><tab3>Tabulated text</tab3></p>_x000D_
<p><tab4>Tabulated text</tab4></p>_x000D_
<p><tab4>Tabulated text</tab4></p>_x000D_
<p>Non tabulated text</p>_x000D_
<p><tab3>Tabulated text</tab3></p>_x000D_
<p><tab4>Tabulated text</tab4></p>_x000D_
<p><tab4>Tabulated text</tab4></p>_x000D_
<p><tab1>Tabulated text</tab1></p>_x000D_
<p><tab2>Tabulated text</tab2></p>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
Run the snippet above to see a visual example.
Extra discussion
There are no horizontal tabulation entities defined in ISO-8859-1 HTML, however there are some other white-space characters available than the usual  
, for example;  
,  
and the aforementioned  
.
It's also worth mentioning that in ASCII and Unicode, 	
is a horizontal tabulation.
Use the Array#join
method (the argument to join
is what to insert between the strings - in this case a space):
@arr.join(" ")
It sounds like the server is having trouble handling POST requests (get and post are verbs). I don't know, how or why someone would configure a server to ignore post requests, but the only solution would be to fix the server, or change your app to use get requests.
Although @Remus Rusanu's is already an excelent answer, in case one is looking forward a better insight on SQL Server's Deadlock causes and trace strategies, I would suggest you to read Brad McGehee's How to Track Down Deadlocks Using SQL Server 2005 Profiler
A complete example for someone who may want to use this to monitor a mount point on a server. This example will check if /var/spool is under 5G and email the person :
#!/bin/bash
# -----------------------------------------------------------------------------------------
# SUMMARY: Check if MOUNT is under certain quota, mail us if this is the case
# DETAILS: If under 5G we have it alert us via email. blah blah
# -----------------------------------------------------------------------------------------
# CRON: 0 0,4,8,12,16 * * * /var/www/httpd-config/server_scripts/clear_root_spool_log.bash
MOUNTP=/var/spool # mount drive to check
LIMITSIZE=5485760 # 5G = 10*1024*1024k # limit size in GB (FLOOR QUOTA)
FREE=$(df -k --output=avail "$MOUNTP" | tail -n1) # df -k not df -h
LOG=/tmp/log-$(basename ${0}).log
MAILCMD=mail
EMAILIDS="[email protected]"
MAILMESSAGE=/tmp/tmp-$(basename ${0})
# -----------------------------------------------------------------------------------------
function email_on_failure(){
sMess="$1"
echo "" >$MAILMESSAGE
echo "Hostname: $(hostname)" >>$MAILMESSAGE
echo "Date & Time: $(date)" >>$MAILMESSAGE
# Email letter formation here:
echo -e "\n[ $(date +%Y%m%d_%H%M%S%Z) ] Current Status:\n\n" >>$MAILMESSAGE
cat $sMess >>$MAILMESSAGE
echo "" >>$MAILMESSAGE
echo "*** This email generated by $(basename $0) shell script ***" >>$MAILMESSAGE
echo "*** Please don't reply this email, this is just notification email ***" >>$MAILMESSAGE
# sending email (need to have an email client set up or sendmail)
$MAILCMD -s "Urgent MAIL Alert For $(hostname) AWS Server" "$EMAILIDS" < $MAILMESSAGE
[[ -f $MAILMESSAGE ]] && rm -f $MAILMESSAGE
}
# -----------------------------------------------------------------------------------------
if [[ $FREE -lt $LIMITSIZE ]]; then
echo "Writing to $LOG"
echo "MAIL ERROR: Less than $((($FREE/1000))) MB free (QUOTA) on $MOUNTP!" | tee ${LOG}
echo -e "\nPotential Files To Delete:" | tee -a ${LOG}
find $MOUNTP -xdev -type f -size +500M -exec du -sh {} ';' | sort -rh | head -n20 | tee -a ${LOG}
email_on_failure ${LOG}
else
echo "Currently $(((($FREE-$LIMITSIZE)/1000))) MB of QUOTA available of on $MOUNTP. "
fi
Beside all the above hints like track by and smaller loops, this one also helped me a lot
<span ng-bind="::stock.name"></span>
this piece of code would print the name once it has been loaded, and stop watching it after that. Similarly, for ng-repeats, it could be used as
<div ng-repeat="stock in ::ctrl.stocks">{{::stock.name}}</div>
however it only works for AngularJS version 1.3 and higher. From http://www.befundoo.com/blog/optimizing-ng-repeat-in-angularjs/
please try following to generate
function addRow()
{
var e1 = document.createElement("input");
e1.type = "text";
e1.name = "name1";
var cont = document.getElementById("content")
cont.appendChild(e1);
}
I case of tomcat 7 the role has changed from manager to manager-gui so set it as below in the tomcat-user.xml file.
Your original plan sounds fine to me. You'll probably find more browser quirks dealing with dynamically managing the <source>
elements, as indicated here by the W3 spec note:
Dynamically modifying a source element and its attribute when the element is already inserted in a video or audio element will have no effect. To change what is playing, just use the src attribute on the media element directly, possibly making use of the canPlayType() method to pick from amongst available resources. Generally, manipulating source elements manually after the document has been parsed is an unncessarily[sic] complicated approach.
http://dev.w3.org/html5/spec/Overview.html#the-source-element
Extension to parse decimal number from string.
Ability to set decimal symbol manually.
public static class StringExtension
{
public static double DoubleParseAdvanced(this string strToParse, char decimalSymbol = ',')
{
string tmp = Regex.Match(strToParse, @"([-]?[0-9]+)([\s])?([0-9]+)?[." + decimalSymbol + "]?([0-9 ]+)?([0-9]+)?").Value;
if (tmp.Length > 0 && strToParse.Contains(tmp))
{
var currDecSeparator = System.Windows.Forms.Application.CurrentCulture.NumberFormat.NumberDecimalSeparator;
tmp = tmp.Replace(".", currDecSeparator).Replace(decimalSymbol.ToString(), currDecSeparator);
return double.Parse(tmp);
}
return 0;
}
}
How to use:
"It's 4.45 O'clock now".DoubleParseAdvanced(); // will return 4.45
"It's 4,45 O'clock now".DoubleParseAdvanced(); // will return 4.45
"It's 4:45 O'clock now".DoubleParseAdvanced(':'); // will return 4.45
var result = string.Join(",", arr);
This uses the following overload of string.Join
:
public static string Join<T>(string separator, IEnumerable<T> values);
I'm pretty sure the code is not using the System.Net.Http.HttpContent class, but instead Microsoft.Http.HttpContent. Microsoft.Http was the WCF REST Starter Kit, which never made it out preview before being placed in the .NET Framework. You can still find it here: http://aspnet.codeplex.com/releases/view/24644
I would not recommend basing new code on it.
The replace function should work for you.
REPLACE(str,from_str,to_str)
Returns the string str with all occurrences of the string from_str replaced by the string to_str. REPLACE()
performs a case-sensitive match when searching for from_str.
Never mind, it's req.session.destroy();
Here's the code I came up with to remove items selected by a user from a listbox It seems to work ok in a multiselect listbox (selectionmode prop is set to multiextended).:
Private Sub cmdRemoveList_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdRemoveList.Click
Dim knt As Integer = lstwhatever.SelectedIndices.Count
Dim i As Integer
For i = 0 To knt - 1
lstwhatever.Items.RemoveAt(lstwhatever.SelectedIndex)
Next
End Sub
Use UploadStringAsync
method:
WebClient webClient = new WebClient();
webClient.UploadStringCompleted += (s, e) =>
{
if (e.Error != null)
{
//handle your error here
}
else
{
//post was successful, so do what you need to do here
}
};
webClient.UploadStringAsync(new Uri(yourUri), UriKind.Absolute), "POST", yourParameters);
A better way to solve this problem is to use a function like this:
function scrollToTop(callback, q) {
if ($('html').scrollTop()) {
$('html').animate({ scrollTop: 0 }, function() {
console.log('html scroll');
callback(q)
});
return;
}
if ($('body').scrollTop()) {
$('body').animate({ scrollTop: 0 }, function() {
console.log('body scroll');
callback(q)
});
return;
}
callback(q);
}
This will work across all browsers and prevents FireFox from scrolling up twice (which is what happens if you use the accepted answer - $("html,body").animate({ scrollTop: 0 }, "slow");
).
...for now
Your onCreate()
method has several huge flaws:
1) onCreate
prepares your Activity - so nothing that you do here will be made visible to the user until this method finishes! For example - you will never be able to alter a TextView
's text here more than ONE time as only the last change will be drawn and thus visible to the user!
2) Keep in mind that an Android program will - by default - run in ONE thread only! Thus: never use Thread.sleep()
or Thread.wait()
in your main thread which is responsible for your UI! (read "Keep your App Responsive" for further information!)
What your initialization of your Activity does is:
TextView
object t
!TextView
in the variable t
later.t
(but keep in mind: it will be displayed only after onCreate()
finishes and the main event loop of your application runs!)onCreate
method - this must never be done as it stops all UI activity and will definitely force an ANR (Application Not Responding, see link above!)onCreate()
method finishes and several other Activity lifecycle methods have been processed!The solution:
Set text only once in onCreate()
- this must be the first text that should be visible.
Create a Runnable
and a Handler
private final Runnable mUpdateUITimerTask = new Runnable() {
public void run() {
// do whatever you want to change here, like:
t.setText("Second text to display!");
}
};
private final Handler mHandler = new Handler();
install this runnable as a handler, possible in onCreate()
(but read my advice below):
// run the mUpdateUITimerTask's run() method in 10 seconds from now
mHandler.postDelayed(mUpdateUITimerTask, 10 * 1000);
Advice: be sure you know an Activity
's lifecycle! If you do stuff like that in onCreate()
this will only happen when your Activity
is created the first time! Android will possibly keep your Activity
alive for a longer period of time, even if it's not visible!
When a user "starts" it again - and it is still existing - you will not see your first text anymore!
=> Always install handlers in onResume()
and disable them in onPause()
! Otherwise you will get "updates" when your Activity
is not visible at all!
In your case, if you want to see your first text again when it is re-activated, you must set it in onResume()
, not onCreate()
!
Disable Power Save Mode and Invalidate Cache and Restart.
Installing Yarn for Ubuntu 16.04 (not sure if this will be the same as 14.04 as it's slightly different than zappee's answer for 17.04)
curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
curl -sL https://deb.nodesource.com/setup_9.x | sudo -E bash -
apt-get update
apt-get install nodejs
apt-get install yarn
Then from wherever you installed your sylius project (/var/www/mysite)
yarn install
yarn run gulp
Follow the below
ng-click="anyFunction()"
anyFunction() {
// call another function here
anotherFunction();
}
In the other posts, you have the shortcut keys, but if you want the menu option in every system, just go to Find > Quick Find All, as shown in the image attached.
Also, check the other answers for key binding to do it faster than menu clicking.
Here's a list of differences. I've highlighted Oracle-specific features, and hopefully the community can add in other vendors' specific difference also. Differences that are common to most vendors can go directly below the headings, with differences highlighted below.
If you want to quickly delete all of the rows from a table, and you're really sure that you want to do it, and you do not have foreign keys against the tables, then a TRUNCATE is probably going to be faster than a DELETE.
Various system-specific issues have to be considered, as detailed below.
Delete is DML, Truncate is DDL (What is DDL and DML?)
Variable by vendor
SQL*Server
Truncate can be rolled back.
PostgreSQL
Truncate can be rolled back.
Oracle
Because a TRUNCATE is DDL it involves two commits, one before and one after the statement execution. Truncate can therefore not be rolled back, and a failure in the truncate process will have issued a commit anyway.
However, see Flashback below.
Delete does not recover space, Truncate recovers space
Oracle
If you use the REUSE STORAGE clause then the data segments are not de-allocated, which can be marginally more efficient if the table is to be reloaded with data. The high water mark is reset.
Delete can be used to remove all rows or only a subset of rows. Truncate removes all rows.
Oracle
When a table is partitioned, the individual partitions can be truncated in isolation, thus a partial removal of all the table's data is possible.
Delete can be applied to tables and tables inside a cluster. Truncate applies only to tables or the entire cluster. (May be Oracle specific)
Oracle
Delete does not affect the data object id, but truncate assigns a new data object id unless there has never been an insert against the table since its creation Even a single insert that is rolled back will cause a new data object id to be assigned upon truncation.
Flashback works across deletes, but a truncate prevents flashback to states prior to the operation.
However, from 11gR2 the FLASHBACK ARCHIVE feature allows this, except in Express Edition
Use of FLASHBACK in Oracle http://docs.oracle.com/cd/E11882_01/appdev.112/e41502/adfns_flashback.htm#ADFNS638
Variable
Oracle
Delete can be granted on a table to another user or role, but truncate cannot be without using a DROP ANY TABLE grant.
Delete generates a small amount of redo and a large amount of undo. Truncate generates a negligible amount of each.
Oracle
A truncate operation renders unusable indexes usable again. Delete does not.
A truncate cannot be applied when an enabled foreign key references the table. Treatment with delete depends on the configuration of the foreign keys.
Oracle
Truncate requires an exclusive table lock, delete requires a shared table lock. Hence disabling table locks is a way of preventing truncate operations on a table.
DML triggers do not fire on a truncate.
Oracle
DDL triggers are available.
Oracle
Truncate cannot be issued over a database link.
SQL*Server
Truncate resets the sequence for IDENTITY column types, delete does not.
In most implementations, a DELETE
statement can return to the client the rows that were deleted.
e.g. in an Oracle PL/SQL subprogram you could:
DELETE FROM employees_temp
WHERE employee_id = 299
RETURNING first_name,
last_name
INTO emp_first_name,
emp_last_name;
I've had good results with this one. Much easier to use than Sharpen.
http://tangiblesoftwaresolutions.com/Product_Details/Java_to_CSharp_Converter.html
You just need to return
from the main function at some point. The error message says that the function is defined to return a value but you are not returning anything.
/* .... */
if (Date1 == Date2)
fprintf (stderr , "Indicating that the first date is equal to second date.\n");
return 0;
}
I'm using Json.net in my project and it works great. In you case, you can do this to parse your json:
EDIT: I changed the code so it supports reading your json file (array)
Code to parse:
void Main()
{
var json = System.IO.File.ReadAllText(@"d:\test.json");
var objects = JArray.Parse(json); // parse as array
foreach(JObject root in objects)
{
foreach(KeyValuePair<String, JToken> app in root)
{
var appName = app.Key;
var description = (String)app.Value["Description"];
var value = (String)app.Value["Value"];
Console.WriteLine(appName);
Console.WriteLine(description);
Console.WriteLine(value);
Console.WriteLine("\n");
}
}
}
Output:
AppName
Lorem ipsum dolor sit amet
1
AnotherAppName
consectetur adipisicing elit
String
ThirdAppName
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua
Text
Application
Ut enim ad minim veniam
100
LastAppName
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat
ZZZ
BTW, you can use LinqPad to test your code, easier than creating a solution or project in Visual Studio I think.
Not so hard:
#include <thread>
void Test::runMultiThread()
{
std::thread t1(&Test::calculate, this, 0, 10);
std::thread t2(&Test::calculate, this, 11, 20);
t1.join();
t2.join();
}
If the result of the computation is still needed, use a future instead:
#include <future>
void Test::runMultiThread()
{
auto f1 = std::async(&Test::calculate, this, 0, 10);
auto f2 = std::async(&Test::calculate, this, 11, 20);
auto res1 = f1.get();
auto res2 = f2.get();
}
The main difference between logging in with a postgres user or any other user created by us, is that when using the postgres user it is NOT necessary to specify the host with -h and instead for another user if.
$ psql -U postgres
# CREATE ROLE usertest LOGIN PASSWORD 'pwtest';
# CREATE DATABASE dbtest WITH OWNER = usertest;
# SHOW port;
# \q
$ psql -h localhost -d dbtest -U usertest -p 5432
GL
Programmers from structural programming language background know it as a function while in OOPS it's called a method.
But there's not any difference between the two.
In the old days, methods did not return values and functions did. Now they both are used interchangeably.
Use repr() and The difference between using repr and str
Using repr
:
>>> try:
... print(x)
... except Exception as e:
... print(repr(e))
...
NameError("name 'x' is not defined")
Using str
:
>>> try:
... print(x)
... except Exception as e:
... print(str(e))
...
name 'x' is not defined
How about something like
CREATE TABLE testRequest (
wardNo nchar(5),
BHTNo nchar(5),
testID nchar(5),
reqDateTime datetime,
PRIMARY KEY (wardNo, BHTNo, testID)
);
Have a look at this example
Try pd.ExcelFile
:
xls = pd.ExcelFile('path_to_file.xls')
df1 = pd.read_excel(xls, 'Sheet1')
df2 = pd.read_excel(xls, 'Sheet2')
As noted by @HaPsantran, the entire Excel file is read in during the ExcelFile()
call (there doesn't appear to be a way around this). This merely saves you from having to read the same file in each time you want to access a new sheet.
Note that the sheet_name
argument to pd.read_excel()
can be the name of the sheet (as above), an integer specifying the sheet number (eg 0, 1, etc), a list of sheet names or indices, or None
. If a list is provided, it returns a dictionary where the keys are the sheet names/indices and the values are the data frames. The default is to simply return the first sheet (ie, sheet_name=0
).
If None
is specified, all sheets are returned, as a {sheet_name:dataframe}
dictionary.
To fix this, I did a reinstall of xcode (This also presented user agreement). I used the following command:
xcode-select --install
In Kotlin, you can use the ktx extensions:
yourView.updateLayoutParams {
height = <YOUR_HEIGHT>
}
I think there are a few things to understand when working with API Gateway integration with Lambda.
There used to be only Lambda Integration which requires mapping templates. I suppose this is why still seeing many examples using it.
As of September 2017, you no longer have to configure mappings to access the request body.
Lambda Proxy Integration, If you enable it, API Gateway will map every request to JSON and pass it to Lambda as the event object. In the Lambda function you’ll be able to retrieve query string parameters, headers, stage variables, path parameters, request context, and the body from it.
Without enabling Lambda Proxy Integration, you’ll have to create a mapping template in the Integration Request section of API Gateway and decide how to map the HTTP request to JSON yourself. And you’d likely have to create an Integration Response mapping if you were to pass information back to the client.
Before Lambda Proxy Integration was added, users were forced to map requests and responses manually, which was a source of consternation, especially with more complex mappings.
Words need to navigate the thinking. To get the terminologies straight.
Lambda Proxy Integration = Pass through
Simply pass the HTTP request through to lambda.
Lambda Integration = Template transformation
Go through a transformation process using the Apache Velocity template and you need to write the template by yourself.
Using Lambda Proxy Integration, the body in the event of lambda is a string escaped with backslash, not a JSON.
"body": "{\"foo\":\"bar\"}"
If tested in a JSON formatter.
Parse error on line 1:
{\"foo\":\"bar\"}
-^
Expecting 'STRING', '}', got 'undefined'
The document below is about response but it should apply to request.
The body field, if you are returning JSON, must be converted to a string or it will cause further problems with the response. You can use JSON.stringify to handle this in Node.js functions; other runtimes will require different solutions, but the concept is the same.
For JavaScript to access it as a JSON object, need to convert it back into JSON object with json.parse in JapaScript, json.dumps in Python.
Strings are useful for transporting but you’ll want to be able to convert them back to a JSON object on the client and/or the server side.
The AWS documentation shows what to do.
if (event.body !== null && event.body !== undefined) {
let body = JSON.parse(event.body)
if (body.time)
time = body.time;
}
...
var response = {
statusCode: responseCode,
headers: {
"x-custom-header" : "my custom header value"
},
body: JSON.stringify(responseBody)
};
console.log("response: " + JSON.stringify(response))
callback(null, response);
You can make both arguments lower case, and that way you will always end up with a case insensitive search.
var string1 = "aBc";
var string2 = "AbC";
if (string1.toLowerCase() === string2.toLowerCase())
{
#stuff
}
I found that CssRewriteUrlTransform fails to run if you're referencing a *.css
file and you have the associated *.min.css
file in the same folder.
To fix this, either delete the *.min.css
file or reference it directly in your bundle:
bundles.Add(new Bundle("~/bundles/bootstrap")
.Include("~/Libs/bootstrap3/css/bootstrap.min.css", new CssRewriteUrlTransform()));
After that you do that, your URLs will be transformed correctly and your images should be correctly resolved.
To be clear there are 4 types of caches you can clear depending upon your case.
php artisan cache:clear
You can run the above statement in your console when you wish to clear the application cache. What it does is that this statement clears all caches inside storage\framework\cache.
php artisan route:cache
This clears your route cache. So if you have added a new route or have changed a route controller or action you can use this one to reload the same.
php artisan config:cache
This will clear the caching of the env file and reload it
php artisan view:clear
This will clear the compiled view files of your application.
Most of the shared hosting providers don't provide SSH access to the systems. In such a case you will need to create a route and call the following line as below:
Route::get('/clear-cache', function() {
Artisan::call('cache:clear');
return "All cache cleared";
});
Escape the apostrophe in O'Neal
by writing O''Neal
(two apostrophes).
Easy:
print my_queryset.query
For example:
from django.contrib.auth.models import User
print User.objects.filter(last_name__icontains = 'ax').query
It should also be mentioned that if you have DEBUG = True, then all of your queries are logged, and you can get them by accessing connection.queries:
from django.db import connections
connections['default'].queries
The django debug toolbar project uses this to present the queries on a page in a neat manner.
you can use like operator wildcard to achieve this:
SELECT t.phone,
t.phone2
FROM jewishyellow.users t
WHERE t.phone LIKE '813%'
AND t.phone2 like '[0-9]';
in this way, you could get all phone2 that have a number prefix.
If you know the network interface (eth0, wlan, tun0 etc):
ifconfig eth0 | grep addr: | awk '{ print $2 }' | cut -d: -f2
I program this way:
sys = {
layout: null,
makeLayout: function (obCLS) {
this.layout = $('<div />').addClass('editor').appendTo($(obCLS)).append(
/* Cargador */
/* @this.layout.find('> div:nth-of-child(1)'); */
'<div>' +
' <p>Seleccione la imagen que desea procesar.</p>' +
' <input type="button" value="Seleccionar" class="btn btn-xlarge btn-success" />' +
' <span></span>' +
'</div>' +
/* Cargador - Progreso */
/* @this.layout.find('> div:nth-of-child(2)'); */
'<div>' +
' <div>' +
' <div></div>' +
' <div>' +
' <div></div>' +
' </div>' +
' </div>' +
'</div>' +
/* Editor */
/* @this.layout.find('> div:nth-of-child(3)');
* @sidebar = this.layout.find('> div:nth-of-child(3) > div > div > div:nth-of-type(1)');
* @body = this.layout.find('> div:nth-of-child(3) > div > div > div:nth-of-type(2) > div'); */
'<div>' +
' <div>' +
' <div>' +
' <div></div>' +
' <div>' +
' <div></div>' +
' </div>' +
' </div>' +
' </div>' +
'</div>'
);
}
}
sys.makeLayout('#div');
If you know that you're using the same context and not detaching any entities, you can make a generic version like this:
public void InsertOrUpdate<T>(T entity, DbContext db) where T : class
{
if (db.Entry(entity).State == EntityState.Detached)
db.Set<T>().Add(entity);
// If an immediate save is needed, can be slow though
// if iterating through many entities:
db.SaveChanges();
}
db
can of course be a class field, or the method can be made static and an extension, but this is the basics.
it should be :
$_SERVER['REQUEST_URI'];
Take a look at : Get the full URL in PHP
just use a reference:
Vec3b & color = image.at<Vec3b>(y,x);
color[2] = 13;
select#xyz {
border:0px;
outline:0px;
}
Exact solution.
If the input numbers have always 7 or 8 digits, you can also use
$str = ($input < 10000000) ? 0 . $input : $input;
I ran some tests and get that this would be up to double as fast as str_pad
or sprintf
.
If the input can have any length, then you could also use
$str = substr('00000000' . $input, -8);
This is not as fast as the other one, but should also be a little bit faster than str_pad
and sprintf
.
Btw: My test also said that sprintf
is a little faster than str_pad
. I made all tests with PHP 5.6.
Edit: Altough the substr
version seems to be still very fast (PHP 7.2), it also is broken in case your input can be longer than the length you want to pad to. E.g. you want to pad to 3 digits and your input has 4 than substr('0000' . '1234', -3) = '234'
will only result in the last 3 digits
Just make the following function:
function insert(str, index, value) {
return str.substr(0, index) + value + str.substr(index);
}
and then use it like that:
alert(insert("foo baz", 4, "bar "));
Output: foo bar baz
It behaves exactly, like the C# (Sharp) String.Insert(int startIndex, string value).
NOTE: This insert function inserts the string value (third parameter) before the specified integer index (second parameter) in the string str (first parameter), and then returns the new string without changing str!
You should be able to get the text using getText()
(for the option element you got using getFirstSelectedOption()
):
Select select = new Select(driver.findElement(By.xpath("//select")));
WebElement option = select.getFirstSelectedOption();
String defaultItem = option.getText();
System.out.println(defaultItem );
Random Samples and Permutations ina dataframe If it is in matrix form convert into data.frame use the sample function from the base package indexes = sample(1:nrow(df1), size=1*nrow(df1)) Random Samples and Permutations
You are trying to delete a row that is referenced by another row (possibly in another table).
You need to delete that row first (or at least re-set its foreign key to something else), otherwise you’d end up with a row that references a non-existing row. The database forbids that.
in express there may be application-scoped JSON formatters.
after looking at express\lib\response.js, I'm using this routine:
function writeJsonPToRes(app, req, res, obj) {
var replacer = app.get('json replacer');
var spaces = app.get('json spaces');
res.set('Content-Type', 'application/json');
var partOfResponse = JSON.stringify(obj, replacer, spaces)
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029');
var callback = req.query[app.get('jsonp callback name')];
if (callback) {
if (Array.isArray(callback)) callback = callback[0];
res.set('Content-Type', 'text/javascript');
var cb = callback.replace(/[^\[\]\w$.]/g, '');
partOfResponse = 'typeof ' + cb + ' === \'function\' && ' + cb + '(' + partOfResponse + ');\n';
}
res.write(partOfResponse);
}
You need to do a couple of things to use the library:
Make sure that you have both the *.lib and the *.dll from the library you want to use. If you don't have the *.lib, skip #2
Put a reference to the *.lib in the project. Right click the project name in the Solution Explorer and then select Configuration Properties->Linker->Input and put the name of the lib in the Additional Dependencies property.
You have to make sure that VS can find the lib you just added so you have to go to the Tools menu and select Options... Then under Projects and Solutions select VC++ Directories,edit Library Directory option. From within here you can set the directory that contains your new lib by selecting the 'Library Files' in the 'Show Directories For:' drop down box. Just add the path to your lib file in the list of directories. If you dont have a lib you can omit this, but while your here you will also need to set the directory which contains your header files as well under the 'Include Files'. Do it the same way you added the lib.
After doing this you should be good to go and can use your library. If you dont have a lib file you can still use the dll by importing it yourself. During your applications startup you can explicitly load the dll by calling LoadLibrary (see: http://msdn.microsoft.com/en-us/library/ms684175(VS.85).aspx for more info)
Cheers!
EDIT
Remember to use #include < Foo.h > as opposed to #include "foo.h". The former searches the include path. The latter uses the local project files.
The other answer is lacking some additional information also in the following post. For example, when the iPhone keep Connect / Disconnect in loop. So here is a better solution:
In vmware.log
search the vid & pid of your iphone USB:
Example:
vmx | USB: Found device [name:Apple\ IR\ Receiver vid:05ac pid:12a8
Close vmware (to unlock .vmx
)
In the .vmx
, add:
usb.quirks.device0 = "0xvid:0xpid skip-reset, skip-refresh, skip-setconfig"
Replace 0xvid:0xpid
by the vid & pid found in vmware.log
. Example:
usb.quirks.device0 = "0x05ac:0x12a8 skip-reset, skip-refresh, skip-setconfig"
In vmware > Edit virtual machine > USB Controller :
USB compatibility : USB 2.0
Active : Automatically connect new USB Devices
Active : Show all USB input devices
Active : Share Bluetooth devices with the virtual Machine
Launch Mac OS and make sure that the mouse is Focus on vmware (or just use the login prompt if it appear)
It's simple but tricky. Please note that we can swap the const
qualifier with any data type (int
, char
, float
, etc.).
Let's see the below examples.
const int *p
==> *p
is read-only [p
is a pointer to a constant integer]
int const *p
==> *p
is read-only [p
is a pointer to a constant integer]
int *p const
==> Wrong Statement. Compiler throws a syntax error.
int *const p
==> p
is read-only [p
is a constant pointer to an integer].
As pointer p
here is read-only, the declaration and definition should be in same place.
const int *p const
==> Wrong Statement. Compiler throws a syntax error.
const int const *p
==> *p
is read-only
const int *const p1
==> *p
and p
are read-only [p
is a constant pointer to a constant integer]. As pointer p
here is read-only, the declaration and definition should be in same place.
int const *p const
==> Wrong Statement. Compiler throws a syntax error.
int const int *p
==> Wrong Statement. Compiler throws a syntax error.
int const const *p
==> *p
is read-only and is equivalent to int const *p
int const *const p
==> *p
and p
are read-only [p
is a constant pointer to a constant integer]. As pointer p
here is read-only, the declaration and definition should be in same place.
This is easy with a flexbox:
#wrapper {_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
#left {_x000D_
flex: 0 0 65%;_x000D_
}_x000D_
_x000D_
#right {_x000D_
flex: 1;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
<div id="left">Left side div</div>_x000D_
<div id="right">Right side div</div>_x000D_
</div>
_x000D_
You can use Create USer to create a user
CREATE LOGIN sam
WITH PASSWORD = '340$Uuxwp7Mcxo7Khy';
USE AdventureWorks;
CREATE USER sam FOR LOGIN sam;
GO
and to Grant (Read-only access) you can use the following
GRANT SELECT TO sam
Hope that helps.
You can't bind an event to the element before it exists, so you should do it in the onload
event:
<html>
<head>
<script type="text/javascript">
window.onload = function() {
document.getElementById('foo').addEventListener('click', function (e) {
var img = document.createElement('img');
img.setAttribute('src', 'http://blog.stackoverflow.com/wp-content/uploads/stackoverflow-logo-300.png');
e.target.appendChild(img);
});
};
</script>
</head>
<body>
<img id="foo" src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />
</body>
</html>
The answer is that #1 is technically correct based on the real meaning of the Mega prefix, however (and in life there is always a however) the math for that doesn't come out so nice in base 2, which is how computers count, so #2 is what people really use.
Various JavaScript versions are implementations of the ECMAScript standard.
Use sorted()
with a key
as follows -
>>> unsorted_list = [['a','b','c','5','d'],['e','f','g','3','h'],['i','j','k','4','m']]
>>> sorted(unsorted_list, key = lambda x: int(x[3]))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]
The lambda
returns the fourth element of each of the inner lists and the sorted
function uses that to sort those list. This assumes that int(elem)
will not fail for the list.
Or use itemgetter
(As Ashwini's comment pointed out, this method would not work if you have string representations of the numbers, since they are bound to fail somewhere for 2+ digit numbers)
>>> from operator import itemgetter
>>> sorted(unsorted_list, key = itemgetter(3))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]
I've found it works this way too:
watch: {
"details.position"(newValue, oldValue) {
console.log("changes here")
}
},
data() {
return {
details: {
position: ""
}
}
}
It works if id value and name value are different:
<input type="password" class="form-control"name="password" id="mainpassword">
password: { required: true, } ,
cpassword: {required: true, equalTo: '#mainpassword' },
You can't: It's a security feature in all modern browsers.
For IE8, it's off by default, but can be reactivated using a security setting:
When a file is selected by using the input type=file object, the value of the value property depends on the value of the "Include local directory path when uploading files to a server" security setting for the security zone used to display the Web page containing the input object.
The fully qualified filename of the selected file is returned only when this setting is enabled. When the setting is disabled, Internet Explorer 8 replaces the local drive and directory path with the string C:\fakepath\ in order to prevent inappropriate information disclosure.
In all other current mainstream browsers I know of, it is also turned off. The file name is the best you can get.
More detailed info and good links in this question. It refers to getting the value server-side, but the issue is the same in JavaScript before the form's submission.
I was wondering, if there is any difference between RemoveAll
and Except
and the pros of using HashSet
, so I have done quick performance check :)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace ListRemoveTest
{
class Program
{
private static Random random = new Random( (int)DateTime.Now.Ticks );
static void Main( string[] args )
{
Console.WriteLine( "Be patient, generating data..." );
List<string> list = new List<string>();
List<string> toRemove = new List<string>();
for( int x=0; x < 1000000; x++ )
{
string randString = RandomString( random.Next( 100 ) );
list.Add( randString );
if( random.Next( 1000 ) == 0 )
toRemove.Insert( 0, randString );
}
List<string> l1 = new List<string>( list );
List<string> l2 = new List<string>( list );
List<string> l3 = new List<string>( list );
List<string> l4 = new List<string>( list );
Console.WriteLine( "Be patient, testing..." );
Stopwatch sw1 = Stopwatch.StartNew();
l1.RemoveAll( toRemove.Contains );
sw1.Stop();
Stopwatch sw2 = Stopwatch.StartNew();
l2.RemoveAll( new HashSet<string>( toRemove ).Contains );
sw2.Stop();
Stopwatch sw3 = Stopwatch.StartNew();
l3 = l3.Except( toRemove ).ToList();
sw3.Stop();
Stopwatch sw4 = Stopwatch.StartNew();
l4 = l4.Except( new HashSet<string>( toRemove ) ).ToList();
sw3.Stop();
Console.WriteLine( "L1.Len = {0}, Time taken: {1}ms", l1.Count, sw1.Elapsed.TotalMilliseconds );
Console.WriteLine( "L2.Len = {0}, Time taken: {1}ms", l1.Count, sw2.Elapsed.TotalMilliseconds );
Console.WriteLine( "L3.Len = {0}, Time taken: {1}ms", l1.Count, sw3.Elapsed.TotalMilliseconds );
Console.WriteLine( "L4.Len = {0}, Time taken: {1}ms", l1.Count, sw3.Elapsed.TotalMilliseconds );
Console.ReadKey();
}
private static string RandomString( int size )
{
StringBuilder builder = new StringBuilder();
char ch;
for( int i = 0; i < size; i++ )
{
ch = Convert.ToChar( Convert.ToInt32( Math.Floor( 26 * random.NextDouble() + 65 ) ) );
builder.Append( ch );
}
return builder.ToString();
}
}
}
Results below:
Be patient, generating data...
Be patient, testing...
L1.Len = 985263, Time taken: 13411.8648ms
L2.Len = 985263, Time taken: 76.4042ms
L3.Len = 985263, Time taken: 340.6933ms
L4.Len = 985263, Time taken: 340.6933ms
As we can see, best option in that case is to use RemoveAll(HashSet)
For Python 3.x
import urllib.request
from urllib.error import HTTPError
try:
urllib.request.urlretrieve(url, fullpath)
except urllib.error.HTTPError as err:
print(err.code)
Dave - any luck finding a solution to the browser problem? Is there a way to force a refresh?
As for the original problem, try the following when initializing the form:
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.base_fields['MyChoiceField'].initial = initial_value
Very simple:
<html>
<head>
<head>
<style type="text/css">
.buttonstyle
{
background: black;
background-position: 0px -401px;
border: solid 1px #000000;
color: #ffffff;
height: 21px;
margin-top: -1px;
padding-bottom: 2px;
}
.buttonstyle:hover {background: white;background-position: 0px -501px;color: #000000; }
</style>
</head>
<body>
<form>
<input class="buttonstyle" type="submit" name="submit" Value="Add Items"/>
</form>
</body>
</html>
This is working I have tested.
As everyone else has mentioned, the first task is to add the certificate to the Trusted Root Authority.
There is a custom exe (selfssl.exe) which will create a certificate and allow you to specify the Issued to: value (the URL). This means Internet explorer will validate the issued to url with the custom intranet url.
Make sure you restart Internet Explorer to refresh changes.
In a situation where you have this:
enum fruit {
apple,
orange,
grape,
banana,
// etc.
};
I like to put this in the header file where the enum is defined:
static inline char *stringFromFruit(enum fruit f)
{
static const char *strings[] = { "apple", "orange", "grape", "banana", /* continue for rest of values */ };
return strings[f];
}
I had an issue similar to this and found out is was due to a default .Net framework setting
Sqlcommand.Timeout
The default is 30 seconds as sated in the above url by Microsoft, try setting this to a higher number of seconds or maybe -1 before opening the connection to see if this solves the issue.
It maybe a setting in your web.config or app.config files or on you applicaiton / web server config files.
You forgot the .class
:
if (value.getClass() == Integer.class) {
System.out.println("This is an Integer");
}
else if (value.getClass() == String.class) {
System.out.println("This is a String");
}
else if (value.getClass() == Float.class) {
System.out.println("This is a Float");
}
Note that this kind of code is usually the sign of a poor OO design.
Also note that comparing the class of an object with a class and using instanceof is not the same thing. For example:
"foo".getClass() == Object.class
is false, whereas
"foo" instanceof Object
is true.
Whether one or the other must be used depends on your requirements.
A better JQuery answer would be:
$('#ParentContainer').scroll(function() {
$('#FixedDiv').animate({top:$(this).scrollTop()});
});
You can also add a number after scrollTop i.e .scrollTop() + 5 to give it buff.
A good suggestion would also to limit the duration to 100 and go from default swing to linear easing.
$('#ParentContainer').scroll(function() {
$('#FixedDiv').animate({top:$(this).scrollTop()},100,"linear");
})
the command to get the effective push remote for the branch, e.g., master, is:
git config branch.master.pushRemote || git config remote.pushDefault || git config branch.master.remote
Here's why (from the "man git config" output):
branch.name.remote [...] tells git fetch and git push which remote to fetch from/push to [...] [for push] may be overridden with remote.pushDefault (for all branches) [and] for the current branch [..] further overridden by branch.name.pushRemote [...]
For some reason, "man git push" only tells about branch.name.remote (even though it has the least precedence of the three) + erroneously states that if it is not set, push defaults to origin - it does not, it's just that when you clone a repo, branch.name.remote is set to origin, but if you remove this setting, git push will fail, even though you still have the origin remote
In new version it is like this:
def validate(self, attrs):
has_unknown_fields = set(self.initial_data) - set(self.fields.keys())
if has_unknown_fields:
raise serializers.ValidationError("Do not send extra fields")
return attrs
As an additional suggestion to what has been suggested, another clever way to provide functionality similar to multiple inheritance is implement multiple interfaces BUT then to provide extension methods on these interfaces. This is called mixins. It's not a real solution but it sometimes handles the issues that would prompt you to want to perform multiple inheritance.
If code doesn't generate any error, but you don't hear sound - create the player as an instance:
static var player: AVAudioPlayer!
For me the first solution worked when I did this change :)
The accepted answer is a bad idea in general because the manually created make.exe
will stick around and can potentially cause unexpected problems. It actually breaks RubyInstaller: https://github.com/oneclick/rubyinstaller2/issues/105
An alternative is installing make via Chocolatey (as pointed out by @Vasantha Ganesh K)
Another alternative is installing MSYS2 from Chocolatey and using make
from C:\tools\msys64\usr\bin
. If make
isn't installed automatically with MSYS2 you need to install it manually via pacman -S make
(as pointed out by @Thad Guidry and @Luke).
These answers are no longer recommended since try_files
works faster than if
in this context. Simply add try_files
in your php location block to test if the file exists, otherwise return a 404.
location ~ \.php {
try_files $uri =404;
...
}
Since we are doing this one to death - you don't have to specify a year:
select * from demo
where somedate between to_date('01/01 00:00:00', 'DD/MM HH24:MI:SS')
and to_date('31/12 23:59:59', 'DD/MM HH24:MI:SS');
However the accepted answer by FerranB makes more sense if you want to specify all date values that fall within the current year.
Since str_split()
function is not multibyte safe, an easy solution to split UTF-8 encoded string is to use preg_split()
with u (PCRE_UTF8)
modifier.
preg_split( '//u', $str, null, PREG_SPLIT_NO_EMPTY )
If your dictionaries are deeply nested and if they contain different types of collections, you could convert them to json string and compare.
import json
match = (json.dumps(dict1) == json.dumps(dict2))
caveat- this solution may not work if your dictionaries have binary strings in the values as this is not json serializable
Using jQuery UI in combination with the excellent datetimepicker plugin from http://trentrichardson.com/examples/timepicker/
You can specify the dateFormat and timeFormat
$('#datepicker').datetimepicker({
dateFormat: "yy-mm-dd",
timeFormat: "hh:mm:ss"
});
SQL> select substr('123456',-1,6) from dual;
S
-
6
SQL> select substr('123456',-6,6) from dual;
SUBSTR
------
123456
SQL> select substr('123456',-7,6) from dual;
S
-
If you watch above statements, 3 query gives null value as -7 > length('123456').
So check the length of CONT_PHONE_NUMBERS
and PHONE_NUMBERS
Hope this helps you
That error is a parse error. The parser is throwing it while going through the code, trying to understand it. No code is being executed yet in the parsing stage. Because of that it hasn't yet executed the error_reporting
line, therefore the error reporting settings aren't changed yet.
You cannot change error reporting settings (or really, do anything) in a file with syntax errors.
A tool that helps me a lot to debug ElasticSearch is ElasticHQ. Basically, it is an HTML file with some JavaScript. No need to install anywhere, let alone in ES itself: just download it, unzip int and open the HTML file with a browser.
Not sure it is the best tool for ES heavy users. Yet, it is really practical to whoever is in a hurry to see the entries.
SELECT * FROM MyTable WHERE Column1 Like "*word*"
This will display all the records where column1
has a partial value contains word
.
If you wants to know how aria-label
helps you practically .. then follow the steps ... you will get it by your own ..
Create a html page having below code
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
</head>
<body>
<button title="Close"> X </button>
<br />
<br />
<br />
<br />
<button aria-label="Back to the page" title="Close" > X </button>
</body>
</html>
Now, you need a virtual screen reader emulator which will run on browser to observe the difference. So, chrome browser users can install chromevox extension and mozilla users can go with fangs screen reader addin
Once done with installation, put headphones in your ears, open the html page and make focus on both button(by pressing tab) one-by-one .. and you can hear .. focusing on first x button
.. will tell you only x button
.. but in case of second x button
.. you will hear back to the page button
only..
i hope you got it well now!!
$('#dbType').change(function(){
var selection = $(this).val();
if(selection == 'other')
{
$('#otherType').show();
}
else
{
$('#otherType').hide();
}
});
BundleConfig
is nothing more than bundle configuration moved to separate file. It used to be part of app startup code (filters, bundles, routes used to be configured in one class)
To add this file, first you need to add the Microsoft.AspNet.Web.Optimization
nuget package to your web project:
Install-Package Microsoft.AspNet.Web.Optimization
Then under the App_Start folder create a new cs file called BundleConfig.cs
. Here is what I have in my mine (ASP.NET MVC 5, but it should work with MVC 4):
using System.Web;
using System.Web.Optimization;
namespace CodeRepository.Web
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
}
}
}
Then modify your Global.asax and add a call to RegisterBundles()
in Application_Start()
:
using System.Web.Optimization;
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
A closely related question: How to add reference to System.Web.Optimization for MVC-3-converted-to-4 app
Make sure that you aren't clicking on "Run unnamed" from 'run' tab. You must click on "run ". Or just click the green shortcut button.
This is exactly the feature I implemented in this lib XDDLib. (But, it's for android)
Lg.d("int array:", intArrayOf(1, 2, 3), "int list:", listOf(4, 5, 6))
One click on the underlined text to navigate to where the log command is
That StackTraceElement
is determined by the first element outside this library. Thus, anywhere outside this lib will be legal, including lambda expression
, static initialization block
, etc.
Maybe you want set -e
:
www.davidpashley.com/articles/writing-robust-shell-scripts.html#id2382181:
This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.
$id = intval($_GET['id']);
$sql = "SELECT * FROM student WHERE IDNO=$id";
$result = mysql_query($sql) or trigger_error(mysql_error().$sql);
always do it this way and it will tell you what is wrong
Use javascript's location.reload() method.
<script type="text/javascript">
function reloadPage()
{
window.location.reload()
}
</script>
You may want to use:
SELECT Name, 'Unpaid' AS Status FROM table;
The SELECT
clause syntax, as defined in MSDN: SELECT Clause (Transact-SQL), is as follows:
SELECT [ ALL | DISTINCT ]
[ TOP ( expression ) [ PERCENT ] [ WITH TIES ] ]
<select_list>
Where the expression
can be a constant, function, any combination of column names, constants, and functions connected by an operator or operators, or a subquery.
sudo xcode-select -s /Applications/Xcode 10.app/Contents/Developer
languoguangs-iMac:/ languoguang$ sudo xcode-select -s /Applications/Xcode 10.app/Contents/Developer
xcode-select: error: invalid argument '10.app/Contents/Developer'
Usage: xcode-select [options]
Print or change the path to the active developer directory. This directory
controls which tools are used for the Xcode command line tools (for example,
xcodebuild) as well as the BSD development commands (such as cc and make).
Options:
-h, --help print this help message and exit
-p, --print-path print the path of the active developer directory
-s <path>, --switch <path> set the path for the active developer directory
--install open a dialog for installation of the command line developer tools
-v, --version print the xcode-select version
-r, --reset reset to the default command line tools path
languoguangs-iMac:/ languoguang$ sudo xcode-select -s "/Applications/Xcode 10.app/Contents/Developer"
because my Xcode name in Application is "Xcode 10",
sudo xcode-select -s "/Applications/Xcode 10.app/Contents/Developer"
works.
You can use jsoup
to parse any kind of web page. Here you can find the jsoup library and full source code.
Here is an example: http://desicoding.blogspot.com/2011/03/how-to-parse-html-in-java-jsoup.html
To install in Eclipse:
You can parse according to tag/parent/child very comfortably
The unglue package provides an alternative, no knowledge about regular expressions is required for simple cases, here we'd do :
# install.packages("unglue")
library(unglue)
string = c("G1:E001", "G2:E002", "G3:E003")
unglue_vec(string,"{x}:{y}", var = "y")
#> [1] "E001" "E002" "E003"
Created on 2019-11-06 by the reprex package (v0.3.0)
More info : https://github.com/moodymudskipper/unglue/blob/master/README.md
Adding to https://stackoverflow.com/users/1638814/nvartolomei answer, which will probably fix your error.
Strictly answering your question, I just want to point out that the when:
statement is probably correct, but would look easier to read in multiline and still fulfill your logic:
when:
- sshkey_result.rc == 1
- github_username is undefined or
github_username |lower == 'none'
https://docs.ansible.com/ansible/latest/user_guide/playbooks_conditionals.html#the-when-statement
Delegate are essentially inline Action
's or Func<T>
. You can declare a delegate outside the scope of a method which you are running or using a lambda
expression(=>
); because you run the delegate within a method, you run it on the thread which is being run for the current window/application which is the bit in bold.
Lambda example
int AddFiveToNumber(int number)
{
var d = (int i => i + 5);
d.Invoke(number);
}
Rather than setting a flag, it could be more elegant to use JavaScript's Array.prototype.find
to find the matching item in the array. The loop will end as soon as a truthy value is returned from the callback, and the array value during that iteration will be the .find
call's return value:
function findXX(word) {
return someArray.find((item, i) => {
$('body').append('-> '+i+'<br />');
return item === word;
});
}
const someArray = new Array();
someArray[0] = 't5';
someArray[1] = 'z12';
someArray[2] = 'b88';
someArray[3] = 's55';
someArray[4] = 'e51';
someArray[5] = 'o322';
someArray[6] = 'i22';
someArray[7] = 'k954';
var test = findXX('o322');
console.log('found word:', test);
function findXX(word) {
return someArray.find((item, i) => {
$('body').append('-> ' + i + '<br />');
return item === word;
});
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
Step 1, delete all the *.DS_store
files. One can run
git rm -f *.DS_Store
but be aware that rm -f
can be a bit dangerous if you have a typo!
Step two: add
*.DS_Store
.DS_Store
to .gitignore. This worked for me!
you don't have to write any code. just before calling window.print() in the first time change the print settings of your browser. for example in firefox:
and one another example for IE (I'm using IE 11 for previous versions you can see this Prevent Firefox or Internet Explorer from Printing the URL on Every Page):
I encountered this problem today as well. I am using Windows and the system language by default is Chinese. Hence, someone may encounter this Unicode error similarly. Simply add encoding = 'utf-8'
:
with open("test.html", "r", encoding='utf-8') as f:
text= f.read()
if you use null values in your stored procedure, you will need to set the parameters to accept null values. That worked for me.
You can use python-docx2txt which is adapted from python-docx but can also extract text from links, headers and footers. It can also extract images.
If you use terminal to build and you have this error you can point to jdk bundled with android studio in your gradle.properties
file:
org.gradle.java.home=/usr/local/android-studio/jre
It's a new feature called Modules or "semantic import". There's more info in the WWDC 2013 videos for Session 205 and 404. It's kind of a better implementation of the pre-compiled headers. You can use modules with any of the system frameworks in iOS 7 and Mavericks. Modules are a packaging together of the framework executable and its headers and are touted as being safer and more efficient than #import
.
One of the big advantages of using @import
is that you don't need to add the framework in the project settings, it's done automatically. That means that you can skip the step where you click the plus button and search for the framework (golden toolbox), then move it to the "Frameworks" group. It will save many developers from the cryptic "Linker error" messages.
You don't actually need to use the @import
keyword. If you opt-in to using modules, all #import
and #include
directives are mapped to use @import
automatically. That means that you don't have to change your source code (or the source code of libraries that you download from elsewhere). Supposedly using modules improves the build performance too, especially if you haven't been using PCHs well or if your project has many small source files.
Modules are pre-built for most Apple frameworks (UIKit, MapKit, GameKit, etc). You can use them with frameworks you create yourself: they are created automatically if you create a Swift framework in Xcode, and you can manually create a ".modulemap" file yourself for any Apple or 3rd-party library.
You can use code-completion to see the list of available frameworks:
Modules are enabled by default in new projects in Xcode 5. To enable them in an older project, go into your project build settings, search for "Modules" and set "Enable Modules" to "YES". The "Link Frameworks" should be "YES" too:
You have to be using Xcode 5 and the iOS 7 or Mavericks SDK, but you can still release for older OSs (say iOS 4.3 or whatever). Modules don't change how your code is built or any of the source code.
From the WWDC slides:
- Imports complete semantic description of a framework
- Doesn't need to parse the headers
- Better way to import a framework’s interface
- Loads binary representation
- More flexible than precompiled headers
- Immune to effects of local macro definitions (e.g.
#define readonly 0x01
)- Enabled for new projects by default
To explicitly use modules:
Replace #import <Cocoa/Cocoa.h>
with @import Cocoa;
You can also import just one header with this notation:
@import iAd.ADBannerView;
The submodules autocomplete for you in Xcode.
If you want to fit other type of models, like a dose-response curve using logistic models you would also need to create more data points with the function predict if you want to have a smoother regression line:
fit: your fit of a logistic regression curve
#Create a range of doses:
mm <- data.frame(DOSE = seq(0, max(data$DOSE), length.out = 100))
#Create a new data frame for ggplot using predict and your range of new
#doses:
fit.ggplot=data.frame(y=predict(fit, newdata=mm),x=mm$DOSE)
ggplot(data=data,aes(x=log10(DOSE),y=log(viability)))+geom_point()+
geom_line(data=fit.ggplot,aes(x=log10(x),y=log(y)))
Here is one way to do this using css
HTML
<div class="imageWrapper">
<img src="http://lorempixel.com/300/300/" alt="" />
<a href="http://google.com" class="cornerLink">Link</a>
</div>?
CSS
.imageWrapper {
position: relative;
width: 300px;
height: 300px;
}
.imageWrapper img {
display: block;
}
.imageWrapper .cornerLink {
opacity: 0;
position: absolute;
bottom: 0px;
left: 0px;
right: 0px;
padding: 2px 0px;
color: #ffffff;
background: #000000;
text-decoration: none;
text-align: center;
-webkit-transition: opacity 500ms;
-moz-transition: opacity 500ms;
-o-transition: opacity 500ms;
transition: opacity 500ms;
}
.imageWrapper:hover .cornerLink {
opacity: 0.8;
}
Or if you just want it in the bottom left corner:
ng-model
ng-model directive in AngularJS is one of the greatest strength to bind the variables used in application with input components. This works as two way data binding. If you want to understand better about the two way bindings, you have an input component and the value updated into that field must be reflected in other part of the application. The better solution is to bind a variable to that field and output that variable whereever you wish to display the updated value throughoput the application.
ng-bind
ng-bind works much different than ng-model. ng-bind is one way data binding used for displaying the value inside html component as inner HTML. This directive can not be used for binding with the variable but only with the HTML elements content. Infact this can be used along with ng-model to bind the component to HTML elements. This directive is very useful for updating the blocks like div, span, etc. with inner HTML content.
This example would help you to understand.
If you are using JPA with EclipseLink, you'll have to set the @PrivateOwned annotation.
Documentation: Eclipse Wiki - Using EclipseLink JPA Extensions - Chapter 1.4 How to Use the @PrivateOwned Annotation
From the side of ZIP archive structure - you can update zip file without recompressing it, you will just need to skip all files which are prior of the file you need to replace, then put your updated file, and then the rest of the files. And finally you'll need to put the updated centeral directory structure. However, I doubt that most common tools would allow you to make this.
v4l support has been dropped in recent kernel versions (including the one shipped with Ubuntu 11.04).
EDIT: Your question is connected to a recent message that was sent to the OpenCV users group, which has instructions to compile OpenCV 2.2 in Ubuntu 11.04. Your approach is not ideal.
I came across this question while trying to answer the same question. McCrohan's approach with the classes array & join is solid.
Through my experience, I have been working with a lot of legacy ruby code that is being converted to React and as we build the component(s) up I find myself reaching out for both existing css classes and inline styles.
example snippet inside a component:
// if failed, progress bar is red, otherwise green
<div
className={`progress-bar ${failed ? failed' : ''}`}
style={{ width: this.getPercentage() }}
/>
Again, I find myself reaching out to legacy css code, "packaging" it with the component and moving on.
So, I really feel that it is a bit in the air as to what is "best" as that label will vary greatly depending on your project.
Copy the below code to a batch file and execute. Below requires Winzip to be installed/accessible from your machine. Do change variables as per your need.
@ECHO OFF
SET winzip_path="C:\Program Files\WinZip"
SET source_path="C:\Test"
SET output_path="C:\Output\"
SET log_file="C:\Test\unzip_log.txt"
SET file_name="*.zip"
cd %source_path%
echo Executing for %source_path% > %log_file%
FOR /f "tokens=*" %%G IN ('dir %file_name% /b') DO (
echo Processing : %%G
echo File_Name : %%G >> %log_file%
%winzip_path%\WINZIP32.EXE -e %%G %output_path%
)
PAUSE
solved my problem on mac 10.14
brew install android-sdk
Use content
:
#Library {
height: 70px;
width: 120px;
}
#Library:hover {
content: url('http://www.furrytalk.com/wp-content/uploads/2010/05/2.jpg');
height: 70px;
width: 120px;
}
I experienced a similar problem: after deleting the deployment (kubectl delete deploy <name>
), the pods kept "Running" and where automatically re-created after deletion (kubectl delete po <name>
).
It turned out that the associated replica set was not deleted automatically for some reason, and after deleting that (kubectl delete rs <name>
), it was possible to delete the pods.
You can also use a Subject and trigger its next() function from promise. See sample below:
Add code like below ( I used service )
class UserService {_x000D_
private createUserSubject: Subject < any > ;_x000D_
_x000D_
createUserWithEmailAndPassword() {_x000D_
if (this.createUserSubject) {_x000D_
return this.createUserSubject;_x000D_
} else {_x000D_
this.createUserSubject = new Subject < any > ();_x000D_
firebase.auth().createUserWithEmailAndPassword(email,_x000D_
password)_x000D_
.then(function(firebaseUser) {_x000D_
// do something to update your UI component_x000D_
// pass user object to UI component_x000D_
this.createUserSubject.next(firebaseUser);_x000D_
})_x000D_
.catch(function(error) {_x000D_
// Handle Errors here._x000D_
var errorCode = error.code;_x000D_
var errorMessage = error.message;_x000D_
this.createUserSubject.error(error);_x000D_
// ..._x000D_
});_x000D_
}_x000D_
_x000D_
}_x000D_
}
_x000D_
Create User From Component like below
class UserComponent {_x000D_
constructor(private userService: UserService) {_x000D_
this.userService.createUserWithEmailAndPassword().subscribe(user => console.log(user), error => console.log(error);_x000D_
}_x000D_
}
_x000D_
Followed Mark's advise and did this to set the default number formatting to text in the whole workbook:
$objPHPExcel = new PHPExcel();
$objPHPExcel->getDefaultStyle()
->getNumberFormat()
->setFormatCode(
PHPExcel_Style_NumberFormat::FORMAT_TEXT
);
And it works flawlessly. Thank you, Mark Baker.
Or can also insert the statement inside bracket.
SELECT * FROM tablename WHERE NOT (columnA = 'x')
You can issue the following query from the command line:
mysql -uUSER -p -e 'SHOW VARIABLES WHERE Variable_Name LIKE "%dir"'
Output (on Linux):
+---------------------------+----------------------------+
| Variable_name | Value |
+---------------------------+----------------------------+
| basedir | /usr |
| character_sets_dir | /usr/share/mysql/charsets/ |
| datadir | /var/lib/mysql/ |
| innodb_data_home_dir | |
| innodb_log_group_home_dir | ./ |
| lc_messages_dir | /usr/share/mysql/ |
| plugin_dir | /usr/lib/mysql/plugin/ |
| slave_load_tmpdir | /tmp |
| tmpdir | /tmp |
+---------------------------+----------------------------+
Output (on macOS Sierra):
+---------------------------+-----------------------------------------------------------+
| Variable_name | Value |
+---------------------------+-----------------------------------------------------------+
| basedir | /usr/local/mysql-5.7.17-macos10.12-x86_64/ |
| character_sets_dir | /usr/local/mysql-5.7.17-macos10.12-x86_64/share/charsets/ |
| datadir | /usr/local/mysql/data/ |
| innodb_data_home_dir | |
| innodb_log_group_home_dir | ./ |
| innodb_tmpdir | |
| lc_messages_dir | /usr/local/mysql-5.7.17-macos10.12-x86_64/share/ |
| plugin_dir | /usr/local/mysql/lib/plugin/ |
| slave_load_tmpdir | /var/folders/zz/zyxvpxvq6csfxvn_n000009800002_/T/ |
| tmpdir | /var/folders/zz/zyxvpxvq6csfxvn_n000009800002_/T/ |
+---------------------------+-----------------------------------------------------------+
Or if you want only the data dir use:
mysql -uUSER -p -e 'SHOW VARIABLES WHERE Variable_Name = "datadir"'
These commands work on Windows too, but you need to invert the single and double quotes.
Btw, when executing which mysql
in Linux as you told, you'll not get the installation directory on Linux. You'll only get the binary path, which is /usr/bin
on Linux, but you see the mysql installation is using multiple folders to store files.
If you need the value of datadir as output, and only that, without column headers etc, but you don't have a GNU environment (awk|grep|sed ...) then use the following command line:
mysql -s -N -uUSER -p information_schema -e 'SELECT Variable_Value FROM GLOBAL_VARIABLES WHERE Variable_Name = "datadir"'
The command will select the value only from mysql's internal information_schema
database and disables the tabular output and column headers.
Output on Linux:
/var/lib/mysql
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:MM");
simpleDateFormat.format(fajr_prayertime);
If you want the image to load and display a particular image, then use .src
to load that image URL.
If you want a piece of meta data (on any tag) that can contain a URL, then use data-src
or any data-xxx
that you want to select.
MDN documentation on data-xxxx attributes: https://developer.mozilla.org/en-US/docs/DOM/element.dataset
Example of src
on an image tag where the image loads the JPEG for you and displays it:
<img id="myImage" src="http://mydomain.com/foo.jpg">
<script>
var imageUrl = document.getElementById("myImage").src;
</script>
Example of 'data-src' on a non-image tag where the image is not loaded yet - it's just a piece of meta data on the div tag:
<div id="myDiv" data-src="http://mydomain.com/foo.jpg">
<script>
// in all browsers
var imageUrl = document.getElementById("myDiv").getAttribute("data-src");
// or in modern browsers
var imageUrl = document.getElementById("myDiv").dataset.src;
</script>
Example of data-src
on an image tag used as a place to store the URL of an alternate image:
<img id="myImage" src="http://mydomain.com/foo.jpg" data-src="http://mydomain.com/foo.jpg">
<script>
var item = document.getElementById("myImage");
// switch the image to the URL specified in data-src
item.src = item.dataset.src;
</script>
This should work. You may save the following in a batch file:
TASKKILL /F /IM chrome.exe
start chrome.exe --args --disable-web-security
pause
You can create a trigger which updates NoofUses
column in Coupon
table whenever
couponid
is used in CouponUse
table
query :
CREATE TRIGGER [dbo].[couponcount] ON [dbo].[couponuse]
FOR INSERT
AS
if EXISTS (SELECT 1 FROM Inserted)
BEGIN
UPDATE dbo.Coupon
SET NoofUses = (SELECT COUNT(*) FROM dbo.CouponUse WHERE Couponid = dbo.Coupon.ID)
end
I've create a solution, mixed the information of varius post.
Its a form, that contains a label and one textbox. The console output is redirected to the textbox.
There are too a class called ConsoleView that implements three publics methods: Show(), Close(), and Release(). The last one is for leave open the console and activate the Close button for view results.
The forms is called FrmConsole. Here are the XAML and the c# code.
The use is very simple:
ConsoleView.Show("Title of the Console");
For open the console. Use:
System.Console.WriteLine("The debug message");
For output text to the console.
Use:
ConsoleView.Close();
For Close the console.
ConsoleView.Release();
Leaves open the console and enables the Close button
XAML
<Window x:Class="CustomControls.FrmConsole"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:CustomControls"
mc:Ignorable="d"
Height="500" Width="600" WindowStyle="None" ResizeMode="NoResize" WindowStartupLocation="CenterScreen" Topmost="True" Icon="Images/icoConsole.png">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="40"/>
<RowDefinition Height="*"/>
<RowDefinition Height="40"/>
</Grid.RowDefinitions>
<Label Grid.Row="0" Name="lblTitulo" HorizontalAlignment="Center" HorizontalContentAlignment="Center" VerticalAlignment="Center" VerticalContentAlignment="Center" FontFamily="Arial" FontSize="14" FontWeight="Bold" Content="Titulo"/>
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="10"/>
</Grid.ColumnDefinitions>
<TextBox Grid.Column="1" Name="txtInner" FontFamily="Arial" FontSize="10" ScrollViewer.CanContentScroll="True" VerticalScrollBarVisibility="Visible" HorizontalScrollBarVisibility="Visible" TextWrapping="Wrap"/>
</Grid>
<Button Name="btnCerrar" Grid.Row="2" Content="Cerrar" Width="100" Height="30" HorizontalAlignment="Center" HorizontalContentAlignment="Center" VerticalAlignment="Center" VerticalContentAlignment="Center"/>
</Grid>
The code of the Window:
partial class FrmConsole : Window
{
private class ControlWriter : TextWriter
{
private TextBox textbox;
public ControlWriter(TextBox textbox)
{
this.textbox = textbox;
}
public override void WriteLine(char value)
{
textbox.Dispatcher.Invoke(new Action(() =>
{
textbox.AppendText(value.ToString());
textbox.AppendText(Environment.NewLine);
textbox.ScrollToEnd();
}));
}
public override void WriteLine(string value)
{
textbox.Dispatcher.Invoke(new Action(() =>
{
textbox.AppendText(value);
textbox.AppendText(Environment.NewLine);
textbox.ScrollToEnd();
}));
}
public override void Write(char value)
{
textbox.Dispatcher.Invoke(new Action(() =>
{
textbox.AppendText(value.ToString());
textbox.ScrollToEnd();
}));
}
public override void Write(string value)
{
textbox.Dispatcher.Invoke(new Action(() =>
{
textbox.AppendText(value);
textbox.ScrollToEnd();
}));
}
public override Encoding Encoding
{
get { return Encoding.UTF8; }
}
}
//DEFINICIONES DE LA CLASE
#region DEFINICIONES DE LA CLASE
#endregion
//CONSTRUCTORES DE LA CLASE
#region CONSTRUCTORES DE LA CLASE
public FrmConsole(string titulo)
{
InitializeComponent();
lblTitulo.Content = titulo;
Clear();
btnCerrar.Click += new RoutedEventHandler(BtnCerrar_Click);
Console.SetOut(new ControlWriter(txtInner));
DesactivarCerrar();
}
#endregion
//PROPIEDADES
#region PROPIEDADES
#endregion
//DELEGADOS
#region DELEGADOS
private void BtnCerrar_Click(object sender, RoutedEventArgs e)
{
Close();
}
#endregion
//METODOS Y FUNCIONES
#region METODOS Y FUNCIONES
public void ActivarCerrar()
{
btnCerrar.IsEnabled = true;
}
public void Clear()
{
txtInner.Clear();
}
public void DesactivarCerrar()
{
btnCerrar.IsEnabled = false;
}
#endregion
}
the code of ConsoleView class
static public class ConsoleView
{
//DEFINICIONES DE LA CLASE
#region DEFINICIONES DE LA CLASE
static FrmConsole console;
static Thread StatusThread;
static bool isActive = false;
#endregion
//CONSTRUCTORES DE LA CLASE
#region CONSTRUCTORES DE LA CLASE
#endregion
//PROPIEDADES
#region PROPIEDADES
#endregion
//DELEGADOS
#region DELEGADOS
#endregion
//METODOS Y FUNCIONES
#region METODOS Y FUNCIONES
public static void Show(string label)
{
if (isActive)
{
return;
}
isActive = true;
//create the thread with its ThreadStart method
StatusThread = new Thread(() =>
{
try
{
console = new FrmConsole(label);
console.ShowDialog();
//this call is needed so the thread remains open until the dispatcher is closed
Dispatcher.Run();
}
catch (Exception)
{
}
});
//run the thread in STA mode to make it work correctly
StatusThread.SetApartmentState(ApartmentState.STA);
StatusThread.Priority = ThreadPriority.Normal;
StatusThread.Start();
}
public static void Close()
{
isActive = false;
if (console != null)
{
//need to use the dispatcher to call the Close method, because the window is created in another thread, and this method is called by the main thread
console.Dispatcher.InvokeShutdown();
console = null;
StatusThread = null;
}
console = null;
}
public static void Release()
{
isActive = false;
if (console != null)
{
console.Dispatcher.Invoke(console.ActivarCerrar);
}
}
#endregion
}
I hope this result usefull.
In intellij8 I was using a specific plugin "Jar Tool" that is configurable and allows to pack a JAR archive.
Try this:
$(function() {
$("#type").change(function() {
if ($(this).val() === 'parcel') $("#row_dim").show();
else $("#row_dim").hide();
}
}
I had trouble running python app (running large dataframes) in 32 - got MemoryError message, while on 64 it worked fine.
@Autowired
private EntityManager entityManager;
@RequestMapping("/authors/{fname}/{lname}")
public List actionAutherMulti(@PathVariable("fname") String fname, @PathVariable("lname") String lname) {
return entityManager.createQuery("select A from Auther A WHERE A.firstName = ?1 AND A.lastName=?2")
.setParameter(1, fname)
.setParameter(2, lname)
.getResultList();
}
If possible use Visual Studio. The Microsoft SQL Server Data Tools (SSDT) bring a built in functionality for this since the March 2014 release:
Note: Be careful, the "View Data" window is just like SSMS "Edit Top 200 Rows"- you can edit data right away
(Tested with Visual Studio 2015 with Microsoft SQL Server Data Tools (SSDT) Version 14.0.60812.0 and Microsoft SQL Server 2012)
I love this answer. However, since next()
raise a StopIteration
exception when there are no items,
i would use the following snippet to avoid an exception:
a = []
item = next((x for x in a), None)
For example,
a = []
item = next(x for x in a)
Will raise a StopIteration
exception;
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
Node.js
introduced async await
in 7.6
so this makes Javascript
more beautiful.
var results = [];
var config = JSON.parse(queries);
for (var key in config) {
var query = config[key].query;
results.push(await search(query));
}
res.writeHead( ... );
res.end(results);
For this to work search
fucntion has to return a promise
or it has to be async
function
If it is not returning a Promise
you can help it to return a Promise
function asyncSearch(query) {
return new Promise((resolve, reject) => {
search(query,(result)=>{
resolve(result);
})
})
}
Then replace this line await search(query);
by await asyncSearch(query);
Below command worked for me:
sudo npm install -g appium --unsafe-perm=true --allow-root
Highlight the cells, format cells, select Custom then select zero.
Add an Application Configuration File
item to your project (Right -Click Project > Add item). This will create a file called app.config
in your project.
Edit the file by adding entries like <add key="keyname" value="someValue" />
within the <appSettings>
tag.
Add a reference to the System.Configuration
dll, and reference the items in the config using code like ConfigurationManager.AppSettings["keyname"]
.
Interesting I never spent too much time adjusting the colours in IntelliJ although tried once.
See link below with an already defined colour scheme you can import.
Where can I download IntelliJ IDEA 10 Color Schemes?
http://devnet.jetbrains.net/docs/DOC-1154
Download the jar file, file import the jar where you will see a what to import ;)
System.out.print("\"Hello\"");
The double quote character has to be escaped with a backslash in a Java string literal. Other characters that need special treatment include:
"\r"
and "\n"
"\\\\"
"\'"
"\t"
and "\f"
The complete list of Java string and character literal escapes may be found in the section 3.10.6 of the JLS.
It is also worth noting that you can include arbitrary Unicode characters in your source code using Unicode escape sequences of the form "\uxxxx" where the "x"s are hexadecimal digits. However, these are different from ordinary string and character escapes in that you can use them anywhere in a Java program ... not just in string and character literals; see JLS sections 3.1, 3.2 and 3.3 for a details on the use of Unicode in Java source code.
See also:
The Oracle Java Tutorial: Numbers and Strings - Characters
USE MyDB;
GO
ALTER SCHEMA dbo TRANSFER jonathan.MovieData;
GO
Ref: ALTER SCHEMA
let text:String = "Hello Friend"
let searchRange:NSRange = NSRange(location:0,length: text.characters.count)
let range:Range`<Int`> = Range`<Int`>.init(start: searchRange.location, end: searchRange.length)
Two ways to delete the image from public folder without changing laravel filesystems config file or messing with pure php unlink function:
- Using the default local storage you need to specify public subfolder:
Storage::delete('public/'.$image_path);
- Use public storage directly:
Storage::disk('public')->delete($image_path);
I would suggest second way as the best one.
Hope this help other people.
I have one solution, but I am not sure it is without flaws.
For it to work, you have to use the following structure:
Here is the code:
var TestClass =
(function () {
// difficult to be guessed.
var hash = Math.round(Math.random() * Math.pow(10, 13) + + new Date());
var TestClass = function () {
var privateFields = {
field1: 1,
field2: 2
};
this.getPrivateFields = function (hashed) {
if(hashed !== hash) {
throw "Cannot access private fields outside of object.";
// or return null;
}
return privateFields;
};
};
TestClass.prototype.prototypeHello = function () {
var privateFields = this.getPrivateFields(hash);
privateFields.field1 = Math.round(Math.random() * 100);
privateFields.field2 = Math.round(Math.random() * 100);
};
TestClass.prototype.logField1 = function () {
var privateFields = this.getPrivateFields(hash);
console.log(privateFields.field1);
};
TestClass.prototype.logField2 = function () {
var privateFields = this.getPrivateFields(hash);
console.log(privateFields.field2);
};
return TestClass;
})();
How this works is that it provides an instance function "this.getPrivateFields" to access the "privateFields" private variables object, but this function will only return the "privateFields" object inside the main closure defined (also prototype functions using "this.getPrivateFields" need to be defined inside this closure).
A hash produced during runtime and difficult to be guessed is used as parameters to make sure that even if "getPrivateFields" is called outside the scope of closure will not return the "privateFields" object.
The drawback is that we can not extend TestClass with more prototype functions outside the closure.
Here is some test code:
var t1 = new TestClass();
console.log('Initial t1 field1 is: ');
t1.logField1();
console.log('Initial t1 field2 is: ');
t1.logField2();
t1.prototypeHello();
console.log('t1 field1 is now: ');
t1.logField1();
console.log('t1 field2 is now: ');
t1.logField2();
var t2 = new TestClass();
console.log('Initial t2 field1 is: ');
t2.logField1();
console.log('Initial t2 field2 is: ');
t2.logField2();
t2.prototypeHello();
console.log('t2 field1 is now: ');
t2.logField1();
console.log('t2 field2 is now: ');
t2.logField2();
console.log('t1 field1 stays: ');
t1.logField1();
console.log('t1 field2 stays: ');
t1.logField2();
t1.getPrivateFields(11233);
EDIT: Using this method, it is also possible to "define" private functions.
TestClass.prototype.privateFunction = function (hashed) {
if(hashed !== hash) {
throw "Cannot access private function.";
}
};
TestClass.prototype.prototypeHello = function () {
this.privateFunction(hash);
};
If the script always outputs lines of 10 characters followed by 3 extra (in other words, you just want the first 10 characters), you can use
script | cut -c 1-10
If it outputs an uncertain number of non-space characters, followed by a space and then 2 other extra characters (in other words, you just want the first field), you can use
script | cut -d ' ' -f 1
... as in majhool's comment earlier. Depending on your platform, you may also have colrm, which, again, would work if the lines are a fixed length:
script | colrm 11