Windows Subsystem for Linux did not exist when this question was asked. It gave these results in my test:
uname -s -> Linux
uname -o -> GNU/Linux
uname -r -> 4.4.0-17763-Microsoft
This means that you need uname -r to distinguish it from native Linux.
I understand you have a scenario with ErrorDocument already defined within your apache conf or .htaccess and want to make those pages appear when manually sending a 4xx status code via php.
Unfortunately this is not possible with common methods because php sends header directly to user's browser (not to Apache web server) whereas ErrorDocument is a display handler for http status generated from Apache.
Slightly more compact:
df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df = df.sort_index()
print(df)
Note:
sort
has been deprecated, replaced by sort_index
for this scenarioinplace
as it is usually harder to read and prevents chaining. See explanation in answer here:
Pandas: peculiar performance drop for inplace rename after dropnaIn order to overcome
Ambiguous output in step `CR-LF..data'
simply solution might be to add -f
flag to force conversion.
Getting the correct URL for your camera seems to be the actual challenge!
I'm putting my working URL here, it might help someone.
The camera is EZVIZ C1C
with exact model cs-c1c-d0-1d2wf
. The working URL is
rtsp://admin:[email protected]/h264_stream
where SZGBZT
is the verification code found at the bottom of the camera. admin
is always admin
regardless of any settings or users you have.
The final code will be
video_capture = cv2.VideoCapture('rtsp://admin:[email protected]/h264_stream')
In languages that support regular expressions with non-capturing groups:
((?:[^/]*/)*)(.*)
I'll explain the gnarly regex by exploding it...
(
(?:
[^/]*
/
)
*
)
(.*)
What the parts mean:
( -- capture group 1 starts
(?: -- non-capturing group starts
[^/]* -- greedily match as many non-directory separators as possible
/ -- match a single directory-separator character
) -- non-capturing group ends
* -- repeat the non-capturing group zero-or-more times
) -- capture group 1 ends
(.*) -- capture all remaining characters in group 2
To test the regular expression, I used the following Perl script...
#!/usr/bin/perl -w
use strict;
use warnings;
sub test {
my $str = shift;
my $testname = shift;
$str =~ m#((?:[^/]*/)*)(.*)#;
print "$str -- $testname\n";
print " 1: $1\n";
print " 2: $2\n\n";
}
test('/var/log/xyz/10032008.log', 'absolute path');
test('var/log/xyz/10032008.log', 'relative path');
test('10032008.log', 'filename-only');
test('/10032008.log', 'file directly under root');
The output of the script...
/var/log/xyz/10032008.log -- absolute path
1: /var/log/xyz/
2: 10032008.log
var/log/xyz/10032008.log -- relative path
1: var/log/xyz/
2: 10032008.log
10032008.log -- filename-only
1:
2: 10032008.log
/10032008.log -- file directly under root
1: /
2: 10032008.log
This is an issue in the Chrome family and has been there forever.
A bug has been raised https://bugs.chromium.org/p/chromium/issues/detail?id=904208
It can be shown here: https://codepen.io/anon/pen/Jedvwj as soon as you add a border to anything button-like (say role="button" has been added to a tag for example) Chrome messes up and sets the focus state when you click with your mouse. You should see that outline only on keyboard tab-press.
I highly recommend using this fix: https://github.com/wicg/focus-visible.
Just do the following
npm install --save focus-visible
Add the script to your html:
<script src="/node_modules/focus-visible/dist/focus-visible.min.js"></script>
or import into your main entry file if using webpack or something similar:
import 'focus-visible/dist/focus-visible.min';
then put this in your css file:
// hide the focus indicator if element receives focus via mouse, but show on keyboard focus (on tab).
.js-focus-visible :focus:not(.focus-visible) {
outline: none;
}
// Define a strong focus indicator for keyboard focus.
// If you skip this then the browser's default focus indicator will display instead
// ideally use outline property for those users using windows high contrast mode
.js-focus-visible .focus-visible {
outline: magenta auto 5px;
}
You can just set:
button:focus {outline:0;}
but if you have a large number of users, you're disadvantaging those who cannot use mice or those who just want to use their keyboard for speed.
Use this:
$('#navigation ul li').css('display', 'inline-block');
Also, as others have stated, if you want to make multiple css changes at once, that's when you would add the curly braces (for object notation), and it would look something like this (if you wanted to change, say, 'background-color' and 'position' in addition to 'display'):
$('#navigation ul li').css({'display': 'inline-block', 'background-color': '#fff', 'position': 'relative'}); //The specific CSS changes after the first one, are, of course, just examples.
This is not exactly what you were asking about and it can only be used from the command line (and may be useless in a batch file), but one quick way to check file size is just to use dir
:
> dir Microsoft.WindowsAzure.Storage.xml
Results in:
Directory of C:\PathToTheFile
08/10/2015 10:57 AM 2,905,897 Microsoft.WindowsAzure.Storage.xml
1 File(s) 2,905,897 bytes
0 Dir(s) 759,192,064,000 bytes free
All of the answers above are correct; attr_reader
and attr_writer
are more convenient to write than manually typing the methods they are shorthands for. Apart from that they offer much better performance than writing the method definition yourself. For more info see slide 152 onwards from this talk (PDF) by Aaron Patterson.
I have a better way:
http
.authorizeRequests()
.antMatchers("/api/v1/signup/**").permitAll()
.anyRequest().authenticated()
Here is another way of doing it, similar to Dan Allan's answer but without the lambda function:
>>> pd.options.display.float_format = '{:.2f}'.format
>>> Series(np.random.randn(3))
0 0.41
1 0.99
2 0.10
or
>>> pd.set_option('display.float_format', '{:.2f}'.format)
SELECT MAX(LEN(Desc)) as MaxLen FROM table
Try this:
x = a > b and 10 or 11
This is a sample of execution:
>>> a,b=5,7
>>> x = a > b and 10 or 11
>>> print x
11
Here's a suggestion: use two indices into the string, say start
and end
. start
points to the first character of the next string to extract, end
points to the character after the last one belonging to the next string to extract. start
starts at zero, end
gets the position of the first char after start
. Then you take the string between [start..end)
and add that to your array. You keep going until you hit the end of the string.
Another way, in jQuery, would be to get the inner height, inner width and positioning of the containing DIV, and simply overlay another DIV, transparent, over the top the same size. This will work on all elements inside that container, instead of only the inputs.
Remember though, with JS disabled, you'll still be able to use the DIVs inputs/content. The same goes with the above answers too.
As mscdex said NPM comes with the nodejs msi installed file. I happened to just install the node js installer (standalone). To separately add NPM I followed following step
The best way is to use IN
statement :
DELETE from tablename WHERE id IN (1,2,3,...,254);
You can also use BETWEEN
if you have consecutive IDs :
DELETE from tablename WHERE id BETWEEN 1 AND 254;
You can of course limit for some IDs using other WHERE clause :
DELETE from tablename WHERE id BETWEEN 1 AND 254 AND id<>10;
I did using in-app updates. This will only with devices running Android 5.0 (API level 21) or higher,
I know this is an old question, but I had this problem recently and none of the answers helped me. However, Corral's comment on Ryan Atkinson's answer did tip me off to the problem.
I had all my compiled class files in target/classes
, which are not packages in my case. I was trying to package it with jar cvfe App.jar target/classes App
, from the root directory of my project, as my App class was in the default unnamed package.
This doesn't work, as the newly created App.jar
will have the class App.class
in the directory target/classes
. If you try to run this jar with java -jar App.jar
, it will complain that it cannot find the App
class. This is because the packages inside App.jar
don't match the actual packages in the project.
This could be solved by creating the jar directly from the target/classes
directory, using jar cvfe App.jar . App
. This is rather cumbersome in my opinion.
The simple solution is to list the folders you want to add with the -C
option instead of using the default way of listing folders. So, in my case, the correct command is java cvfe App.jar App -C target/classes .
. This will directly add all files in the target/classes
directory to the root of App.jar
, thus solving the problem.
You could use a css class too.
$('#hook').parent().parent().parent().siblings().addClass("class_name");
Good day!
** Update ** A scalars converter has been added to retrofit that allows for a String
response with less ceremony than my original answer below.
Example interface --
public interface GitHubService {
@GET("/users/{user}")
Call<String> listRepos(@Path("user") String user);
}
Add the ScalarsConverterFactory
to your retrofit builder. Note: If using ScalarsConverterFactory
and another factory, add the scalars factory first.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
// add other factories here, if needed.
.build();
You will also need to include the scalars converter in your gradle file --
implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'
--- Original Answer (still works, just more code) ---
I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject
land. I suspect your specific problem might be better solved using a custom gson TypeAdapter
or a retrofit Converter
if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -
First, if you are using Retrofit 2, you should start using the Call
API. Instead of sending an object to convert as the type parameter, use ResponseBody
from okhttp --
public interface GitHubService {
@GET("/users/{user}")
Call<ResponseBody> listRepos(@Path("user") String user);
}
then you can create and execute your call --
GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Response<ResponseBody> response) {
try {
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Throwable t) {
e.printStackTrace();
}
});
Note The code above calls string()
on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream()
instead. See the ResponseBody
docs.
I think you probably want to view the minification of each set of css as a separate task
task minifyBrandACss(type: com.eriwen.gradle.css.tasks.MinifyCssTask) {
source = "src/main/webapp/css/brandA/styles.css"
dest = "${buildDir}/brandA/styles.css"
}
etc etc
BTW executing your minify tasks in an action of the war task seems odd to me - wouldn't it make more sense to make them a dependency of the war task?
Read the Request.Form NameValueCollection and process your logic accordingly:
NameValueCollection nvc = Request.Form;
string userName, password;
if (!string.IsNullOrEmpty(nvc["txtUserName"]))
{
userName = nvc["txtUserName"];
}
if (!string.IsNullOrEmpty(nvc["txtPassword"]))
{
password = nvc["txtPassword"];
}
//Process login
CheckLogin(userName, password);
... where "txtUserName" and "txtPassword" are the Names of the controls on the posting page.
If your shell supports it, would something like this work ?
javac com/**/*.java
If your shell does not support **
, then maybe
javac com/*/*/*.java
works (for all packages with 3 components - adapt for more or less).
You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.
I used CountIf below, but there is lots of different ways to check existence of a value in a range.
Public Sub test()
Dim rng As Range
Dim aNumber As Long
aNumber = 666
Set rng = Sheet5.Range("B16:B615")
If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then
rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)
Else
MsgBox aNumber & " does not exist in range " & rng.Address
End If
End Sub
ALTERNATIVE WAY
Public Sub test()
Dim rng As Range
Dim aNumber As Variant
Dim rowNum As Long
aNumber = "2gg"
Set rng = Sheet5.Range("B1:B20")
If Not IsError(Application.Match(aNumber, rng, 0)) Then
rowNum = Application.Match(aNumber, rng, 0)
MsgBox rowNum
Else
MsgBox "error"
End If
End Sub
OR
Public Sub test()
Dim rng As Range
Dim aNumber As Variant
Dim rowNum As Variant
aNumber = "2gg"
Set rng = Sheet5.Range("B1:B20")
rowNum = Application.Match(aNumber, rng, 0)
If Not IsError(rowNum) Then
MsgBox rowNum
Else
MsgBox "error"
End If
End Sub
There are two ways to do this. One is very simple but unsafe:
Map<String, Object> map = new HashMap<String, Object>();
Map<String, String> newMap = new HashMap<String, String>((Map)map); // unchecked warning
The other way has no compiler warnings and ensures type safety at runtime, which is more robust. (After all, you can't guarantee the original map contains only String values, otherwise why wouldn't it be Map<String, String>
in the first place?)
Map<String, Object> map = new HashMap<String, Object>();
Map<String, String> newMap = new HashMap<String, String>();
@SuppressWarnings("unchecked") Map<String, Object> intermediate =
(Map)Collections.checkedMap(newMap, String.class, String.class);
intermediate.putAll(map);
@media only screen and (min-width : 320px) and (max-width : 480px) {/*--- Mobile portrait ---*/}
@media only screen and (min-width : 480px) and (max-width : 595px) {/*--- Mobile landscape ---*/}
@media only screen and (min-width : 595px) and (max-width : 690px) {/*--- Small tablet portrait ---*/}
@media only screen and (min-width : 690px) and (max-width : 800px) {/*--- Tablet portrait ---*/}
@media only screen and (min-width : 800px) and (max-width : 1024px) {/*--- Small tablet landscape ---*/}
@media only screen and (min-width : 1024px) and (max-width : 1224px) {/*--- Tablet landscape --- */}
You'll need the SQL Server Configuration Manager. Go to Sql Native Client Configuration, Select Client Protocols, Right Click on TCP/IP and set your default port there.
Going to provide a slightly different answer to those provided so far.
If you have a row for an anonymous user from localhost in your users table ''@'localhost'
then this will be treated as more specific than your user with wildcard'd host 'user'@'%'
. This is why it is necessary to also provide 'user'@'localhost'
.
You can see this explained in more detail at the bottom of this page.
In case, your data is in the following structure, you get string as an index
items = {
am:"Amharic",
ar:"Arabic",
az:"Azerbaijani",
ba:"Bashkir",
be:"Belarusian"
}
In this case, you can use extra variable to get the index in number:
<ul>
<li v-for="(item, key, index) in items">
{{ item }} - {{ key }} - {{ index }}
</li>
</ul>
I wasn't thinking this was my issue at first but in running through this list I discovered that it didn't cover what my issues was.
My issue was that I had a bug in which it tried to write the same record numerous times using entity framework. It shouldn't have been doing this; it was my bug. Take a look at the data you are writing. My thoughts are that SQL was busy writing a record, possibly locking and creating the timeout. After I fixed the area of code that was attempting to write the record multiple in sequential attempts, the error went away.
If you want to add different border on different sides, may be add a subview with the specific style is a way easy to come up with.
I also had a same requirement to delete an element from array which is in state.
const array= [...this.state.selectedOption]
const found= array.findIndex(x=>x.index===k)
if(found !== -1){
this.setState({
selectedOption:array.filter(x => x.index !== k)
})
}
First I copied the elements into an array. Then checked whether the element exist in the array or not. Then only I have deleted the element from the state using the filter option.
You're using curvy-braces when you should be using parentheses.
A where statement is kept inside a scriptblock, which is defined using curvy baces { }
. To isolate/wrap you tests, you should use parentheses ()
.
I would also suggest trying to do the filtering on the remote computer. Try:
Invoke-Command -computername SERVERNAME {
Get-ChildItem -path E:\dfsroots\datastore2\public |
Where-Object { ($_.extension -eq "xls" -or $_.extension -eq "xlk") -and $_.creationtime -ge "06/01/2014" }
}
It's a logic bomb, it keeps recreating itself and takes up all your CPU resources. It overloads your computer with too many processes and it forces it to shut down. If you make a batch file with this in it and start it you can end it using taskmgr. You have to do this pretty quickly or your computer will be too slow to do anything.
In my case I used google play services...I increase library service it solved
implementation 'com.google.android.gms:play-services-auth:16.0.0'
Google play service must be same in library and app modules
Using rcParams you can show grid very easily as follows
plt.rcParams['axes.facecolor'] = 'white'
plt.rcParams['axes.edgecolor'] = 'white'
plt.rcParams['axes.grid'] = True
plt.rcParams['grid.alpha'] = 1
plt.rcParams['grid.color'] = "#cccccc"
If grid is not showing even after changing these parameters then use
plt.grid(True)
before calling
plt.show()
Sormula supports SQL IN operator by allowing you to supply a java.util.Collection object as a parameter. It creates a prepared statement with a ? for each of the elements the collection. See Example 4 (SQL in example is a comment to clarify what is created but is not used by Sormula).
Click on Manage Certificates->Apple Distribution->Done
I encountered this error when running my Android app on my home WiFi, then trying to run it on different WiFi without closing my simulator.
Simply closing the simulator and re-launching the app worked for me!
.md
extension stands for Markdown, which Github uses, among others, to format those files.
Read about Markdown:
http://daringfireball.net/projects/markdown/
http://en.wikipedia.org/wiki/Markdown
Also:
If you committed the merge:
git reset HEAD~1
# Make sure what you are reverting is in fact the merge files
git add .
git reset --hard
You install a new version of R from the official website.
RStudio should automatically start with the new version when you relaunch it.
In case you need to do it manually, in RStudio, go to :Tools -> options -> General.
Check @micstr's answer for a more detailed walkthrough.
This would be really bad to do because sharing your connection string opens up your website to so many vulnerabilities that you can't simply patch up, you have to use a different method if you want it to be secure. Otherwise you are opening up to a huge audience to take advantage of your site.
#include <string.h>
...
char otherString[6]; // note 6, not 5, there's one there for the null terminator
...
strncpy(otherString, someString, 5);
otherString[5] = '\0'; // place the null terminator
If you accidentally reset your keychain, this can occur due to missing Apple certificates in the keychain. I followed the answer on this to solve my problem.
I had the same issue and was able to fix by re-downloading the WWDR (Apple Worldwide Developer Relations Certification Authority). Download from here: http://developer.apple.com/certificationauthority/AppleWWDRCA.cer
&& and || are short circuit operators operating on scalars. & and | operate on arrays, and use short-circuiting only in the context of if
or while
loop expressions.
With this code, you only change rows backcolor where columname value is null other rows color still the default one.
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells["columnname"].Value != null)
{
dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.MistyRose;
}
}
From your question, I think it is safe to assume you have CASCADING DELETES turned on.
All that is needed in that case is
DELETE FROM MainTable
WHERE PrimaryKey = ???
You database engine will take care of deleting the corresponding referencing records.
Note the difference with the added "?" character after ".php", especially when dealing with CodeIgniter:
RewriteRule ^(.*)$ index.php/$1 [L]
vs.
RewriteRule ^(.*)$ index.php?/$1 [L]
It depends on several other things.. if doesn't work, try the other option!
You can use Date.parse(), but the input formats that it accepts are implementation-dependent. However, if you can convert the date to ISO format (YYYY-MM-DD), most implementations should understand it.
I never understood why this makes a difference for the compiler, but this is sufficient.
public static class ControlExtensions
{
public static void Invoke(this Control control, Action action)
{
control.Invoke(action);
}
}
Bonus: add some error handling, because it is likely that, if you are using Control.Invoke
from a background thread you are updating the text / progress / enabled state of a control and don't care if the control is already disposed.
public static class ControlExtensions
{
public static void Invoke(this Control control, Action action)
{
try
{
if (!control.IsDisposed) control.Invoke(action);
}
catch (ObjectDisposedException) { }
}
}
Use std::printf and c_str() example:
std::printf("Follow this command: %s", myString.c_str());
Assuming you are programming in Java, this works:
if (90 >= angle && angle <= 180 ) {
(don't you mean 90 is less than angle
? If so: 90 <= angle
)
since you followed the tutorial, I presume you have a screen that says Hello World.
that means you have some code in your layout xml that looks like this
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
you want to display an image, so instead of TextView you want to have ImageView. and instead of a text attribute you want an src attribute, that links to your drawable resource
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/cool_pic"
/>
Try gzipping some data through the gzip libary like this...
import gzip
content = "Lots of content here"
f = gzip.open('Onlyfinnaly.log.gz', 'wb')
f.write(content)
f.close()
... then run your code as posted ...
import gzip
f=gzip.open('Onlyfinnaly.log.gz','rb')
file_content=f.read()
print file_content
This method worked for me as for some reason the gzip library fails to read some files.
If data already exists in the column you should do:
ALTER TABLE tbl_name ALTER COLUMN col_name TYPE integer USING col_name::integer;
As pointed out by @nobu and @jonathan-porter in comments to @derek-kromm's answer.
A more up to date answer for anyone else who comes across this:
(from https://www.jetbrains.com/help/idea/eclipse.html, §Auto-compilation; click for screenshots)
Compile automatically:
To enable automatic compilation, navigate to Settings/Preferences | Build, Execution, Deployment | Compiler and select the Build project automatically option
Show all errors in one place:
The Problems tool window appears if the Make project automatically option is enabled in the Compiler settings. It shows a list of problems that were detected on project compilation.
Use the Eclipse compiler: This is actually bundled in IntelliJ. It gives much more useful error messages, in my opinion, and, according to this blog, it's much faster since it was designed to run in the background of an IDE and uses incremental compilation.
While Eclipse uses its own compiler, IntelliJ IDEA uses the javac compiler bundled with the project JDK. If you must use the Eclipse compiler, navigate to Settings/Preferences | Build, Execution, Deployment | Compiler | Java Compiler and select it... The biggest difference between the Eclipse and javac compilers is that the Eclipse compiler is more tolerant to errors, and sometimes lets you run code that doesn't compile.
To save hours of coding time, use a jquery plug-in already optimized for embedded video iframes.
I spent a couple days trying to integrate Vimeo's moogaloop API with jquery tools unsuccessfully. See this list for a handful of easier options.
Suggestion: format a FRAMESET HTML page which contains, let´s say, 9 frames inside. Each frame will GET a different "instance" of your myapp.php page. There will be 9 different threads running on the Web server, in parallel.
Another way, you can use a pass-through object to capture the last value and then do something with it:
List<Integer> list = new ArrayList<Integer>();
Integer lastValue = null;
for (Integer i : list) {
// do stuff
lastValue = i;
}
// do stuff with last value
I have Mojave 10.14.6 and the only thing that did work for me was:
export JAVA_HOME=/Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin/Contents/Home
Hope it helps! You can now type java --version
and it should work
There are different methods to open or close winform. Form.Close() is one method in closing a winform.
When 'Form.Close()' execute , all resources created in that form are destroyed. Resources means control and all its child controls (labels , buttons) , forms etc.
Some other methods to close winform
Some methods to Open/Start a form
All of them act differently , Explore them !
.circle {
border-radius: 50%;
width: 500px;
height: 500px;
background: red;
}
<div class="circle"></div>
see this FIDDLE
Technically, Node.js isn't proper JavaScript as we know it, since there isn't a Document Object Model (DOM). For instance, JavaScript scripts that run in the browser will not work. At all. The solution would be to run JavaScript with a headless browser. Fortunately there is a project still active: Mozilla Firefox has a headless mode.
https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Headless_mode
$ /Applications/Firefox.app/Contents/MacOS/firefox -headless index.html
*** You are running in headless mode.
you can find the opencv_core248 and other dlls in opencv\build\x86\vc12\bin folder. Just copy the dlls you require into system32 folder. And your app should start working in a flash ! Hope it helps.
Here is another modification of the most popular answer, but with handling of variable length of text in the first column labels: http://jsfiddle.net/ozx56n41/
Basically, I'm using the second column for creating row height, like was mentioned. But my fiddle actually works unlike most mentioned above.
HTML:
<div id="outerdiv">
<div id="innerdiv">
<table>
<tr>
<td class="headcol"><div>This is a long label</div></td>
<td class="hiddenheadcol"><div>This is a long label</div></td>
<td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
<td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
</tr>
<tr>
<td class="headcol"><div>Short label</div></td>
<td class="hiddenheadcol"><div>Short label</div></td>
<td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
<td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
</tr>
</table>
</div>
</div>
CSS:
body {
font: 16px Calibri;
}
#outerdiv {
position: absolute;
top: 0;
left: 0;
right: 0;
width: 100%;
border-top: 1px solid grey;
}
#innerdiv {
overflow-x: scroll;
margin-left: 100px;
overflow-y: visible;
padding-bottom: 1px;
}
table {
border-collapse:separate;
}
td {
margin: 0;
border: 1px solid grey;
border-top-width: 0;
border-left-width: 0px;
padding: 10px;
}
td.headcol {
/* Frozen 1st column */
position: absolute;
left: 0;
top: auto;
border-bottom-width: 1px;
padding: 0;
border-left-width: 1px;
}
td.hiddenheadcol {
/* Hidden 2nd column to create height */
max-width: 0;
visibility: hidden;
padding: 0;
}
td.headcol div {
/* Text container in the 1st column */
width: 100px;
max-width: 100px;
background: lightblue;
padding: 10px;
box-sizing: border-box;
}
td.hiddenheadcol div {
/* Text container in the 2nd column */
width: 100px;
max-width: 100px;
background: red;
padding: 10px;
}
td.long {
background:yellow;
letter-spacing:1em;
}
Solved it. Turns out the column had a limited set of characters it would accept, changed it, and now the query works fine.
Basically, it will make your code a lot easier to compile under other compilers which also implement the ANSI standard, and, if you are careful in which libraries/api calls you use, under other operating systems/platforms.
The first one, turns off SPECIFIC features of GCC. (-ansi) The second one, will complain about ANYTHING at all that does not adhere to the standard (not only specific features of GCC, but your constructs too.) (-pedantic).
It seems like there is permission on mobile keypad setting, so the easiest way to do this is:
editText.setFilters(new InputFilter[]{new InputFilter.AllCaps()});
hope this will work
Below are some reasons arguing for the use of the pattern and example code in Java, but it is an implementation of the Builder Pattern covered by the Gang of Four in Design Patterns. The reasons you would use it in Java are also applicable to other programming languages as well.
As Joshua Bloch states in Effective Java, 2nd Edition:
The builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters.
We've all at some point encountered a class with a list of constructors where each addition adds a new option parameter:
Pizza(int size) { ... }
Pizza(int size, boolean cheese) { ... }
Pizza(int size, boolean cheese, boolean pepperoni) { ... }
Pizza(int size, boolean cheese, boolean pepperoni, boolean bacon) { ... }
This is called the Telescoping Constructor Pattern. The problem with this pattern is that once constructors are 4 or 5 parameters long it becomes difficult to remember the required order of the parameters as well as what particular constructor you might want in a given situation.
One alternative you have to the Telescoping Constructor Pattern is the JavaBean Pattern where you call a constructor with the mandatory parameters and then call any optional setters after:
Pizza pizza = new Pizza(12);
pizza.setCheese(true);
pizza.setPepperoni(true);
pizza.setBacon(true);
The problem here is that because the object is created over several calls it may be in an inconsistent state partway through its construction. This also requires a lot of extra effort to ensure thread safety.
The better alternative is to use the Builder Pattern.
public class Pizza {
private int size;
private boolean cheese;
private boolean pepperoni;
private boolean bacon;
public static class Builder {
//required
private final int size;
//optional
private boolean cheese = false;
private boolean pepperoni = false;
private boolean bacon = false;
public Builder(int size) {
this.size = size;
}
public Builder cheese(boolean value) {
cheese = value;
return this;
}
public Builder pepperoni(boolean value) {
pepperoni = value;
return this;
}
public Builder bacon(boolean value) {
bacon = value;
return this;
}
public Pizza build() {
return new Pizza(this);
}
}
private Pizza(Builder builder) {
size = builder.size;
cheese = builder.cheese;
pepperoni = builder.pepperoni;
bacon = builder.bacon;
}
}
Note that Pizza is immutable and that parameter values are all in a single location. Because the Builder's setter methods return the Builder object they are able to be chained.
Pizza pizza = new Pizza.Builder(12)
.cheese(true)
.pepperoni(true)
.bacon(true)
.build();
This results in code that is easy to write and very easy to read and understand. In this example, the build method could be modified to check parameters after they have been copied from the builder to the Pizza object and throw an IllegalStateException if an invalid parameter value has been supplied. This pattern is flexible and it is easy to add more parameters to it in the future. It is really only useful if you are going to have more than 4 or 5 parameters for a constructor. That said, it might be worthwhile in the first place if you suspect you may be adding more parameters in the future.
I have borrowed heavily on this topic from the book Effective Java, 2nd Edition by Joshua Bloch. To learn more about this pattern and other effective Java practices I highly recommend it.
Use encodeURI()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI
Escapes pretty much all problematic characters in strings for proper JSON encoding and transit for use in web applications. It's not a perfect validation solution but it catches the low-hanging fruit.
Linked List Class
class LinkedStack:
# Nested Node Class
class Node:
def __init__(self, element, next):
self.__element = element
self.__next = next
def get_next(self):
return self.__next
def get_element(self):
return self.__element
def __init__(self):
self.head = None
self.size = 0
self.data = []
def __len__(self):
return self.size
def __str__(self):
return str(self.data)
def is_empty(self):
return self.size == 0
def push(self, e):
newest = self.Node(e, self.head)
self.head = newest
self.size += 1
self.data.append(newest)
def top(self):
if self.is_empty():
raise Empty('Stack is empty')
return self.head.__element
def pop(self):
if self.is_empty():
raise Empty('Stack is empty')
answer = self.head.element
self.head = self.head.next
self.size -= 1
return answer
Usage
from LinkedStack import LinkedStack
x = LinkedStack()
x.push(10)
x.push(25)
x.push(55)
for i in range(x.size - 1, -1, -1):
print '|', x.data[i].get_element(), '|' ,
#next object
if x.data[i].get_next() == None:
print '--> None'
else:
print x.data[i].get_next().get_element(), '-|----> ',
Output
| 55 | 25 -|----> | 25 | 10 -|----> | 10 | --> None
There is an issue with the Command + F solution. It will replace all 0's if you click replace all. This means if you do not review every zero, zero's contained in important cells will also be removed. For example, if you have phone numbers that have (420) area codes they will all be changed to (40).
For Perfect DateTime
Match in SQL Server
SELECT ID FROM [Table Name] WHERE (DateLog between '2017-02-16 **00:00:00.000**' and '2017-12-16 **23:59:00.999**') ORDER BY DateLog DESC
The default (when created with the designer) is:
label.ForeColor = SystemColors.ControlText;
This should respect the system color settings (e.g. these "high contrast" schemes for visual impaired).
Nothing stops you from doing
moveUp = moveDown = moveLeft = moveRight = mouseDown = touchDown = false;
Check this example
var a, b, c;_x000D_
a = b = c = 10;_x000D_
console.log(a + b + c)
_x000D_
In my case the problem was the DateTime
object I was sending. I created a DateTime
with "yyyy-MM-dd", and the DateTime
that was required by the object I was mapping to needed "HH-mm-ss" aswell. So appending "00-00" solved the problem (the full item was null because of this).
Here is a sample code:
<?php
$sql="select * from Posts limit 20";
$response = array();
$posts = array();
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)) {
$title=$row['title'];
$url=$row['url'];
$posts[] = array('title'=> $title, 'url'=> $url);
}
$response['posts'] = $posts;
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);
?>
Sometimes this syntax wont work:
df[['col1','col2']] = df[['col1','col2']].fillna()
Use the following instead:
df['col1','col2']
I solved this problem by removing --deploy-mode cluster from spark-submit code. By default , spark submit takes client mode which has following advantage :
1. It opens up Netty HTTP server and distributes all jars to the worker nodes.
2. Driver program runs on master node , which means dedicated resources to driver process.
While in cluster mode :
1. It runs on worker node.
2. All the jars need to be placed in a common folder of the cluster so that it is accessible to all the worker nodes or in folder of each worker node.
Here it's not able to access hive metastore due to unavailability of hive jar to any of the nodes in cluster.
In my case, I received the HTTP 415 Unsupported Media Type response, since I specified the content type to be TEXT and NOT JSON, so simply changing the type solved the issue. Please check the solution in more detail in the following blog post: https://www.howtodevelop.net/article/20/unsupported-media-type-415-in-aspnet-core-web-api
typeof(BaseClass).IsAssignableFrom(unknownType);
Try this: org.apache.commons.math3.util.Precision.round(double x, int scale)
See: http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/util/Precision.html
Apache Commons Mathematics Library homepage is: http://commons.apache.org/proper/commons-math/index.html
The internal implemetation of this method is:
public static double round(double x, int scale) {
return round(x, scale, BigDecimal.ROUND_HALF_UP);
}
public static double round(double x, int scale, int roundingMethod) {
try {
return (new BigDecimal
(Double.toString(x))
.setScale(scale, roundingMethod))
.doubleValue();
} catch (NumberFormatException ex) {
if (Double.isInfinite(x)) {
return x;
} else {
return Double.NaN;
}
}
}
I had the same problem: I was programmatically binding my GridView1 to one SQL table [dictonary] or another [meny] BUT when I selected the second table from my RadioButtonList1, I was getting an error (System.Web.HttpException: Field or property with the title [the first column's title from the previously selected table] was not found in the selected data source.) i.e. saying that the columns from my first-selected table couldn't be found. All I needed to do was insert:
GridView1.Columns.Clear()
before adding the table columns. Here goes the full code:
Dim connectionString As String = "your-string-details"
Dim connection As New SqlConnection(connectionString)
Then comes your first Sub:
Private Sub BindOrders()
connection.Open()
Dim sqlCommand As String = "SELECT * FROM [dictionary]"
Dim dataAdapter As New SqlDataAdapter(sqlCommand, connection)
Dim dt As New DataTable()
dataAdapter.Fill(dt)
GridView1.Columns.Clear() ' clear columns before adding new ones
If GridView1.Columns.Count <= 0 Then
Dim Field As New BoundField()
Field.DataField = "id"
Field.HeaderText = "id"
GridView1.Columns.Add(Field)
Field = New BoundField()
Field.DataField = "strArHundreds"
Field.HeaderText = "strArHundreds"
GridView1.Columns.Add(Field)
Field = New BoundField()
Field.DataField = "strArTens"
Field.HeaderText = "strArTens"
GridView1.Columns.Add(Field)
Field = New BoundField()
Field.DataField = "strArSingles"
Field.HeaderText = "strArSingles"
GridView1.Columns.Add(Field)
End If
GridView1.DataSource = dt
GridView1.DataBind()
connection.Close()
End Sub
Then comes your second Sub:
Private Sub BindDocuments()
connection.Open()
Dim sqlCommand As String = "SELECT * FROM [meny]"
Dim dataAdapter As New SqlDataAdapter(sqlCommand, connection)
Dim dt As New DataTable()
dataAdapter.Fill(dt)
GridView1.Columns.Clear() ' clear columns before adding new ones
If GridView1.Columns.Count <= 0 Then
Dim Field As New BoundField
Field = New BoundField
Field.DataField = "id"
Field.HeaderText = "id"
GridView1.Columns.Add(Field)
Field = New BoundField
Field.DataField = "nazev"
Field.HeaderText = "nazev"
GridView1.Columns.Add(Field)
End If
GridView1.DataSource = dt
GridView1.DataBind()
connection.Close()
End Sub
Finally comes your RadioButton:
Protected Sub RadioButtonList1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles RadioButtonList1.SelectedIndexChanged
Dim index As Integer
index = RadioButtonList1.SelectedIndex
Select Case index
Case 0
BindOrders()
Exit Select
Case 1
BindDocuments()
Exit Select
End Select
End Sub
For completion, here is the code for the GridView1 and the RadioButtonList1 in the associated aspx.file:
<asp:RadioButtonList ID="RadioButtonList1"
runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">
<asp:ListItem>Obraty</asp:ListItem>
<asp:ListItem>Dokumenty</asp:ListItem>
</asp:RadioButtonList>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
</asp:GridView>
This all works well now.
Little late to the party but why don't you guys try animation.No I am not telling you to manage animation controllers and disposing them off and all that stuff.theres a built-in widget for that called TweenAnimationBuilder.You can animate between values of any type,heres an example with a Duration class
TweenAnimationBuilder<Duration>(
duration: Duration(minutes: 3),
tween: Tween(begin: Duration(minutes: 3), end: Duration.zero),
onEnd: () {
print('Timer ended');
},
builder: (BuildContext context, Duration value, Widget child) {
final minutes = value.inMinutes;
final seconds = value.inSeconds % 60;
return Padding(
padding: const EdgeInsets.symmetric(vertical: 5),
child: Text('$minutes:$seconds',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 30)));
}),
and You also get onEnd call back which notifies you when the animation completes;
here's the output
Can you assign a unique CSS class to each distinct timer? That way you could use the selector for the CSS class, which would work fine with multiple div
elements.
By default, the hr
element in Twitter Bootstrap CSS file has a top and bottom margin of 18px
. That's what creates a gap. If you want the gap to be smaller you'll need to adjust margin property of the hr
element.
In your example, do something like this:
.container hr {
margin: 2px 0;
}
I liked FakeRainBrigand's answer, however it contains a few problems: It can not handle whitespace between a quote and a comma, and does not support 2 consecutive commas. I tried editing his answer but my edit got rejected by reviewers that apparently did not understand my code. Here is my version of FakeRainBrigand's code. There is also a fiddle: http://jsfiddle.net/xTezm/46/
String.prototype.splitCSV = function() {
var matches = this.match(/(\s*"[^"]+"\s*|\s*[^,]+|,)(?=,|$)/g);
for (var n = 0; n < matches.length; ++n) {
matches[n] = matches[n].trim();
if (matches[n] == ',') matches[n] = '';
}
if (this[0] == ',') matches.unshift("");
return matches;
}
var string = ',"string, duppi, du" , 23 ,,, "string, duppi, du",dup,"", , lala';
var parsed = string.splitCSV();
alert(parsed.join('|'));
Also check out the open financial exchange (ofx) http://www.ofx.net/
This is what apps like quicken, ms money etc use.
for (Int32 i = 1; i < dt_pattern.Rows.Count - 1; i++){
double yATmax = ToDouble(dt_pattern.Rows[i]["Ampl"].ToString()) + AT;
}
if you want to get around the + 1 issue
You may want to look at IBExpert Personal Edition. While not open source, this is a very good tool for designing, building, and administering Firebird and InterBase databases.
The Personal Edition is free, but some of the more advanced features are not available. Still, even without the slick extras, the free version is very powerful.
http://msdn.microsoft.com/en-us/library/wkze6zky.aspx
menu: Project-->Add Reference
click: assemblies, framework
Put a checkmark on Microsoft.VisualBasic.
Hit OK.
That link is for Visual Studio 2013, you can use the "Other versions" dropdown for different versions of visual studio.
In all cases you need to add a reference to the .NET assembly "Microsoft.VisualBasic".
At the top of your c# file you neeed:
using Microsoft.VisualBasic;
Then you can look at writing the code.
The code would be something like:
private void btnOK_Click(object sender, EventArgs e)
{
if ( Information.IsNumeric(startingbudget) )
{
MessageBox.Show("This is a number.");
}
}
There are currently three distinct events which may or may not be triggered when the client devices moves. Two of them are focused around orientation and the last on motion:
ondeviceorientation
is known to work on the desktop version of Chrome, and most Apple laptops seems to have the hardware required for this to work. It also works on Mobile Safari on the iPhone 4 with iOS 4.2. In the event handler function, you can access alpha
, beta
, gamma
values on the event data supplied as the only argument to the function.
onmozorientation
is supported on Firefox 3.6 and newer. Again, this is known to work on most Apple laptops, but might work on Windows or Linux machines with accelerometer as well. In the event handler function, look for x
, y
, z
fields on the event data supplied as first argument.
ondevicemotion
is known to work on iPhone 3GS + 4 and iPad (both with iOS 4.2), and provides data related to the current acceleration of the client device. The event data passed to the handler function has acceleration
and accelerationIncludingGravity
, which both have three fields for each axis: x
, y
, z
The "earthquake detecting" sample website uses a series of if
statements to figure out which event to attach to (in a somewhat prioritized order) and passes the data received to a common tilt
function:
if (window.DeviceOrientationEvent) {
window.addEventListener("deviceorientation", function () {
tilt([event.beta, event.gamma]);
}, true);
} else if (window.DeviceMotionEvent) {
window.addEventListener('devicemotion', function () {
tilt([event.acceleration.x * 2, event.acceleration.y * 2]);
}, true);
} else {
window.addEventListener("MozOrientation", function () {
tilt([orientation.x * 50, orientation.y * 50]);
}, true);
}
The constant factors 2 and 50 are used to "align" the readings from the two latter events with those from the first, but these are by no means precise representations. For this simple "toy" project it works just fine, but if you need to use the data for something slightly more serious, you will have to get familiar with the units of the values provided in the different events and treat them with respect :)
Don't know what you are doing (helpful to show what you tried that didn't work), but your claim that cex.axis
only affects the x-axis is not true:
set.seed(123)
foo <- data.frame(X = rnorm(10), Y = rnorm(10))
plot(Y ~ X, data = foo, cex.axis = 3)
at least for me with:
> sessionInfo()
R version 2.11.1 Patched (2010-08-17 r52767)
Platform: x86_64-unknown-linux-gnu (64-bit)
locale:
[1] LC_CTYPE=en_GB.UTF-8 LC_NUMERIC=C
[3] LC_TIME=en_GB.UTF-8 LC_COLLATE=en_GB.UTF-8
[5] LC_MONETARY=C LC_MESSAGES=en_GB.UTF-8
[7] LC_PAPER=en_GB.UTF-8 LC_NAME=C
[9] LC_ADDRESS=C LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_GB.UTF-8 LC_IDENTIFICATION=C
attached base packages:
[1] grid stats graphics grDevices utils datasets methods
[8] base
other attached packages:
[1] ggplot2_0.8.8 proto_0.3-8 reshape_0.8.3 plyr_1.2.1
loaded via a namespace (and not attached):
[1] digest_0.4.2 tools_2.11.1
Also, cex.axis
affects the labelling of tick marks. cex.lab
is used to control what R call the axis labels.
plot(Y ~ X, data = foo, cex.lab = 3)
but even that works for both the x- and y-axis.
Following up Jens' comment about using barplot()
. Check out the cex.names
argument to barplot()
, which allows you to control the bar labels:
dat <- rpois(10, 3) names(dat) <- LETTERS[1:10] barplot(dat, cex.names = 3, cex.axis = 2)
As you mention that cex.axis
was only affecting the x-axis I presume you had horiz = TRUE
in your barplot()
call as well? As the bar labels are not drawn with an axis()
call, applying Joris' (otherwise very useful) answer with individual axis()
calls won't help in this situation with you using barplot()
HTH
Try the following lines in Dockerfile
:
RUN useradd -rm -d /home/ubuntu -s /bin/bash -g root -G sudo -u 1001 ubuntu
USER ubuntu
WORKDIR /home/ubuntu
useradd
options (see: man useradd
):
-r
, --system
Create a system account. see: Implications creating system accounts-m
, --create-home
Create the user's home directory.-d
, --home-dir HOME_DIR
Home directory of the new account.-s
, --shell SHELL
Login shell of the new account.-g
, --gid GROUP
Name or ID of the primary group.-G
, --groups GROUPS
List of supplementary groups.-u
, --uid UID
Specify user ID. see: Understanding how uid and gid work in Docker containers-p
, --password PASSWORD
Encrypted password of the new account (e.g. ubuntu
).To set the user password, add -p "$(openssl passwd -1 ubuntu)"
to useradd
command.
Alternatively add the following lines to your Dockerfile
:
SHELL ["/bin/bash", "-o", "pipefail", "-c"]
RUN echo 'ubuntu:ubuntu' | chpasswd
The first shell instruction is to make sure that -o pipefail
option is enabled before RUN
with a pipe in it. Read more: Hadolint: Linting your Dockerfile.
I wrote a hasAttr() plugin for jquery that will do all of this very simply, exactly as the OP has requested. More information here
EDIT: My plugin was deleted in the great plugins.jquery.com database deletion disaster of 2010. You can look here for some info on adding it yourself, and why it hasn't been added.
Here's a little trick I'm using lately and brings good results. I would like to share with those who have to fight often with VBA.
1.- Implement a public initiation subroutine in each of your custom classes. I call it InitiateProperties throughout all my classes. This method has to accept the arguments you would like to send to the constructor.
2.- Create a module called factory, and create a public function with the word "Create" plus the same name as the class, and the same incoming arguments as the constructor needs. This function has to instantiate your class, and call the initiation subroutine explained in point (1), passing the received arguments. Finally returned the instantiated and initiated method.
Example:
Let's say we have the custom class Employee. As the previous example, is has to be instantiated with name and age.
This is the InitiateProperties method. m_name and m_age are our private properties to be set.
Public Sub InitiateProperties(name as String, age as Integer)
m_name = name
m_age = age
End Sub
And now in the factory module:
Public Function CreateEmployee(name as String, age as Integer) as Employee
Dim employee_obj As Employee
Set employee_obj = new Employee
employee_obj.InitiateProperties name:=name, age:=age
set CreateEmployee = employee_obj
End Function
And finally when you want to instantiate an employee
Dim this_employee as Employee
Set this_employee = factory.CreateEmployee(name:="Johnny", age:=89)
Especially useful when you have several classes. Just place a function for each in the module factory and instantiate just by calling factory.CreateClassA(arguments), factory.CreateClassB(other_arguments), etc.
As stenci pointed out, you can do the same thing with a terser syntax by avoiding to create a local variable in the constructor functions. For instance the CreateEmployee function could be written like this:
Public Function CreateEmployee(name as String, age as Integer) as Employee
Set CreateEmployee = new Employee
CreateEmployee.InitiateProperties name:=name, age:=age
End Function
Which is nicer.
You could write a little, very simple routine that does it, without using a regular expression:
pos
so that is points to just before the opening bracket after your for
or while
. openBr
to 0
.pos
, reading the characters at the respective positions, and increment openBr
when you see an opening bracket, and decrement it when you see a closing bracket. That will increment it once at the beginning, for the first opening bracket in "for (
", increment and decrement some more for some brackets in between, and set it back to 0
when your for
bracket closes. openBr
is 0
again.The stopping positon is your closing bracket of for(...)
. Now you can check if there is a semicolon following or not.
If you have fresh installation / update of Xcode, it is possible that your git binary can't be executed (I had mine under /usr/bin/git
). To fix this problem just run the Xcode and "Accept" license conditions and try again, it should work.
With the release of RecyclerView library, now you can align a list of images bind with text easily. You can use LinearLayoutManager to specify the direction in which you would like to orient your list, either vertical or horizontal as shown below.
You can download a full working demo from this post
You could also subscribe to the store mutations:
store.subscribe((mutation, state) => {
console.log(mutation.type)
console.log(mutation.payload)
})
You should always use below MIME type if you want to serve excel file in xlsx format
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
don't forget the very helpful 'x of generator' syntax to loop through the generator. No need to use the next() function at all.
function* square(x){
for(i=0;i<100;i++){
x = x * 2;
yield x;
}
}
var gen = square(2);
for(x of gen){
console.log(x);
}
Based on this code (which you provided in response to Alex's answer):
Editable newTxt=(Editable)userName1.getText();
String newString = newTxt.toString();
It looks like you're trying to get the text out of a TextView or EditText. If that's the case then this should work:
String newString = userName1.getText().toString();
Small tweak to Luke's answer,
function reloadJs(src) {
src = $('script[src$="' + src + '"]').attr("src");
$('script[src$="' + src + '"]').remove();
$('<script/>').attr('src', src).appendTo('head');
}
and call it like,
reloadJs("myFile.js");
This will not have any path related issues.
string trim(const string & sStr)
{
int nSize = sStr.size();
int nSPos = 0, nEPos = 1, i;
for(i = 0; i< nSize; ++i) {
if( !isspace( sStr[i] ) ) {
nSPos = i ;
break;
}
}
for(i = nSize -1 ; i >= 0 ; --i) {
if( !isspace( sStr[i] ) ) {
nEPos = i;
break;
}
}
return string(sStr, nSPos, nEPos - nSPos + 1);
}
Why is this happening?
The entire ext/mysql
PHP extension, which provides all functions named with the prefix mysql_
, was officially deprecated in PHP v5.5.0 and removed in PHP v7.
It was originally introduced in PHP v2.0 (November 1997) for MySQL v3.20, and no new features have been added since 2006. Coupled with the lack of new features are difficulties in maintaining such old code amidst complex security vulnerabilities.
The manual has contained warnings against its use in new code since June 2011.
How can I fix it?
As the error message suggests, there are two other MySQL extensions that you can consider: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql
. Both have been in PHP core since v5.0, so if you're using a version that is throwing these deprecation errors then you can almost certainly just start using them right away—i.e. without any installation effort.
They differ slightly, but offer a number of advantages over the old extension including API support for transactions, stored procedures and prepared statements (thereby providing the best way to defeat SQL injection attacks). PHP developer Ulf Wendel has written a thorough comparison of the features.
Hashphp.org has an excellent tutorial on migrating from ext/mysql
to PDO.
I understand that it's possible to suppress deprecation errors by setting
error_reporting
inphp.ini
to excludeE_DEPRECATED
:error_reporting = E_ALL ^ E_DEPRECATED
What will happen if I do that?
Yes, it is possible to suppress such error messages and continue using the old ext/mysql
extension for the time being. But you really shouldn't do this—this is a final warning from the developers that the extension may not be bundled with future versions of PHP (indeed, as already mentioned, it has been removed from PHP v7). Instead, you should take this opportunity to migrate your application now, before it's too late.
Note also that this technique will suppress all E_DEPRECATED
messages, not just those to do with the ext/mysql
extension: therefore you may be unaware of other upcoming changes to PHP that would affect your application code. It is, of course, possible to only suppress errors that arise on the expression at issue by using PHP's error control operator—i.e. prepending the relevant line with @
—however this will suppress all errors raised by that expression, not just E_DEPRECATED
ones.
You are starting a new project.
There is absolutely no reason to use ext/mysql
—choose one of the other, more modern, extensions instead and reap the rewards of the benefits they offer.
You have (your own) legacy codebase that currently depends upon ext/mysql
.
It would be wise to perform regression testing: you really shouldn't be changing anything (especially upgrading PHP) until you have identified all of the potential areas of impact, planned around each of them and then thoroughly tested your solution in a staging environment.
Following good coding practice, your application was developed in a loosely integrated/modular fashion and the database access methods are all self-contained in one place that can easily be swapped out for one of the new extensions.
Spend half an hour rewriting this module to use one of the other, more modern, extensions; test thoroughly. You can later introduce further refinements to reap the rewards of the benefits they offer.
The database access methods are scattered all over the place and cannot easily be swapped out for one of the new extensions.
Consider whether you really need to upgrade to PHP v5.5 at this time.
You should begin planning to replace ext/mysql
with one of the other, more modern, extensions in order that you can reap the rewards of the benefits they offer; you might also use it as an opportunity to refactor your database access methods into a more modular structure.
However, if you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.
You are using a third party project that depends upon ext/mysql
.
Consider whether you really need to upgrade to PHP v5.5 at this time.
Check whether the developer has released any fixes, workarounds or guidance in relation to this specific issue; or, if not, pressure them to do so by bringing this matter to their attention. If you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.
It is absolutely essential to perform regression testing.
Build Version Increment (GPL) gives you (nearly) everything you need for controlling the version of your assemblies.
Some Features (copied from the site):
This is now possible with C# 7.0's pattern matching. For example:
var myString = "abcDEF";
switch(myString)
{
case string x when x.StartsWith("abc"):
//Do something here
break;
}
In a MVC application, I got this warning because I was opening a Kendo Window with a method that was returning a View(), instead of a PartialView(). The View() was trying to retrive again all the scripts of the page.
If you are running SQL Server 2008 R2 the built in options on to do this in SSMS as marc_s described above changed a bit. Instead of selecting Script data = true
as shown in his diagram, there is now a new option called "Types of data to script"
just above the "Table/View Options" grouping. Here you can select to script data only, schema and data or schema only. Works like a charm.
instead of:
android:drawable="@color/transparent"
write
android:drawable="@android:color/transparent"
The readarray
command (also spelled mapfile
) was introduced in bash 4.0.
readarray -t a < /path/to/filename
Arrays.fill(arrayName,value);
in java
int arrnum[] ={5,6,9,2,10};
for(int i=0;i<arrnum.length;i++){
System.out.println(arrnum[i]+" ");
}
Arrays.fill(arrnum,0);
for(int i=0;i<arrnum.length;i++){
System.out.println(arrnum[i]+" ");
}
Output
5 6 9 2 10
0 0 0 0 0
Easy solution in Python3+:
import time
todaysdate = time.strftime("%d/%m/%Y")
#with '.' isntead of '/'
todaysdate = time.strftime("%d.%m.%Y")
You cannot set inter-paragraph spacing in CSS using line-height, the spacing between <p>
blocks. That instead sets the intra-paragraph line spacing, the space between lines within a <p>
block. That is, line-height is the typographer's inter-line leading within the paragraph is controlled by line-height.
I presently do not know of any method in CSS to produce (for example) a 0.15em inter-<p>
spacing, whether using em or rem variants on any font property. I suspect it can be done with more complex floats or offsets. A pity this is necessary in CSS.
If you don't support future dated transactions then something like this might work:
AND oh.tran_date >= trunc(sysdate-1)
The server_name
docs directive is used to identify virtual hosts, they're not used to set the binding.
netstat
tells you that nginx listens on 0.0.0.0:80
which means that it will accept connections from any IP.
If you want to change the IP nginx binds on, you have to change the listen
docs rule.
So, if you want to set nginx to bind to localhost
, you'd change that to:
listen 127.0.0.1:80;
In this way, requests that are not coming from localhost are discarded (they don't even hit nginx).
I'd rather do something like this:
private final static String TAG_FRAGMENT = "TAG_FRAGMENT";
private void showFragment() {
final Myfragment fragment = new MyFragment();
final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment, fragment, TAG_FRAGMENT);
transaction.addToBackStack(null);
transaction.commit();
}
@Override
public void onBackPressed() {
final Myfragment fragment = (Myfragment) getSupportFragmentManager().findFragmentByTag(TAG_FRAGMENT);
if (fragment.allowBackPressed()) { // and then you define a method allowBackPressed with the logic to allow back pressed or not
super.onBackPressed();
}
}
Hey there's a useful tutorial on Dot Net pearls: http://www.dotnetperls.com/progressbar
In agreement with Peter, you need to use some amount of threading or the program will just hang, somewhat defeating the purpose.
Example that uses ProgressBar and BackgroundWorker: C#
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, System.EventArgs e)
{
// Start the BackgroundWorker.
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i <= 100; i++)
{
// Wait 100 milliseconds.
Thread.Sleep(100);
// Report progress.
backgroundWorker1.ReportProgress(i);
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// Change the value of the ProgressBar to the BackgroundWorker progress.
progressBar1.Value = e.ProgressPercentage;
// Set the text.
this.Text = e.ProgressPercentage.ToString();
}
}
} //closing here
This works on Android Studio 1.x:
Update for RxJS 6 (April 2018)
It is now perfectly fine to import directly from rxjs
. (As can be seen in Angular 6+). Importing from rxjs/operators
is also fine and it is actually no longer possible to import operators globally (one of major reasons for refactoring rxjs 6
and the new approach using pipe
). Thanks to this treeshaking can now be used as well.
Sample code from rxjs repo:
import { Observable, Subject, ReplaySubject, from, of, range } from 'rxjs';
import { map, filter, switchMap } from 'rxjs/operators';
range(1, 200)
.pipe(filter(x => x % 2 === 1), map(x => x + x))
.subscribe(x => console.log(x));
Backwards compatibility for rxjs < 6?
rxjs team released a compatibility package on npm that is pretty much install & play. With this all your rxjs 5.x
code should run without any issues. This is especially useful now when most of the dependencies (i.e. modules for Angular) are not yet updated.
What you are doing is printing the value in the array at spot [3][3], which is invalid for a 3by3 array, you need to loop over all the spots and print them.
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
printf("%d ", array[i][j]);
}
printf("\n");
}
This will print it in the following format
10 23 42
1 654 0
40652 22 0
if you want more exact formatting you'll have to change how the printf is formatted.
class Hi
self #=> Hi
class << self #same as 'class << Hi'
self #=> #<Class:Hi>
self == Hi.singleton_class #=> true
end
end
[it makes self == thing.singleton_class
in the context of its block].
hi = String.new
def hi.a
end
hi.class.instance_methods.include? :a #=> false
hi.singleton_class.instance_methods.include? :a #=> true
hi
object inherits its #methods
from its #singleton_class.instance_methods
and then from its #class.instance_methods
.
Here we gave hi
's singleton class instance method :a
. It could have been done with class << hi instead.
hi
's #singleton_class
has all instance methods hi
's #class
has, and possibly some more (:a
here).
[instance methods of thing's #class
and #singleton_class
can be applied directly to thing. when ruby sees thing.a, it first looks for :a method definition in thing.singleton_class.instance_methods and then in thing.class.instance_methods]
By the way - they call object's singleton class == metaclass == eigenclass.
Local Explorer - File Manager on web browser extention can solve for chrome
but still some encoding problems
I was asking the same too. Another solution is you could overload your method:
void remove_id(EmployeeClass);
void remove_id(ProductClass);
void remove_id(DepartmentClass);
in the call the argument will fit accordingly the object you pass. but then you will have to repeat yourself
void remove_id(EmployeeClass _obj) {
int saveId = _obj->id;
...
};
void remove_id(ProductClass _obj) {
int saveId = _obj->id;
...
};
void remove_id(DepartmentClass _obj) {
int saveId = _obj->id;
...
};
I have created a solution which may be of use to some people. Simply include the code on your page, and you can write your own function that will be called when the back button is clicked.
I have tested in IE, FF, Chrome, and Safari, and are all working. The solution I have works based on iframes without the need for constant polling, in IE and FF, however, due to limitations in other browsers, the location hash is used in Safari.
There is a module called HttpHeadersMoreModule that gives you more control over headers. It does not come with Nginx and requires additional installation. With it, you can do something like this:
location ... {
more_set_headers "Server: my_server";
}
That will "set the Server output header to the custom value for any status code and any content type". It will replace headers that are already set or add them if unset.
You can do this with css transforms, though be careful with container height/width. Also you may need to position it lower:
input[type="range"] {_x000D_
position: absolute;_x000D_
top: 40%;_x000D_
transform: rotate(270deg);_x000D_
}
_x000D_
<input type="range"/>
_x000D_
or the 3d transform equivalent:
input[type="range"] {
transform: rotateZ(270deg);
}
You can also use this to switch the direction of the slide by setting it to 180deg or 90deg for horizontal or vertical respectively.
Wamp server default disk is "C:\"
if you install it to another disk for ex G:\
:
go to
g:\wamp\bin\apache\apache2.4.9\bin\
2 .call cmd
3 .execute httpd.exe -t
you will see errors
go to
g:\wamp\bin\apache\apache2.4.9\conf\extra\httpd-autoindex.conf
change in line 23 to :
Alias /icons/ "g:/Apache24/icons/"
<Directory "g:/Apache24/icons">
Options Indexes MultiViews
AllowOverride None
Require all granted
</Directory>
See http://adamalbrecht.com/2013/12/12/creating-a-simple-modal-dialog-directive-in-angular-js/ for a simple way of doing modal dialog with Angular and without needing bootstrap
Edit: I've since been using ng-dialog from http://likeastore.github.io/ngDialog which is flexible and doesn't have any dependencies.
When you use recv
in connection with select
if the socket is ready to be read from but there is no data to read that means the client has closed the connection.
Here is some code that handles this, also note the exception that is thrown when recv
is called a second time in the while loop. If there is nothing left to read this exception will be thrown it doesn't mean the client has closed the connection :
def listenToSockets(self):
while True:
changed_sockets = self.currentSockets
ready_to_read, ready_to_write, in_error = select.select(changed_sockets, [], [], 0.1)
for s in ready_to_read:
if s == self.serverSocket:
self.acceptNewConnection(s)
else:
self.readDataFromSocket(s)
And the function that receives the data :
def readDataFromSocket(self, socket):
data = ''
buffer = ''
try:
while True:
data = socket.recv(4096)
if not data:
break
buffer += data
except error, (errorCode,message):
# error 10035 is no data available, it is non-fatal
if errorCode != 10035:
print 'socket.error - ('+str(errorCode)+') ' + message
if data:
print 'received '+ buffer
else:
print 'disconnected'
After you get an error, in the next cell just run %debug
and that's it.
>>> import pandas as pd
>>> df = pd.DataFrame({'x' : [1, 2, 3, 4], 'y' : [4, 5, 6, 7]})
>>> df
x y
0 1 4
1 2 5
2 3 6
3 4 7
>>> s = df.ix[:,0]
>>> type(s)
<class 'pandas.core.series.Series'>
>>>
===========================================================================
UPDATE
If you're reading this after June 2017, ix
has been deprecated in pandas 0.20.2, so don't use it. Use loc
or iloc
instead. See comments and other answers to this question.
You can just read the data into a list and insert the new record where you want.
names = []
with open('names.txt', 'r+') as fd:
for line in fd:
names.append(line.split(' ')[-1].strip())
names.insert(2, "Charlie") # element 2 will be 3. in your list
fd.seek(0)
fd.truncate()
for i in xrange(len(names)):
fd.write("%d. %s\n" %(i + 1, names[i]))
There is http://ptsv2.com/
"Here you will find a server which receives any POST you wish to give it and stores the contents for you to review."
This script searches for non-ascii characters in one column. It generates a string of all valid characters, here code point 32 to 127. Then it searches for rows that don't match the list:
declare @str varchar(128)
declare @i int
set @str = ''
set @i = 32
while @i <= 127
begin
set @str = @str + '|' + char(@i)
set @i = @i + 1
end
select col1
from YourTable
where col1 like '%[^' + @str + ']%' escape '|'
Following Rory McCrossan answer, if you want to send an array of integer (almost for .NET), this is the code:
// ...
url: "MyUrl", // For example --> @Url.Action("Method", "Controller")
method: "post",
traditional: true,
data:
$('#myForm').serialize() +
"¶m1="xxx" +
"¶m2="33" +
"&" + $.param({ paramArray: ["1","2","3"]}, true)
,
// ...
Generally to avoid this kind of exceptions, you will need to surround your code by try and catch like this
try{
// your intent here
} catch (ActivityNotFoundException e) {
// show message to user
}
This is what list comprehensions are for:
numbers = [ int(x) for x in numbers ]
I have tried some hours now and the easiest way to stop browsers to jump to the anchor instead of scrolling to it is: Using another anchor (an id you do not use on the site). So instead of linking to "http://#YourActualID" you link to "http://#NoIDonYourSite". Poof, browsers won’t jump anymore.
Then just check if an anchor is set (with the script provided below, that is pulled out of the other thread!). And set your actual id you want to scroll to.
$(document).ready(function(){
$(window).load(function(){
// Remove the # from the hash, as different browsers may or may not include it
var hash = location.hash.replace('#','');
if(hash != ''){
// Clear the hash in the URL
// location.hash = ''; // delete front "//" if you want to change the address bar
$('html, body').animate({ scrollTop: $('#YourIDtoScrollTo').offset().top}, 1000);
}
});
});
See https://lightningsoul.com/media/article/coding/30/YOUTUBE-SOCKREAD-SCRIPT-FOR-MIRC#content for a working example.
You can run the MySQL command SHOW FULL PROCESSLIST;
to see what queries are being processed at any given time, but that probably won't achieve what you're hoping for.
The best method to get a history without having to modify every application using the server is probably through triggers. You could set up triggers so that every query run results in the query being inserted into some sort of history table, and then create a separate page to access this information.
Do be aware that this will probably considerably slow down everything on the server though, with adding an extra INSERT
on top of every single query.
Edit: another alternative is the General Query Log, but having it written to a flat file would remove a lot of possibilities for flexibility of displaying, especially in real-time. If you just want a simple, easy-to-implement way to see what's going on though, enabling the GQL and then using running tail -f
on the logfile would do the trick.
There are a number of different ways to do this. You might want to check out XStream or JAXB. There are tutorials and the examples.
Stack allocation is much faster since all it really does is move the stack pointer. Using memory pools, you can get comparable performance out of heap allocation, but that comes with a slight added complexity and its own headaches.
Also, stack vs. heap is not only a performance consideration; it also tells you a lot about the expected lifetime of objects.
Yes. The same notation that works for non-empty dict/set works for empty ones.
Notice the difference between non-empty dict
and set
literals:
{1: 'a', 2: 'b', 3: 'c'}
-- a number of key-value pairs inside makes a dict
{'aaa', 'bbb', 'ccc'}
-- a tuple of values inside makes a set
So:
{}
== zero number of key-value pairs == empty dict
{*()}
== empty tuple of values == empty set
However the fact, that you can do it, doesn't mean you should. Unless you have some strong reasons, it's better to construct an empty set explicitly, like:
a = set()
Performance:
The literal is ~15% faster than the set-constructor (CPython-3.8, 2019 PC, Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz):
>>> %timeit ({*()} & {*()}) | {*()} 214 ns ± 1.26 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) >>> %timeit (set() & set()) | set() 252 ns ± 0.566 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
... and for completeness, Renato Garcia's
frozenset
proposal on the above expression is some 60% faster!>>> ? = frozenset() >>> %timeit (? & ?) | ? 100 ns ± 0.51 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
NB: As ctrueden noticed in comments, {()}
is not an empty set. It's a set with 1 element: empty tuple.
This language feature is convenient in this situation.
public String getName() {
return (String) memberHashMap.get("Name");
}
If memberHashMap.get("Name") returns null, you'd still want the method above to return null without throwing an exception. No matter what the class is, null is null.
Other answers already pointed out that the representation of floating numbers is a thorny issue, to say the least.
Since you don't give enough context in your question, I cannot know if the decimal module can be useful for your needs:
http://docs.python.org/library/decimal.html
Among other things you can explicitly specify the precision that you wish to obtain (from the docs):
>>> getcontext().prec = 6
>>> Decimal('3.0')
Decimal('3.0')
>>> Decimal('3.1415926535')
Decimal('3.1415926535')
>>> Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85987')
>>> getcontext().rounding = ROUND_UP
>>> Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85988')
A simple example from my prompt (python 2.6):
>>> import decimal
>>> a = decimal.Decimal('10.000000001')
>>> a
Decimal('10.000000001')
>>> print a
10.000000001
>>> b = decimal.Decimal('10.00000000000000000000000000900000002')
>>> print b
10.00000000000000000000000000900000002
>>> print str(b)
10.00000000000000000000000000900000002
>>> len(str(b/decimal.Decimal('3.0')))
29
Maybe this can help? decimal is in python stdlib since 2.4, with additions in python 2.6.
Hope this helps, Francesco
SELECT *
FROM
(
SELECT [Period], [Account], [Value]
FROM TableName
) AS source
PIVOT
(
MAX([Value])
FOR [Period] IN ([2000], [2001], [2002])
) as pvt
Another way,
SELECT ACCOUNT,
MAX(CASE WHEN Period = '2000' THEN Value ELSE NULL END) [2000],
MAX(CASE WHEN Period = '2001' THEN Value ELSE NULL END) [2001],
MAX(CASE WHEN Period = '2002' THEN Value ELSE NULL END) [2002]
FROM tableName
GROUP BY Account
The WHERE
clause is misplaced, it has to follow the table references and JOIN operations.
Something like this:
FROM tartikel p1
JOIN tartikelpict p2
ON p1.kArtikel = p2.kArtikel
AND p2.nNr = 1
WHERE p1.dErstellt >= DATE(NOW()) - INTERVAL 7 DAY
ORDER BY p1.kArtikel DESC
EDIT (three plus years later)
The above essentially answers the question "I tried to add a WHERE clause to my query and now the query is returning an error, how do I fix it?"
As to a question about writing a condition that checks a date range of "last 7 days"...
That really depends on interpreting the specification, what the datatype of the column in the table is (DATE or DATETIME) and what data is available... what should be returned.
To summarize: the general approach is to identify a "start" for the date/datetime range, and "end" of that range, and reference those in a query. Let's consider something easier... all rows for "yesterday".
If our column is DATE type. Before we incorporate an expression into a query, we can test it in a simple SELECT
SELECT DATE(NOW()) + INTERVAL -1 DAY
and verify the result returned is what we expect. Then we can use that same expression in a WHERE clause, comparing it to a DATE column like this:
WHERE datecol = DATE(NOW()) + INTERVAL -1 DAY
For a DATETIME or TIMESTAMP column, we can use >=
and <
inequality comparisons to specify a range
WHERE datetimecol >= DATE(NOW()) + INTERVAL -1 DAY
AND datetimecol < DATE(NOW()) + INTERVAL 0 DAY
For "last 7 days" we need to know if that mean from this point right now, back 7 days ... e.g. the last 7*24 hours , including the time component in the comparison, ...
WHERE datetimecol >= NOW() + INTERVAL -7 DAY
AND datetimecol < NOW() + INTERVAL 0 DAY
the last seven complete days, not including today
WHERE datetimecol >= DATE(NOW()) + INTERVAL -7 DAY
AND datetimecol < DATE(NOW()) + INTERVAL 0 DAY
or past six complete days plus so far today ...
WHERE datetimecol >= DATE(NOW()) + INTERVAL -6 DAY
AND datetimecol < NOW() + INTERVAL 0 DAY
I recommend testing the expressions on the right side in a SELECT statement, we can use a user-defined variable in place of NOW() for testing, not being tied to what NOW() returns so we can test borders, across week/month/year boundaries, and so on.
SET @clock = '2017-11-17 11:47:47' ;
SELECT DATE(@clock)
, DATE(@clock) + INTERVAL -7 DAY
, @clock + INTERVAL -6 DAY
Once we have expressions that return values that work for "start" and "end" for our particular use case, what we mean by "last 7 days", we can use those expressions in range comparisons in the WHERE clause.
(Some developers prefer to use the DATE_ADD
and DATE_SUB
functions in place of the + INTERVAL val DAY/HOUR/MINUTE/MONTH/YEAR
syntax.
And MySQL provides some convenient functions for working with DATE, DATETIME and TIMESTAMP datatypes... DATE, LAST_DAY,
Some developers prefer to calculate the start and end in other code, and supply string literals in the SQL query, such that the query submitted to the database is
WHERE datetimecol >= '2017-11-10 00:00'
AND datetimecol < '2017-11-17 00:00'
And that approach works too. (My preference would be to explicitly cast those string literals into DATETIME, either with CAST, CONVERT or just the + INTERVAL trick...
WHERE datetimecol >= '2017-11-10 00:00' + INTERVAL 0 SECOND
AND datetimecol < '2017-11-17 00:00' + INTERVAL 0 SECOND
The above all assumes we are storing "dates" in appropriate DATE, DATETIME and/or TIMESTAMP datatypes, and not storing them as strings in variety of formats e.g. 'dd/mm/yyyy'
, m/d/yyyy
, julian dates, or in sporadically non-canonical formats, or as a number of seconds since the beginning of the epoch, this answer would need to be much longer.
To create the regex from a string, you have to use JavaScript's RegExp
object.
If you also want to match/replace more than one time, then you must add the g
(global match) flag. Here's an example:
var stringToGoIntoTheRegex = "abc";
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;
var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.
Not every string is a valid regex, though: there are some speciall characters, like (
or [
. To work around this issue, simply escape the string before turning it into a regex. A utility function for that goes in the sample below:
function escapeRegExp(stringToGoIntoTheRegex) {
return stringToGoIntoTheRegex.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
var stringToGoIntoTheRegex = escapeRegExp("abc"); // this is the only change from above
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;
var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.
Note: the regex in the question uses the s
modifier, which didn't exist at the time of the question, but does exist -- a s
(dotall) flag/modifier in JavaScript -- today.
Utilizing the "dynamic table" capability in SQL Server (querying against a parenthesis-surrounded query), you can return 2000, 49 w/ the following. If your platform doesn't offer an equivalent to the "dynamic table" ANSI-extention, you can always utilize a temp table in two-steps/statement by inserting the results within the "dynamic table" to a temp table, and then performing a subsequent select on the temp table.
DECLARE @T TABLE(
[contract] INT,
project INT,
activity INT
)
INSERT INTO @T VALUES( 1000, 8000, 10 )
INSERT INTO @T VALUES( 1000, 8000, 20 )
INSERT INTO @T VALUES( 1000, 8001, 10 )
INSERT INTO @T VALUES( 2000, 9000, 49 )
INSERT INTO @T VALUES( 2000, 9001, 49 )
INSERT INTO @T VALUES( 3000, 9000, 79 )
INSERT INTO @T VALUES( 3000, 9000, 78 )
SELECT
[contract],
[Activity] = max (activity)
FROM
(
SELECT
[contract],
[Activity]
FROM
@T
GROUP BY
[contract],
[Activity]
) t
GROUP BY
[contract]
HAVING count (*) = 1
Sql server has a limit of ~2000 parameters, which is a pain if you have 10k Ids and want the records connected with them. I wrote these methods which accept batched lists of ids and are called like this:
List<Order> orders = dataContext.Orders.FetchByIds(
orderIdChunks,
list => row => list.Contains(row.OrderId)
);
List<Customer> customers = dataContext.Orders.FetchByIds(
orderIdChunks,
list => row => list.Contains(row.OrderId),
row => row.Customer
);
public static List<ResultType> FetchByIds<RecordType, ResultType>(
this IQueryable<RecordType> querySource,
List<List<int>> IdChunks,
Func<List<int>, Expression<Func<RecordType, bool>>> filterExpressionGenerator,
Expression<Func<RecordType, ResultType>> projectionExpression
) where RecordType : class
{
List<ResultType> result = new List<ResultType>();
foreach (List<int> chunk in IdChunks)
{
Expression<Func<RecordType, bool>> filterExpression =
filterExpressionGenerator(chunk);
IQueryable<ResultType> query = querySource
.Where(filterExpression)
.Select(projectionExpression);
List<ResultType> rows = query.ToList();
result.AddRange(rows);
}
return result;
}
public static List<RecordType> FetchByIds<RecordType>(
this IQueryable<RecordType> querySource,
List<List<int>> IdChunks,
Func<List<int>, Expression<Func<RecordType, bool>>> filterExpressionGenerator
) where RecordType : class
{
Expression<Func<RecordType, RecordType>> identity = r => r;
return FetchByIds(
querySource,
IdChunks,
filterExpressionGenerator,
identity
);
}
You can do it using the foreach loop
DataTable dr_art_line_2 = ds.Tables["QuantityInIssueUnit"];
foreach(DataRow row in dr_art_line_2.Rows)
{
QuantityInIssueUnit_value = Convert.ToInt32(row["columnname"]);
}
By the way guys, (int)Decimal.MaxValue will overflow. You can't get the "int" part of a decimal because the decimal is too friggen big to put in the int box. Just checked... its even too big for a long (Int64).
If you want the bit of a Decimal value to the LEFT of the dot, you need to do this:
Math.Truncate(number)
and return the value as... A DECIMAL or a DOUBLE.
edit: Truncate is definitely the correct function!
Work with checkboxes using observables
You could even choose to use a behaviourSubject
to utilize the power of observables so you can start a certain chain of reaction starting at the isChecked$
observable.
In your component.ts:
public isChecked$ = new BehaviorSubject(false);
toggleChecked() {
this.isChecked$.next(!this.isChecked$.value)
}
In your template
<input type="checkbox" [checked]="isChecked$ | async" (change)="toggleChecked()">
Sorry, JS code...
Tested with the two inputs:
a = [55,11,66,77,72];
a = [ 0, 12, 13, 4, 5, 32, 8 ];
var first = Number.MIN_VALUE;
var second = Number.MIN_VALUE;
for (var i = -1, len = a.length; ++i < len;) {
var dist = a[i];
// get the largest 2
if (dist > first) {
second = first;
first = dist;
} else if (dist > second) { // && dist < first) { // this is actually not needed, I believe
second = dist;
}
}
console.log('largest, second largest',first,second);
largest, second largest 32 13
This should have a maximum of a.length*2 comparisons and only goes through the list once.
Mount the certs onto the Docker container using -v
:
docker run -v /host/path/to/certs:/container/path/to/certs -d IMAGE_ID "update-ca-certificates"
It's wrong. Use a span.
Swift 4.0
for i in stride(from: 5, to: 0, by: -1) {
print(i) // 5,4,3,2,1
}
If you want to include the to
value:
for i in stride(from: 5, through: 0, by: -1) {
print(i) // 5,4,3,2,1,0
}
For me it was using {{ }} instead of {% %}:
href="{{ static 'bootstrap.min.css' }}" # wrong
href="{% static 'bootstrap.min.css' %}" # right
If you are splitting from Linux, you can still reassemble in Windows.
copy /b file1 + file2 + file3 + file4 filetogether
Since Clone
would return an object instance of Book, that object would first need to be cast to a Book before you can call ToList
on it. The example above needs to be written as:
List<Book> books_2 = books_1.Select(book => (Book)book.Clone()).ToList();
Change the = to : to
fix the error.
var makeRequest = function(message) {<br>
var options = {<br>
host: 'localhost',<br>
port : 8080,<br>
path : '/',<br>
method: 'POST'<br>
}
This is a bit old but I want to add a thing I think is relevant.
(I meant to comment on one or 2 threads above but it seems I need reputation 50 and I have only 21 at the time I'm writing this. :) )
Just want to say that there are times when it's much better to access the elements of a form by name rather than by id. I'm not talking about the form itself. The form, OK, you can give it an id and then access it by it. But if you have a radio button in a form, it's much easier to use it as a single object (getting and setting its value) and you can only do this by name, as far as I know.
Example:
<form id="mainForm" name="mainForm">
<input type="radio" name="R1" value="V1">choice 1<br/>
<input type="radio" name="R1" value="V2">choice 2<br/>
<input type="radio" name="R1" value="V3">choice 3
</form>
You can get/set the checked value of the radio button R1 as a whole by using
document.mainForm.R1.value
or
document.getElementById("mainForm").R1.value
So if you want to have a unitary style, you might want to always use this method, regardless of the type of form element. Me, I'm perfectly comfortable accessing radio buttons by name and text boxes by id.
Presume he's using the tutorial from http://www.arcsynthesis.org/gltut/ along with premake4.3 :-)
sudo apt-get install libx11-dev
................. forX11/Xlib.h
sudo apt-get install mesa-common-dev
........ forGL/glx.h
sudo apt-get install libglu1-mesa-dev
..... forGL/glu.h
sudo apt-get install libxrandr-dev
........... forX11/extensions/Xrandr.h
sudo apt-get install libxi-dev
................... forX11/extensions/XInput.h
After which I could build glsdk_0.4.4 and examples without further issue.
while doing performance testing, the measure i go by is RPS, that is how many requests per second can the server serve within acceptable latency.
theoretically one server can only run as many requests concurrently as number of cores on it..
It doesn't look like the problem is ASP.net's threading model, since it can potentially serve thousands of rps. It seems like the problem might be your application. Are you using any synchronization primitives ?
also whats the latency on your web services, are they very quick to respond (within microseconds), if not then you might want to consider asynchronous calls, so you dont end up blocking
If this doesnt yeild something, then you might want to profile your code using visual studio or redgate profiler
What you need is called attribute selector. An example, using your html structure, is the following:
div[class^="tocolor-"], div[class*=" tocolor-"] {
color:red
}
In the place of div
you can add any element or remove it altogether, and in the place of class
you can add any attribute of the specified element.
[class^="tocolor-"]
— starts with "tocolor-".
[class*=" tocolor-"]
— contains the substring "tocolor-" occurring directly after a space character.
Demo: http://jsfiddle.net/K3693/1/
More information on CSS attribute selectors, you can find here and here. And from MDN Docs MDN Docs
This solution:
Minimum version of jQuery is 1.12
$(document).ready(function () {
function poll () {
$.get({
url: '/api/stream/',
success: function (data) {
console.log(data)
},
timeout: 10000 // == 10 seconds timeout
}).always(function () {
setTimeout(poll, 30000) // == 30 seconds polling period
})
}
// start polling
poll()
})
You can also use the Record type in typescript :
export interface nameInterface {
propName : Record<string, otherComplexInterface>
}
import (
"bytes"
"encoding/json"
)
const (
empty = ""
tab = "\t"
)
func PrettyJson(data interface{}) (string, error) {
buffer := new(bytes.Buffer)
encoder := json.NewEncoder(buffer)
encoder.SetIndent(empty, tab)
err := encoder.Encode(data)
if err != nil {
return empty, err
}
return buffer.String(), nil
}
This is old, but the answers here led me to a slightly different solution. If you are up for abusing comprehensions, you can get short-circuiting this way.
xs = [1, 2, 1]
s = set()
any(x in s or s.add(x) for x in xs)
# You can use a similar approach to actually retrieve the duplicates.
s = set()
duplicates = set(x for x in xs if x in s or s.add(x))
var arr = [ 'a', 'b', 'c'];
arr.push('d'); // insert as last item
Do you really want to style the <div>
? Or do you want to style the <input type="button">
? You should use the correct selector if you want the latter:
input[type=button] {
color:#08233e;
font:2.4em Futura, ‘Century Gothic’, AppleGothic, sans-serif;
font-size:70%;
/* ... other rules ... */
cursor:pointer;
}
input[type=button]:hover {
background-color:rgba(255,204,0,0.8);
}
See also:
I was upgrading from old sweetalert and found out how to do it in the new Version (official Docs):
// this is a Node object
var span = document.createElement("span");
span.innerHTML = "Testno sporocilo za objekt <b>test</b>";
swal({
title: "" + txt + "",
content: span,
confirmButtonText: "V redu",
allowOutsideClick: "true"
});
I had to delay a form submission in jQuery in order to execute an asynchronous call. Here's the simplified code...
$("$theform").submit(function(e) {
e.preventDefault();
var $this = $(this);
$.ajax('/path/to/script.php',
{
type: "POST",
data: { value: $("#input_control").val() }
}).done(function(response) {
$this.unbind('submit').submit();
});
});
Google Chrome Developer Tools has (a currently experimental) feature called CSS Overview which will allow you to find unused CSS rules.
To enable it follow these steps:
Try this:
string text = "My text that I want to display";
MessageBox.Show(text);
If you want an actual boolean column:
ALTER TABLE users ADD "priv_user" boolean DEFAULT false;
When you look up your php-fpm.conf
example location:
cat /usr/src/php/sapi/fpm/php-fpm.conf
you will see, that you need to configure the PHP FastCGI Process Manager to actually use Unix sockets. Per default, the listen
directive` is set up to listen on a TCP socket on one port. If there's no Unix socket defined, you won't find a Unix socket file.
; The address on which to accept FastCGI requests.
; Valid syntaxes are:
; 'ip.add.re.ss:port' - to listen on a TCP socket to a specific IPv4 address on
; a specific port;
; '[ip:6:addr:ess]:port' - to listen on a TCP socket to a specific IPv6 address on
; a specific port;
; 'port' - to listen on a TCP socket to all IPv4 addresses on a
; specific port;
; '[::]:port' - to listen on a TCP socket to all addresses
; (IPv6 and IPv4-mapped) on a specific port;
; '/path/to/unix/socket' - to listen on a unix socket.
; Note: This value is mandatory.
listen = 127.0.0.1:9000
Remove the width and display: block
and then add display: inline-block
to the button. To have it remain centered you can either add text-align: center;
on the body
or do the same on a newly created container.
The advantage of this approach (as opossed to centering with auto margins) is that the button will remain centered regardless of how much text it has.
Example: http://cssdeck.com/labs/2u4kf6dv
Best way is to define it in styles.xml
<style name="common_txt_style_heading" parent="android:style/Widget.TextView">
<item name="android:textSize">@dimen/common_txtsize_heading</item>
<item name="android:textColor">@color/color_black</item>
<item name="android:textStyle">bold|italic</item>
</style>
And update it in TextView
<TextView
android:id="@+id/txt_userprofile"
style="@style/common_txt_style_heading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="@dimen/margin_small"
android:text="@string/some_heading" />
var test = {'red':'#FF0000', 'blue':'#0000FF'};_x000D_
delete test.blue; // or use => delete test['blue'];_x000D_
console.log(test);
_x000D_
this deletes test.blue
replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(string,'a',''),'b',''),'c',''),'d',''),'e',''),'f',''),'g',''),'h',''),'i',''),'j',''),'k',''),'l',''),'m',''),'n',''),'o',''),'p',''),'q',''),'r',''),'s',''),'t',''),'u',''),'v',''),'w',''),'x',''),'y',''),'z',''),'A',''),'B',''),'C',''),'D',''),'E',''),'F',''),'G',''),'H',''),'I',''),'J',''),'K',''),'L',''),'M',''),'N',''),'O',''),'P',''),'Q',''),'R',''),'S',''),'T',''),'U',''),'V',''),'W',''),'X',''),'Y',''),'Z','')*1 AS string
,
:)
Just use this:
svn copy http://svn.example.com/project/trunk
http://svn.example.com/project/branches/release-1
-m "branch for release 1.0"
(all on one line, of course.) You should always make a branch of the entire trunk folder and contents. It is of course possible to branch sub-parts of the trunk, but this will almost never be a good practice. You want the branch to behave exactly like the trunk does now, and for that to happen you have to branch the entire trunk.
See a better summary of SVN usage at my blog: SVN Essentials, and SVN Essentials 2
It works for me by using class=blink for the respective element(s)
Simple JS Code
// Blink
setInterval(function()
{
setTimeout(function()
{
//$(".blink").css("color","rgba(0,0,0,0.1)"); // If you want simply black/white blink of text
$(".blink").css("visibility","hidden"); // This is for Visibility of the element
},900);
//$(".blink").css("color","rgba(0,0,0,1)"); // If you want simply black/white blink of text
$(".blink").css("visibility","visible"); // This is for Visibility of the element
},1000);
As many other answers suggest the limit approach, This can be another way
You can use the indexOf method on String which will returns the first Occurance of the given character, Using that index you can get the desired output
String target = "apple=fruit table price=5" ;
int x= target.indexOf("=");
System.out.println(target.substring(x+1));
First, the code:
from random import choices
def random_name(length=6):
return "".join(choices("abcdefghijklmnopqrstuvwxyz", k=length))
# ---
from IPython.display import IFrame, display, HTML
import tempfile
from os import unlink
def display_html_to_frame(html, width=600, height=600):
name = f"temp_{random_name()}.html"
with open(name, "w") as f:
print(html, file=f)
display(IFrame(name, width, height), metadata=dict(isolated=True))
# unlink(name)
def display_html_inline(html):
display(HTML(html, metadata=dict(isolated=True)))
h="<html><b>Hello</b></html>"
display_html_to_iframe(h)
display_html_inline(h)
Some quick notes:
metadata=dict(isolated=True)
does not isolate the result in an IFrame, as older documentation suggests. It appears to prevent clear-fix
from resetting everything. The flag is no longer documented: I just found using it allowed certain display: grid
styles to correctly render.IFrame
solution writes to a temporary file. You could use a data uri as described here but it makes debugging your output difficult. The Jupyter IFrame
function does not take a data
or srcdoc
attribute.tempfile
module creations are not sharable to another process, hence the random_name()
.HTML('Hello, <b>world</b>')
at top level of cell and its return value will render. Within a function, use display(HTML(...))
as is done above. This also allows you to mix display
and print
calls freely.System.IO.Path.GetRandomFileName()
if ((Request.Headers["XYZComponent"] ?? "") == "true")
{
// header is present and set to "true"
}
Seems there is another format now
where: {
LastName: "Doe",
$or: [
{
FirstName:
{
$eq: "John"
}
},
{
FirstName:
{
$eq: "Jane"
}
},
{
Age:
{
$gt: 18
}
}
]
}
Will generate
WHERE LastName='Doe' AND (FirstName = 'John' OR FirstName = 'Jane' OR Age > 18)
See the doc: http://docs.sequelizejs.com/en/latest/docs/querying/#where
I found a way to do it.
you can do an x,y scatterplot. it will ignore null records (i.e. rows)
all these annotations are type of stereo type type of annotation,the difference between these three annotations are
- If we add the @Component then it tells the role of class is a component class it means it is a class consisting some logic,but it does not tell whether a class containing a specifically business or persistence or controller logic so we don't use directly this @Component annotation
- If we add @Service annotation then it tells that a role of class consisting business logic
- If we add @Repository on top of class then it tells that a class consisting persistence logic
- Here @Component is a base annotation for @Service,@Repository and @Controller annotations
for example
package com.spring.anno;
@Service
public class TestBean
{
public void m1()
{
//business code
}
}
package com.spring.anno;
@Repository
public class TestBean
{
public void update()
{
//persistence code
}
}
@Service
or @Repositroy
or @Controller
annotation by default @Component
annotation is going to existence on top of the classYou could do this:
import java.io.*;
import java.util.*;
class WriteText
{
public static void main(String[] args)
{
try {
String text = "Your sample content to save in a text file.";
BufferedWriter out = new BufferedWriter(new FileWriter("sample.txt"));
out.write(text);
out.close();
}
catch (IOException e)
{
System.out.println("Exception ");
}
return ;
}
};
Understanding why ASCII and Unicode were created in the first place helped me understand the differences between the two.
ASCII, Origins
As stated in the other answers, ASCII uses 7 bits to represent a character. By using 7 bits, we can have a maximum of 2^7 (= 128) distinct combinations*. Which means that we can represent 128 characters maximum.
Wait, 7 bits? But why not 1 byte (8 bits)?
The last bit (8th) is used for avoiding errors as parity bit. This was relevant years ago.
Most ASCII characters are printable characters of the alphabet such as abc, ABC, 123, ?&!, etc. The others are control characters such as carriage return, line feed, tab, etc.
See below the binary representation of a few characters in ASCII:
0100101 -> % (Percent Sign - 37)
1000001 -> A (Capital letter A - 65)
1000010 -> B (Capital letter B - 66)
1000011 -> C (Capital letter C - 67)
0001101 -> Carriage Return (13)
See the full ASCII table over here.
ASCII was meant for English only.
What? Why English only? So many languages out there!
Because the center of the computer industry was in the USA at that time. As a consequence, they didn't need to support accents or other marks such as á, ü, ç, ñ, etc. (aka diacritics).
ASCII Extended
Some clever people started using the 8th bit (the bit used for parity) to encode more characters to support their language (to support "é", in French, for example). Just using one extra bit doubled the size of the original ASCII table to map up to 256 characters (2^8 = 256 characters). And not 2^7 as before (128).
10000010 -> é (e with acute accent - 130)
10100000 -> á (a with acute accent - 160)
The name for this "ASCII extended to 8 bits and not 7 bits as before" could be just referred as "extended ASCII" or "8-bit ASCII".
As @Tom pointed out in his comment below there is no such thing as "extended ASCII" yet this is an easy way to refer to this 8th-bit trick. There are many variations of the 8-bit ASCII table, for example, the ISO 8859-1, also called ISO Latin-1.
Unicode, The Rise
ASCII Extended solves the problem for languages that are based on the Latin alphabet... what about the others needing a completely different alphabet? Greek? Russian? Chinese and the likes?
We would have needed an entirely new character set... that's the rational behind Unicode. Unicode doesn't contain every character from every language, but it sure contains a gigantic amount of characters (see this table).
You cannot save text to your hard drive as "Unicode". Unicode is an abstract representation of the text. You need to "encode" this abstract representation. That's where an encoding comes into play.
Encodings: UTF-8 vs UTF-16 vs UTF-32
This answer does a pretty good job at explaining the basics:
UTF-8 uses the ASCII set for the first 128 characters. That's handy because it means ASCII text is also valid in UTF-8.
Mnemonics:
Note:
Why 2^7?
This is obvious for some, but just in case. We have seven slots available filled with either 0 or 1 (Binary Code). Each can have two combinations. If we have seven spots, we have 2 * 2 * 2 * 2 * 2 * 2 * 2 = 2^7 = 128 combinations. Think about this as a combination lock with seven wheels, each wheel having two numbers only.
Source: Wikipedia, this great blog post and Mocki.co where I initially posted this summary.