text:
Q: Lookup function in multiple sheets data I have multiple sheets of data and I want to make it in one sheet (All of them are in the same workbook). Link to the excel file.
I tried to use Hlookup function in excel file, something like below:
=HLOOKUP("University",Sheet1!$A$1:$G$2, 2, FALSE).

But, since I have more than 100 sheets of data, I want to find a way to drag the function and auto generate the function below the 2nd row. I have tried to use indirect function by setting a reference column in front as below but cannot deal with it.
=HLOOKUP("University", 'INDIRECT(A3)'!$A$1:$G$2, 2, FALSE)

My next option is VB code. But, I am new to VB. Anybody can help on it?

A: Place your individual sheet names in column H of the Summary sheet and the row number in column I (as helper columns) and write this formula in cell A2 of the summary sheet.
=IFERROR(HLOOKUP(A$1,INDIRECT($H2&"!A1:G"&$I2),$I2,0),)

and drag to column F and down for as many sheet rows combos you have. I used 10 rows but you can obviously make it longer or shorter as neeed.

When you are done you can filter on 0 in column A and remove any lines with no data.
If your sheet names have spaces in them, you'll need to adjust the INDIRECT formula to this:
INDIRECT("'"&$H2&"'!A1:G"&$I2)

A: best way would be "defined names" + INDIRECT + HLOOKUP (or LOOKUP) like:
defined names
name:    SList
formula: =MID(TRANSPOSE(GET.WORKBOOK(1))&T(NOW()),FIND("]",TRANSPOSE(GET.WORKBOOK(1))&T(NOW()))+1,255)

formula in cells: (this in A2 then simply autofill to G2 and thenn everything down) (you'll get a row with 0's between the sheets, which can be filtered out or deleted later (copy/paste values))
=IFERROR(HLOOKUP(A$1,INDIRECT("'"&INDEX(SList,COUNTIF($A$1:$A1,0)+2)&"'!$A:$G"),$H2,0),"")

Set H2 to 2 and for H3: (autofill down from H3)
=MAX(($H2+1)*($A2>0),2)

works perfectly for me LINK
No manual typing of sheetnames or something like that (only Column H:H as helper). Youll get rows's with 0's every time a new sheet is selected which can be filtered out. (or if you copy/paste values also can be deleted)
the +2 at ...st,COUNTIF($A$1:$A1,0)+2)&... simply tells to start with sheet 2 (if summary is the first). You may change it to +1 if you want to lookup starting with the first sheet.

A: Assuming you already have all 100+ sheet names typed out in column A, this will work whether or not you have spaces in the sheet names:
=HLOOKUP("University", OFFSET(INDIRECT(ADDRESS(1,1,1,1,A2)),0,0,2,7),2,FALSE)


text:
Q: SQL Query to designate value based upon finding a value within the previous n-rows I have a process that records when an event occurs and it is assumed that this event has an influence over the next six hours.
A table has data consisting of Date, Period, BooleanValue; where the Day is dd/mm/yyyy, the Period is a value 1-48 designating the half-hour period (there are 48 during a day) and whether an event has caused a occurred (Impact or NotImpact). As an example, a single event has occurred on 5th Jan 2011 (Period 3) and thus, the table looks like:
    Date            Period      Event
    05/01/2011      1           NotImpact
    05/01/2011      2           NotImpact
    05/01/2011      3           IMPACT
    05/01/2011      4           NotImpact
    05/01/2011      5           NotImpact

In Excel, I have created forth column and wrote a formula that looks for "IMPACT" in the 'Event' column and if found, flags the next 12 Half Hours as "IMPACT". If it doesn't find "IMPACT", the default value of "NotImpact" is used.
 =IF(IF(ISERROR(COUNTIF(E2:E13,"IMPACT")),"NotImpact",COUNTIF(E2:E13,"DIS"))>0,"IMPACT","NotImpact")

Applying this formula, to the forth column, would result it:
    Date            Period      Event       ImpactYesNo
    05/01/2011      1           NotImpact   NotImpact
    05/01/2011      2           NotImpact   NotImpact
    05/01/2011      3           IMPACT      IMPACT
    05/01/2011      4           NotImpact   IMPACT
    05/01/2011      5           NotImpact   IMPACT
    05/01/2011      6           NotImpact   IMPACT
    05/01/2011      7           NotImpact   IMPACT
    05/01/2011      8           NotImpact   IMPACT
    05/01/2011      9           NotImpact   IMPACT
    05/01/2011      10          NotImpact   IMPACT
    05/01/2011      11          NotImpact   IMPACT
    05/01/2011      12          NotImpact   IMPACT
    05/01/2011      13          NotImpact   IMPACT
    05/01/2011      14          NotImpact   IMPACT
    05/01/2011      15          NotImpact   NotImpact
    05/01/2011      16          NotImpact   NotImpact
    05/01/2011      17          NotImpact   NotImpact

I would much prefer to have this table generated in SQL (this table is residing on a SQL Server 2005 box) and I have attempted to replicate this Excel approach on there (and writing a function in Python) but with no success. I would really grateful if someone could help me out or point me in the right direction.
If I can answer any other questions about what I am asking, please do not hesitate to pop them in the comments

A: DECLARE
    @Intervals INT, -- How many periods per day
    @Lasts INT  -- Number of intervals effected
SELECT
    @Intervals  = 48,
    @Lasts = 6

-- Use CTE to calculate continous sequence #
;WITH SeqImpact ([Date], Period, [Event], Seq)
AS (Select *, Convert(int, Date) * @Intervals + Period as SEQ  from IMPACT)

SELECT
    [Date],
    Period,
    [Event],
    CASE (
            SELECT Count(*)
            FROM SeqImpact History
            WHERE
                History.Seq <= SeqImpact.Seq
                AND  History.Seq > SeqImpact.Seq - @Lasts
                AND [Event] = 'Impact'
        )
        WHEN 0 THEN 'NotImpact'
        ELSE 'Impact'
    END
    AS ImpactYesNo
FROM SeqImpact

A: You can try this. It converts your date and period to datetime and then does some calculations on that. You have to test with your data to see if the performance is good enough or not.
set dateformat dmy

;with C as
(
  select dateadd(minute, (Period - 1) * 30, cast([Date] as datetime)) as StartTime,
         [Date],
         Period,
         [Event]
  from YourTable
)
select C1.[Date],
       C1.Period,
       C1.[Event],
       coalesce(C2.[Event], C1.[Event]) as ImpactYesNo
from C as C1
  left outer join (select StartTime,
                          dateadd(hour, 6, StartTime) as EndTime,
                          [Event]
                   from C
                   where [Event] = 'IMPACT') as C2
    on C1.StartTime >= C2.StartTime and
       C1.StartTime < C2.EndTime
order by C1.StartTime

https://data.stackexchange.com/stackoverflow/q/122443/

A: declare @T table
(
  [Date] varchar(10),
  Period int,
  [Event] varchar(9)
);

-- shortened to 1 hour periods
insert into @T
select '20110501',      1,           'NotImpact' union all
select '20110501',      2,           'NotImpact' union all
select '20110501',      3,           'NotImpact' union all
select '20110501',      4,           'NotImpact' union all
select '20110501',      5,           'NotImpact' union all
select '20110501',      6,           'NotImpact' union all
select '20110501',      7,           'NotImpact' union all
select '20110501',      8,           'NotImpact' union all
select '20110501',      9,           'NotImpact' union all
select '20110501',      10,          'NotImpact' union all
select '20110501',      11,          'NotImpact' union all
select '20110501',      12,          'NotImpact' union all
select '20110501',      13,          'NotImpact' union all
select '20110501',      14,          'NotImpact' union all
select '20110501',      15,          'IMPACT' union all
select '20110501',      16,          'NotImpact' union all
select '20110501',      17,          'NotImpact' union all
select '20110501',      18,          'NotImpact' union all
select '20110501',      19,          'NotImpact' union all
select '20110501',      20,          'NotImpact' union all
select '20110501',      21,          'NotImpact' union all
select '20110501',      22,          'NotImpact' union all
select '20110501',      23,          'NotImpact' union all
select '20110501',      24,          'NotImpact' union all
select '20110601',      1,           'NotImpact' union all
select '20110601',      2,           'NotImpact' union all
select '20110601',      3,           'NotImpact' union all
select '20110601',      4,           'NotImpact' union all
select '20110601',      5,           'NotImpact' union all
select '20110601',      6,           'NotImpact' union all
select '20110601',      7,           'NotImpact' union all
select '20110601',      8,           'NotImpact' union all
select '20110601',      9,           'NotImpact' union all
select '20110601',      10,          'NotImpact' union all
select '20110601',      11,          'NotImpact' union all
select '20110601',      12,          'NotImpact' union all
select '20110601',      13,          'NotImpact' union all
select '20110601',      14,          'NotImpact' union all
select '20110601',      15,          'NotImpact' union all
select '20110601',      16,          'NotImpact' union all
select '20110601',      17,          'NotImpact' union all
select '20110601',      18,          'NotImpact' union all
select '20110601',      19,          'NotImpact' union all
select '20110601',      20,          'NotImpact' union all
select '20110601',      21,          'NotImpact' union all
select '20110601',      22,          'NotImpact' union all
select '20110601',      23,          'NotImpact' union all
select '20110601',      24,          'NotImpact';

with cte as
(
  select [Date], Period, [Event],
    ROW_NUMBER() OVER (ORDER BY [Date], Period) AS rn
  from @T
)
SELECT
    T1.[Date], T1.Period,
    ISNULL(T2.[Event], T1.[Event]),
T1.rn , T2.rn
FROM
    cte T1
    LEFT JOIN
    cte T2 ON T1.rn BETWEEN T2.rn AND T2.rn + 12 AND T2.[Event] = 'Impact'

redpajama_set_name: RedPajamaStackExchange


text:
Q: Remove characters using Regex I have a string. I need to replace all instances of a given array of strings from this original string - how would I do that?
Currently I am using...
var inputString = "this is my original string.";
var replacement = "";
var pattern = string.Join("|", arrayOfStringsToRemove);

Regex.Replace(inputString, pattern, replacement);

This works fine, but unfortunately it breaks down when someone tries to remove a character that has a special meaning in the regex.
How should I do this? Is there a better way?

A: Build the pattern using Regex.Escape:
StringBuilder pattern = new StringBuilder();
foreach (string s in arrayOfStringsToRemove)
{
    pattern.Append("(");
    pattern.Append(Regex.Escape(s));
    pattern.Append(")|");
}
Regex.Replace(inputString, pattern.ToString(0, pattern.Length - 1), // remove trailing |
    replacement);

A: Look at Regex.Escape

A: You need to escape special characters with a backslash
\

Sometimes you may need to use two backslashes
\\

A: You need to escape characters with spacial meaning of course.
var str_to_replace = "removing \[this\]\(link\)";


text:
Q: Exit Man opened from the touch bar So in terminal there is a fun feature now, as you can open a man page of the current command by using the touchbar. I failed to close the man page though. The usual q did nothing as well as esc or CTRL-C. Does anyone know how to close it?

A: It might have to do with the order of keys that you were typing that prevented q from working when you were trying to find the key to exit out of the manual.
If you press the ESC key it writes to the screen and the last line goes from END to ESC. If you then press q it doesn't close the manual but it will switch it back to END. Press q again and it should exit you out. Keep pressing q.


text:
Q: Python Enum: how to make enum member to behave like zero? I have enum and I'd like some constants acts like 0. It's not the case by default (what is strange by itself). I have tried to bind nonzero method to enum member directly, but it's not called in if statment. What is going on!? And is there clear way to make FOO behave like 0?
from enum import Enum

class A(Enum):
    FOO = 0
    BAR = 1

if A.FOO: print 'foo!'
if A.BAR: print 'bar!'

setattr(A.FOO, '__nonzero__', (lambda self:False).__get__(A.FOO, A.FOO.__class__))

if A.FOO: print 'foo!'
print A.FOO.__nonzero__()

Output
foo!
bar!
foo!
False

Upd: for Python 2.7 zvone's solution looks like this and works fine:
from enum import Enum

class A(Enum):
    FOO = 0
    BAR = 1

    def __nonzero__(self): return self!=A.FOO

if A.FOO: print 'foo!'
if A.BAR: print 'bar!'

A: There are several problems here:

*

*there is no enum in Python 2.7 (the question is tagged as 2.7) - see enum doc; perhaps you are using the enum34 backport?

*there is enum in Python 3.4 and later, but there is no __nonzero__ there (Python 3 uses __bool__ instead)

*The __nonzero__/__bool__ method, if it existed, would have to be defined on the class and not on the instance

So, finally, there is a solution in Python 3:
class A(Enum):
    FOO = 0
    BAR = 1

    def __bool__(self):
         # only return False for A.FOO
         return self != A.FOO

And the solution for Python 2:
class A(Enum):
    FOO = 0
    BAR = 1

    def __nonzero__(self):
         # return boolean value of any A
         return bool(self._value_)


text:
Q: Running a timed background job in bash I would like to execute a command in bash every 30 seconds and have it run as a background job. Form this post, I gather that using the watch command is useful. However every time I attempt to background it, it stops.

watch -n 1 'date >> dateFile.txt'

works. I can cat dateFilet.txt and see a bunch of lines.

watch -n 1 'date >> dateFile.txt' &

returns

[1]+  Stopped                 watch -n 1 'date >> dateFile.txt'

executing bg returns the same line again.
What am I doing wrong? How do I fix it? What I eventually want to do is source a file every minute or so to keep certain variables in my bash session up to date.

A: In bash, you can do this easily using the PROMPT_COMMAND variable (from man bash):

PROMPT_COMMAND
If set, the value is executed as a command prior to issuing each
                primary prompt.

So, if you add something like this to your ~/.bashrc:
PROMPT_COMMAND=". /path/to/file"

You will have any variables defined in that file available.

A: In your crontab :
* * * * * date >> dateFile.txt & sleep 30; date >> dateFile.txt &

Straightforward, no ? =)
(Better put the full PATH of the date command)
Another solution:
while true; do date >> dateFile.txt & sleep 30; done

A:
What I eventually want to do is source a file every minute or so to keep certain variables in my bash session up to date.

*

*You cannot do that from a child process.

*You cannot do that from a parent process.

*You cannot do that from any process other than the one you want it to affect.

Changing a process's environment is the same as changing a process's private memory (in fact, that's exactly what would be involved).  Absolutely not allowed!  That's why IPC is such an elaborate realm.


text:
Q: "by afternoon" or "by the afternoon" I was reading the book Advanced Grammar in Use (Martin Hewings) and there was an example:

*

*I'll be there by (the) morning / ... by (the) evening.

but …

*

*... by the afternoon, not  … by afternoon)

But when I compare "by afternoon"with "by the afternoon" using Ludwig, the phrase "by afternoon" is not just acceptable, but actually more common. Some examples are:

*

*By afternoon, Steve still hadn't arrived.

*By afternoon, the entire army was exhausted.

So I wonder: are both the phrases acceptable and do they have the same meaning?

A: Although I prefer the sound of 'by the afternoon' or 'by that afternoon', Google ngrams (several tokens checked; no false positives) show that 'by afternoon' seems quite as idiomatic as 'by the afternoon' and was probably the preferred version between the 1940s and 1970s:


text:
Q: Cocoa Button Launch outside Application I have the following setup:
A grid of 4x4 (16 total) buttons (standard NSButton buttons) in an NSWindow.
The NSWindow will come to the front when I press a hotkey combination (DDHotKey)
Now, what I'd like to do is give my buttons the following functionality:

*

*When the button is clicked, open a dialog that shows the /Applications/ directory and allow me to select any of the applications listed there.

*When the application is selected store it in a variable (I'm guessing) (or string?) and make it so that when the buttons Key Equivalent is pressed, that application launches
I'm looking around and I'm not exactly sure what to do or really where to begin looking...any clues?

I have this in my appdelegate.m file:
- (void)openDoc:(id)sender
{
    int result;
    NSArray *fileTypes = [NSArray arrayWithObject:@"td"];
    NSOpenPanel *oPanel = [NSOpenPanel openPanel];

[oPanel setAllowsMultipleSelection:YES];
result = [oPanel runModalForDirectory:NSHomeDirectory()
                file:nil types:fileTypes];
if (result == NSOKButton) {
    NSArray *filesToOpen = [oPanel filenames];
    int i, count = [filesToOpen count];
    for (i=0; i<count; i++) {
        NSString *aFile = [filesToOpen objectAtIndex:i];
        id currentDoc = [[ToDoDoc alloc] initWithFile:aFile];
    }
}
}

How do I link the button to it?

A: You can use an NSOpenPanel to choose the application.
Then to launch the application, take a look at this stack overflow question.

A: store the path to application, then when you want to open them. You can use the system() function.
system("open -a /Applications/someApplication.app");


text:
Q: How to pass parameters through link_to using POST request? I want to pass parameters through link_to in rails. However, I don't want it to be a part of the URL. I went through the answer here, however it does not help.
I am using a slim template and have something similar to this:
= link_to "Test", test_path(param1: "value1"), param2: 'value2', param3: value3, :method => :post

I want param1 to be a part of the URL, but not param2 and param3. However, params[:param2] or or params[:param3] gives me a blank value.
Any ideas on how this can be done?

A: hidden_field_tag 'token', 'VUBJKB23UIVI1UU1VOBVI@' => <input id="token" name="token" type="hidden" value="VUBJKB23UIVI1UU1VOBVI@" />

https://apidock.com/rails/ActionView/Helpers/FormTagHelper/hidden_field_tag


text:
Q: beamer's tableofcontents links to the wrong slide I compiled the following code 3 times to get the table of contents. The problem is that section names links to wrong slides. A links to B1 and B links to B2. So, it's wrong by one slide.
How can I fix it?

\documentclass{beamer}

\begin{document}

\frame{\tableofcontents}

\section{A}
\frame{A}

\section{B}
\frame{B1}
\frame{B2}

\end{document}

A: I tested your example with TeX Live 2012 and it works well.
I use the following version:
beamer.cls    2011/09/12 development version 3.20 A class for typesetting pre
sentations (rcs-revision 70f9d8411e54)


text:
Q: Which is the most effective Sniper Rifle, and where can I lay my hands on one? As with the demo, I already find my Infiltrator Shepard is leaning towards sniper rifles as a primary weapon. So, excluding anything DLC or otherwise not in the core game, which Sniper Rifle has the highest DPS and which has the highest damage per individual shot?
And where in the single player campaign can I find or buy them?

A: M-98 Widow
Base Damage: 368.3
Default ammo: 1 / 12
Found during Priority: Thessia on the ledge where the Asari sniper is.

Hope it helps

A: 'Best' is of course subjective, 'Highest Damage' will be the Geth Sniper Rifle (called The Javelin) that has the highest damage per hit of any weapon in the game, but a slow attack speed and a 'power up' time when you attack of approximately half a second. This will pretty much always one shot any non-special enemy throughout the entire game with a headshot, including in multi-player on high difficulty settings, but takes some practice to get used to the lead time on the shots.
As I said, 'Best' is subjective but my personal opinion on it is The Javelin.
How to get it:

*

*Single-player: On the path after a crashed escape pod during Rannoch: Admiral Koris. (Purchasable at Elkoss Combine Arsenal Supplies if missed during mission.)

*Multiplayer: Randomly rewarded by purchasing an item pack.
Points of interest:

*

*In single-player, the Javelin deals roughly the same damage as the M-98 Widow, however in multiplayer it deals about 20% more damage, thus placing the Javelin as the most powerful single-shot weapon in the game, Claymore aside.

*The Javelin is a very powerful piercing weapon, starting off with its own natural high piercing thickness and high damage when piercing, and when paired with the piercing mod the Javelin can even pierce thin walls to pick off enemies with headshots.

*With the highest-level piercing mod, the Javelin is able to shoot through almost any cover, including thick walls and floors. This is most observable in multiplayer, where the battlefields are on different levels and many different locales are present. In fact, a level V piercing mod allows the Javelin to fire straight through the floor of array control on Dagger and still get a one-shot body kill to standard enemies on silver.
It is also worth noting that this weapon gains bonuses from the 'Networked AI' ability, further increasing it's damage and reducing it's weight and gains additional benefit from the ability as this is a Geth weapon.

A: The Black Widow is my favorite because it has excellent DPS and one shot - one kill capacity.
While the widow and javelin have more damage per shot, if you miss you are screwed as you have to wait for a lengthy reload and reacquire your target.  With the black widow, if you miss or if your target survives your first shot (not likely), you simply pull the trigger a second time to finish him.
You can clear areas much more efficiently with the black widow. With adrenaline rush it is not uncommon to kill 3 enemies per reload. In the right hands, the black widow can dispatch entire squads of enemies in seconds, even on the higher difficulty levels.
I should note that I have not played multiplayer, so I don't know if it has been nerfed or is viable for that mode.  For single player though, the black widow is the best. The whole point of being a sniper is to kill your enemies before they can get close to you, and there is no better weapon in the game for doing that than the black widow.

A: Asking which sniper rifle has the highest DPS is kind of a bad question, IMO. The most important question that you should be asking is, "How easy is it to hit successive headshots".
All the damage in the world isn't going to save you if you can't hit jack squat.
The M98 Widow had the highest DPS of any sniper rifle in the last game, and its probably still one of (if not the) best in this game also. The problem with this from a DPS standpoint is that it is single shot / reload.
The Black Widow (available from Spectre Requisitions) does almost the same amount of damage as a Widow, but it can fire multiple times without reloading, meaning it should do superior damage if you're more accurate. (You can also get multiple damage bonuses from cloak if you're fast enough, something impossible with the widow because of the reload).
You should also check out the Javelin, which is found on Rannoch. It's like the Widow, but focused on shields/barriers instead of just armor, which makes it very good for banshees.

A: Well, the Raptor has the highest firing rate of all the sniper rifles, and in my experience it took me less time to take out an Atlas with it than when using the M-98 Widow.

A: Krysae Sniper Rifle X with mods Sniper Rifle High-Velocity Barrel V and Sniper Rifle Concentration V. Enemies just explode in pieces, this is half sniper half rocket launcher.
For one who likes it 100% sniper but also have serveral shots, good fire rate and fast reload, I'd say N7 Valiant. Same modes as above.

A: For higher difficulty use nothing, but "Black Widow". Stay away from the single shot rifle. You can't single shot an enemy even if it has a tiny bit of protection.

A: I was addicted to the Black Widow. I played it twice so I could upgrade the Black Widow V to Black Widow X. It's just super insane. Using cyro ammo is the funniest part. One hit kills except headshots has an awesome "explosion" animation where the enemies literally breaks and shatters into small pieces.
Then there is it's predecessor, the ultimate M98 Widow. I liked it, but due to it one hit per reload, I didn't enjoy it as much as the Black Widow. But then I found the Javelin addictive.
I upgraded my Javelin to Javelin X, and BANG! This sweetie packs a punch like none other. The sound of the shot is like music to my ears. The scope is the best feature. It even lets me CLEARLY see cloaked enemies like the Geth Hunter and Phantoms. The thermal imaging system highlights the foes in purple and allies in blue. If you happen to see someone crouched behind cover using the Javelin X, shoot it. The thermal imaging systems will show hidden enemies through cover which you CAN shoot. Naturally penetration is a mod but the Javelin is a built in penetrator. I'm hooked to the Javelin and Black Widow. They're the best sniper rifles. Note I haven played Multiplayer so base this comment on SP

A: Playing only in Single Player, my preference is the Black Widow X. It still takes me seven rounds, (5 if they are strictly head shots) to take down a Banshe - which must be done quickly if you are using Disruptor Ammo. I use the concentrator mod V and the extended barrel for higher damage. It 'one shot' kills everything else, just about everything else - especially if aiming for the head. I like the 3 rounds capability before having to reload. I liked the one shot Black Widow and M98 Widow too but, too slow when hordes are storming you. I would like to see my bullets pass through lesser targets, (like husks), and do damage or kill what is behind them - even though there is something "wonderful" in seeing the green luminescent spray of a husk exploding in the scope when you overkill it using disrupter ammo.\


text:
Q: How to convert any video to .avi with wmv1 codec using ffmpeg/avconv? I have installed ffmpeg to convert a video. I am trying to convert a .mp4 to a .avi video with the codec wmv1. How to do this?
I am using the command avconv in a Kubuntu terminal. Last attempt I did this:
avconv new_video.avi wmv1 old_video.mp4

And I always got this message:
Unable to find a suitable output format for 'wmv1'

Anyone can help me?

A: Important note: ffmpeg is not avconv – there's a difference between those. Many simple commands will just work fine in either tool, but you should always download a recent ffmpeg version instead of doing an apt-get install ffmpeg, because you won't get the "real" ffmpeg.

Your command is quite off. Have you had a look at any examples or the documentation? We also have a blog post on ffmpeg.
You first have to specify an input file with -i <file>, then the encoding parameters, and then the output file:
ffmpeg -i old_video.mp4 -c:v wmv1 new_video.avi

That's the most basic command to achieve what you want. The audio will be converted to MP3 here using the libmp3lame encoder. Choose a bitrate by setting -b:v 500k or whatever you need. Same for audio with -b:a 128k or similar.


text:
Q: Using polarity reversal to limit voltage My electrical experience is limited to ordinary soldering of resistors, pots, and relays to control my model railroad layout, so please excuse my lack of more advanced logic circuit and semiconductor knowledge.
What I'd like to do is reduce 7 volts to 4 volts on a particular track when a photocell trips a DC polarity reversal (½ amp max current). The idea is that a train on this track would shuttle back and forth in automated mode. I've installed the photocell device, which senses the train and reverses track polarity, causing the train to stop and run in the opposite direction.
The problem is that the track has a steep downgrade and  voltage needs to be reduced to 4 volts to avoid excessive speed going downhill. Of course, I can manually vary the track voltage at the transformer, but that defeats the idea of having the train continuously shuttle back and forth in automated, hands-off mode.
Any suggestions for a circuit that would block the 7 volts and direct the current flow to a resistor or pot limiting track voltage to 4 volts, when the DC current changes from positive to negative?

A: Thanks, immibis, for your answer. As you suggested, I attached a 5 watt diode to the sensor's 7v + output and a 10 ohm resistor in parallel to reduce voltage to 3v when polarity reverses to negative, and that solved the problem.


text:
Q: OpenGL with PyFace How I can write an OpenGl application using Enthought Framework? I created a TasksApplication and I am stuck on this tutorial, I don't know what I can use instead PythonEditor there. I need to create something where I will be able to render.
UPDATE:
I changed the code to
def create(self, parent):
    widget = GLWidget(parent)
    self.control = widget

Where GlWidget is implemented like in this example.
And I have a runtime crash. But I am able to run the GL script from the example above.
UPDATE2:
Log file
UPDATE4:
Code was updated according to @Robert Kern suggestions. Now it works.
Min Example
MinExample 7z

A: The control trait of a TaskPane is just the Qt widget object that you are using. In the example that you link, we happen to be getting it from another PyFace widget that wraps a Qt widget in a similar fashion, so we just grab the control attribute from it. You should just directly use a QGLWidget as the control of your pane. Please consult the Qt documentation for how to use it. You can use PyOpenGL in the paintGL(), etc. methods to do the actual rendering.


text:
Q: Polyline doesn't draw a line on my clustered Google map markers I have 3 points of which i want a polyline to be drawn but a polyline isn't visible.
First and foremost , the 3 markers are available on the map , so i tried to join them with a polyline and it refused, and to me the code seems fine, but a polyline is not visible , How can i improve my code.
Below is my code:
 @Override
    public void onMapReady(GoogleMap googleMap) {

        mMap = googleMap;

        setUpClusterer(mMap);
    }

    //clustered map

    private void setUpClusterer(GoogleMap mMap) {
        // Position the map.

        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-23.684, 133.903), 4));
        // Initialize the manager with the context and the map.
        // (Activity extends context, so we can pass 'this' in the constructor.)
        mClusterManager = new ClusterManager<MyItem>(this, mMap);

        // Point the map's listeners at the listeners implemented by the cluster
        // manager.
        mMap.setOnCameraIdleListener(mClusterManager);
        mMap.setOnMarkerClickListener(mClusterManager);

        // Add cluster items (markers) to the cluster manager.
        addItems(mMap);
    }

    private void addItems(GoogleMap mMap) {

        // Set some lat/lng coordinates to start with.
        double lat = 51.5145160;
        double lng = -0.1270060;
        HashMap<Double,Double> hm = new HashMap<>();

       /* new LatLng(-34.747, 145.592),
                new LatLng(-34.364, 147.891),
                new LatLng(-33.501, 150.217),*/
        hm.put(-34.747,145.592);
        hm.put(-34.364,147.891);
        hm.put(-33.501,150.217);

        // Add ten cluster items in close proximity, for purposes of this example.

        for(Map.Entry m:hm.entrySet()){
            System.out.println(m.getKey()+" "+m.getValue());
            MyItem offsetItem = new MyItem(Double.parseDouble(m.getKey().toString()),Double.parseDouble(m.getValue().toString()));
            mClusterManager.addItem(offsetItem);

            Polyline polyline = mMap.addPolyline(new PolylineOptions()
                    .clickable(true)
                    .add(
                            new LatLng(Double.parseDouble(m.getKey().toString()), Double.parseDouble(m.getValue().toString()))

                    ));
            stylePolyline(polyline);

        }

    }

A: You are creating one Polyline for each point. You need to create some kind of iterable (an ArrayList for example), add the LatLngs to it and then add all the points to a new Polyline:
List<LatLngs> latLngs = new ArrayList<LatLng>();

for(Map.Entry m:hm.entrySet()){
    MyItem offsetItem = new MyItem(Double.parseDouble(m.getKey().toString()),Double.parseDouble(m.getValue().toString()));
    mClusterManager.addItem(offsetItem);

    latLngs.add(new LatLng(Double.parseDouble(m.getKey().toString()), Double.parseDouble(m.getValue().toString())));
}

Polyline polyline = mMap.addPolyline(new PolylineOptions()
                            .clickable(true)
                            .addAll(latLngs));
stylePolyline(polyline);


text:
Q: regex. how to exclude a substring from the result after it matches the pattern I wonder how i can exclude a substring from the result after it matches the pattern.
example:
<?php __('string1');?>
<?php __("string2");?>

I want to get only the strings passed as parameters to the __() function. i tried this regex:
'/__\(((\'([^\']+)\')|(\"([^\"]+)\"))/'

but that returns 'string1' and "string2" wrapped in single quotes and double quotations.
how can i exclude single quotes and double quotations?

A: You want to try using non-capturing groups - (?:ABC)

A: *

*Use (?:  ) appropriately. These are for grouping that you don't want to capture.

*If you have the quotations inside the capture (  ), then the quotes will be included in the capture. If you put the quotes outside, then they will not be included.

*You have more (  ) than you need. | has the least priority in association.

*You are escaping more than you need. Quotations don't need to be escapted.

*Since you are using [^'] and [^"], you don't have to specify for close quotes/parens.

A fix would be like:
'/__\((?:'([^']+)|"([^"]+))/'

A: You can use Lookahead and Lookbehind or make the string inside of the quotes a group.

A: Try this
'/__\(('|")([^\1]+)\1\)/'
       ^1^  ^^2^^^

You can see it online here on Regexr
Every time when you open a round bracket you create a capturing group. So, if you don't want it use (?:) this would define a non capturing group. I don't use this here. I rewrote your regex a bit. In my first group I check if there are ' or " and store them into group 1. later on I use the backreference \1 to this group one, to use the correct character.
Your result is then stored always into group 2. How you access this result depends on your used language.


text:
Q: How to run an @MainActor func synchronously? I have an @MainActor function that I want to run synchronously. So far, I've come up with this:
    static func runOnMainThreadAndWait<T>(
        action: @MainActor @Sendable () throws -> T
    ) rethrows -> T {
        if Thread.isMainThread {
            return try unsafeExecuteWithoutActorChecking(action)
        } else {
            return try DispatchQueue.main.sync(execute: action)
        }
    }

    @preconcurrency
    private static func unsafeExecuteWithoutActorChecking<T>(
        _ action: () throws -> T
    ) rethrows -> T {
        return try action()
    }

This works, but the first case of that if statement feels janky, and with -warn-concurrency even unsafeExecuteWithoutActorChecking(_:) doesn't suffice:

Converting function value of type '@MainActor @Sendable () throws -> T' to '() throws -> T' loses global actor 'MainActor'

What's the safest way to implement this call?

Edit, for more details:
The function is usually called from the main thread -- specifically, when a view is created -- and the return value is needed to render the views. It was originally written under the assumption that this would be the only way it was called, so no safety mechanisms were put in place. I have been going back through the code and adding @MainActor annotations and similar safety checks where appropriate. Here, I need to support the common case (calling it synchronously while on the main thread) while making the incorrect behavior (running on a background thread) impossible. I added an asynchronous overload that calls await MainActor.run ... as a stopgap measure, but most of the time awaiting it is unnecessary and only adds noise.
I've seen a variation on this solution from before Swift's structured concurrency:
static func runOnMainThreadSync<T>(action: () throws -> T) rethrows -> T {
    if Thread.isMainThread {
        return try action()
    } else {
        return try DispatchQueue.main.sync(execute: action)
    }
}

and I thought I could just add @MainActor to this.

A: Running something in the @MainActor context does not mean that you are running on the main thread.
It does mean that your code will run synchronously relative to other code running on the Main Actor, which includes code running in the main thread.  But all that means is that while your code is running in the main actor context, if it's not running on the main thread, then the main thread will be suspended. (no other main actor code will be running in parallel)
So your if check is not just janky, it's bogus.
You don't say much about the calling context where you are trying to run something on the main actor, but the easiest solution is probably to use
await MainActor.run {
    ... some code here ...
}

A: You said:

I've seen a variation on this solution from before Swift's structured concurrency:
static func runOnMainThreadSync<T>(action: () throws -> T) rethrows -> T >{
   if Thread.isMainThread {
       return try action()
   } else {
       return try DispatchQueue.main.sync(execute: action)
   }
}

and I thought I could just add @MainActor to this.

You can (and simplify it significantly):
extension MainActor {
    @MainActor static func runOnMainThread<T>(action: @MainActor @Sendable () throws -> T) rethrows -> T {
        try action()
    }
}

But I would advise against this. One could use MainActor.run.
Or, even better, we can just mark the methods that must be run on a particular actor, and the compiler will perform compile-time checks (rather than the above run-time checks). If you call it from a context not isolated to the particular actor the compiler will tell you that you have to await. And only if you have a series of await suspension points to the main actor and would like to wrap that in a single task would you ever need to use MainActor.run.
But with Swift concurrency, there is no guessing, like we might have had to do in GCD. Nowadays, this runOnMainThreadSync pattern (anti-pattern?) is unnecessary. In Swift concurrency, we are generally explicit about which methods and properties are actor isolated, eliminating the ambiguity.


text:
Q: Find non trivial homomorphism $\mathbb{Z}/q\mathbb{Z} \rightarrow \text{Aut}(\mathbb{Z}/p\mathbb{Z})$ Let $H= \mathbb{Z}/p\mathbb{Z}$ and $F=\mathbb{Z}/q\mathbb{Z}$ with $p,q$ primes. As indication, I got that $${\rm Aut}(H) \cong (\mathbb{Z}/p\mathbb{Z})^\times \cong \mathbb{Z}/(p-1)\mathbb{Z}.$$
I have to show that if $q$ divides $p-1$ there exist a non-trivial homomorphism $\psi$: $F \rightarrow{\rm Aut}(H)$.
I understand if $q$ divides $p-1$ then there is an element of order $q$ in $\mathbb{Z}/(p-1)\mathbb{Z}$. But, the problem I have, is that I don't really understand how to construct homomorphisms so I'd like to have a step-by-step explanation if possible, please. For me, this non-trivial homomorphism is simply of form $\psi([x]_q): y \rightarrow y \cdot g^x$, where $g$ is generator of $(\mathbb{Z}/p\mathbb{Z})^\times$. But I was told that it is wrong.
Thanks in advance and have a nice day.

A: The map in your problem could represent the morphism induced by a semidirect product of a $p$-Sylow and a $q$-Sylow $\mathbb Z_p\rtimes_{\psi}\mathbb Z_q$.
Consider the homomorhism $\psi: \mathbb Z_q\to \operatorname{Aut}(\mathbb Z_p)$ you have that $|\psi(\mathbb Z_q)|$ divides $|\mathbb Z_q|$ and $|\operatorname{Aut}(\mathbb Z_p)|$, where $|\operatorname{Aut}(\mathbb Z_p)|=\varphi(p)=p-1$ (for example the two groups could be $\mathbb Z_2$ and $\mathbb Z_3$).
Note: Since $q$ divides $|\operatorname{Aut}(\mathbb Z_p)|$, which is a cyclic group, you could take the homomorphism that maps a generator of $\mathbb Z_q$ to a generator of the (single) $q$-group in $\operatorname{Aut}(\mathbb Z_p)$ (in a $p$-cyclic group $P$ every element of $P$ has the same order of the group and generate it).
If $q|p-1$, we can assume $|\psi(\mathbb Z_q)|=q$ and for the first theorem of isomorphism, we know that $$|\psi(\mathbb Z_q)|=q=|F:Ker(\psi)|\implies|Ker(\psi)|=\dfrac{|\mathbb Z_q|}{q}=1 \implies \psi\ne id_{\mathbb Z_q}$$
Since the order of the Kernel of the morphism is not equal to the order of the group, this shows that $$\exists\psi\in \operatorname{Hom}(\mathbb Z_q,\operatorname{Aut}\mathbb Z_q)\text{, where }\psi\text{ is non-trivial and it is also injective}.$$


text:
Q: I can't make a message box I want my form to display an error message that pops up when the user doesn't enter a number or if the text box is blank. I have tried:
 //If nothing is inserted in text, error box.
        int value = 0;
        if (string.IsNullOrWhitespace(txtBegin.Text) || !int.TryParse(txtBegin.Text, out value)) // Test for null or empty string or string is not a number
            MessageBox.Show("Please enter a number!");
        else
            MessageBox.Show(string.Format("You entered: {0}!", value));

It is giving me an error:'string' does not contain a definition for 'IsNullOrWhitespace'

A: int value = 0;
if (string.IsNullOrWhitespace(txtBegin) || !int.TryParse(txtBegin, out value) ) //Test for null or empty string or string is not a number
  MessageBox.Show("Please enter a number!");
else
  MessageBox.Show(string.Format("You entered: {0}!", value));

A: try
if (string.IsNullOrWhitespace(txtBegin)){
    MessageBox.Show("Please enter a number!");
}

A: It is actually string.IsNullOrWhiteSpace() - with capital S. Or try string.IsNullOrEmpty() instead.

A: This one would do. Check if there is a value in the textbox and then remove the space, and check if the length is zero.
if (txtBox1.Text.Length>0 && txtBox1.Text.Trim().Length==0)
{
MessageBox.Show("Please enter a number!");
}


text:
Q: value attribute on  tag not selecting default option Perhaps i'm misunderstanding here, but given the following html:
<select value="2">
    <option value="1">Something</option>
    <option value="2">Something else</option>
</select>

I would expect "Something else" to be the default selected option. However, it does not seem to be. Why is this, and what should I be doing differently?

A: React JS
Some coding implementations such as ReactJS allow you to use a value attribute with the <select> tag so this would be perfectly valid code:
<select value="2">
    <option value="1">Something</option>
    <option value="2">Something else</option>
</select>

So if you are seeing code examples like this it is likely because it is in React or other similar library/framework.
Of course, with this approach, typically you would want to specify the value in state, so that it is updateable.
HTML with Attribute Minimization:
However, if you are using purely HTML you must use the selected attribute in your <option> tag as follows:
<select>
    <option value="1">Something</option>
    <option value="2" selected>Something else</option>
</select>

HTML with Full Attribute Specification:
The above uses attribute minimization, but you can also specify the full form if you want:
<select>
    <option value="1">Something</option>
    <option value="2" selected="selected">Something else</option>
</select>

A: You use selected attribute on an option element to specify default option.
<select>
    <option value="1">Something</option>
    <option value="2" selected="selected">Something else</option> // this is default
</select>

select elements do not have a value attribute.

A: The only way to have a default option is to have selected in the option tag.
<SELECT>
<OPTION>Something
<OPTION SELECTED>Something Else

A: The <select> element does not have a value attribute so that is ignored. So, you have a single selection <select> and none of its <option> elements have the selected attribute, that means that the first <option> is taken as the default selection.

A: I know this post is quite old but in case anyone else is struggling with this you can implement the functionality you are looking for using jquery.
The full code using php would be something like this
PHP
if ($_SERVER['REQUEST_METHOD']== "POST") {
$thing = $_POST['things'];
} else {
$thing ="";
}

HTML
<select name='things' value="<?php echo $thing; ?>">
    <option value="1">Something</option>
    <option value="2">Something else</option>
</select>

JQUERY
$(function() {
    $("select[value]").each(function() {
        $(this).val(this.getAttribute("value"));
    });
}); //end document ready

This will allow the select options chosen by the user to remain selected
after the page has re-loaded via post instead of returning
to the default values.

A: You have to use select attribute. in below code, a swift option will be selected by default
<select name="myCar" id="car">
            <option value="ind">Indica</option>
            <option value="swf" selected>Swift</option>
 </select>


text:
Q: Duplicate request sent at fixed time interval on tomcat 5.5 mod_jk connector Configuration on tomcat -
mod_jk connector
worker.properties -
worker.list=tomcat
worker.tomcat.type=ajp13
worker.tomcat.host=localhost
worker.tomcat.port=7615

Problem Statement -
For heavy load data, when the browser sends a request to my application, after exactly 3 minutes i can see another duplicate request being sent to my application.
I tried the following things -
1) For small load data, I tried putting thread.sleep for 5 minutes, and the result was duplicate request sent to my application.
2) I also tried configuring the worker.properties with reply_timeout, socket_timeout. But it keeps on sending duplicate request.
3) I also deployed my application on Tomcat 6, but I got the same result.
The mod_jk logs -
[Mon Nov 12 11:09:04 2012] [23690:1908194448] [info] init_jk::mod_jk.c (3183): mod_jk/1.2.28 initialized
[Mon Nov 12 11:15:32 2012] [23692:1908194448] [info] ajp_send_request::jk_ajp_common.c (1496): (tomcat) all endpoints are disconnected, detected by connect check (1), cping (0), send (0)
[Mon Nov 12 11:15:54 2012] [23797:1908194448] [info] ajp_process_callback::jk_ajp_common.c (1788): Writing to client aborted or client network problems
[Mon Nov 12 11:15:54 2012] [23797:1908194448] [info] ajp_service::jk_ajp_common.c (2447): (tomcat) sending request to tomcat failed (unrecoverable), because of client write error (attempt=1)
[Mon Nov 12 11:15:54 2012] [23797:1908194448] [info] jk_handler::mod_jk.c (2608): Aborting connection for worker=tomcat
[Mon Nov 12 11:16:31 2012] [23694:1908194448] [info] ajp_send_request::jk_ajp_common.c (1496): (tomcat) all endpoints are disconnected, detected by connect check (1), cping (0), send (0)

I do not get any error in the access.log.
Could there be a network connection issue? If yes, then what is the possible solution to this problem?
Thanks.


text:
Q: eclipse cdt add multiple libraries Is there any way to add multiple libraries or only one by one in C/C++ Build --> Settings --> MinGW C++ Linker --> Libraries (-l) ?
What I mean is there a way just to copy from somewhere (some txt file for example) all of the names of libraries and then to paste them into the Libraries (-l) field, the same way it could be done in Visual Studio 2010?

Also, where does eclipse stores information about this? I have to rename a lot of libraries (from opencv245 to opencv246) so I guess if it is stored in some XML file I could just run search and replace tool on it's content.

A: I'm using Eclipse (Kepler) with CDT on CentOS and it appears that my project libraries (-l) and library paths (-L) are in the .cproject XML file located in the project directory. There is a lot in there but you should be able to find it under the appropriate tool XML entry. (I'm using Linux GCC.) Here's mine:
<tool id="cdt.managedbuild.tool.gnu.cpp.linker.exe.debug.429094553" name="GCC C++ Linker" superClass="cdt.managedbuild.tool.gnu.cpp.linker.exe.debug">
  <option id="gnu.cpp.link.option.libs.2011755342" name="Libraries (-l)" superClass="gnu.cpp.link.option.libs" valueType="libs">
    <listOptionValue builtIn="false" value="common"/>
    <listOptionValue builtIn="false" value="customapi"/>
  </option>
  <option id="gnu.cpp.link.option.paths.1035898902" name="Library search path (-L)" superClass="gnu.cpp.link.option.paths" valueType="libPaths">
    <listOptionValue builtIn="false" value=""${workspace_loc:/common/Debug}""/>
    <listOptionValue builtIn="false" value=""${workspace_loc:/customapi/Debug}""/>
  </option>
  <inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.198247885" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
    <additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
    <additionalInput kind="additionalinput" paths="$(LIBS)"/>
  </inputType>
</tool>


text:
Q: Переход из TableView в DetailView. Собсно есть  TableView содержащий некое количество ссылок. При нажатию на ячейку ссылка передается в следующий вью и там уже скачивается картинка. Система оказалась неудобной и надо бы ее исправить, потому что если картинка большая, то приложение "зависает". К тому же где-то вычитал, что Яблоко рекомендует, чтобы следующий вью загружался немедленно. Отсюда и вопрос - как все это дело поправить?
Немного кода:
Tableview.m:
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.navigationController setToolbarHidden:NO];

    _urls = @[@"http://host.ru/288270_732748.jpg",
              @"http://host.ru/288270_732749.jpg",
              @"http://host.ru/288270_732750.jpg",
              @"http://host.ru/288270_732751.jpg",
              @"http://host.ru/288270_732752.jpg"
              ];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_urls count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    if (cell) {
        cell.textLabel.text = [NSString stringWithFormat:@"%d", indexPath.row+1];
    }

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    if ([segue.identifier isEqualToString:@"DetailView"]) {
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
        DetailViewController *destViewController = segue.destinationViewController;
        destViewController.downloadedimage = [_urls objectAtIndex:indexPath.row];
    }
}

А так получаем картинку в DetailView.m:
NSURL *url = [NSURL URLWithString:_downloadedimage];
NSData *data = [NSData dataWithContentsOfURL:url];
self.img = [[UIImage alloc] initWithData:data];
self.imageView = [[UIImageView alloc] initWithImage:_img];

Обновление
Глупо наверное, но я впихнул в DetailView вот это для загрузки картинки:

[self.imageView sd_setImageWithURL: [NSURL URLWithString:_downloadedimage]
               placeholderImage:[UIImage imageNamed:@"123.png"]];

И почему-то ничего не получилось =\  Я что-то не то сделал же, да?
A: Загружайте в backgroung. Открывайте сразу экран и тут же начинаете грузить в фоновом потоке, даже прогресс можно показать. Рекомендую использовать либу, коих много, я пользуюсь SDWebImage - без нареканий, обновляется, работает без сбоев, кэширует на диск и в память, есть категории для UIKit овых классов (UIImageView, UIButton и тд.), поддерживает блоки и прогресс загрузки.
https://github.com/rs/SDWebImage
Скажем, код в самом простом случае будет выглядеть так:
[self.imageView setImageWithURL: pictureURL placeholderImage:[UIImage imageNamed:@"placeholder.png"]];


text:
Q: How to delete unwanted quotation marks in dictionary I have this file:
shorts: cat, dog, fox
longs: supercalifragilisticexpialidocious
mosts:dog, fox
count: 13
avglen: 5.6923076923076925

cat 3
dog 4
fox 4
frogger 1
supercalifragilisticexpialidocious 1

I want to convert this into a dictionary with the keys as shorts,longs,mosts,counts, and avglen and the values as whats after the colons. For the last part. that would be a dictionary within the dictionary.
I have this code:
def read_report(filename):
list1 = []
d = {}
file_name = open(filename)
for line in file_name:
    list1.append(line[:-1])
d = dict(zip(list1[::2], list1[1::2]))
file_name.close()
return d

and the result is:
{'mosts: dog, fox': 'count: 13', 'shorts: cat, dog, fox': 'longs: supercalifragilisticexpialidocious', 'cat 3': 'dog 4', 'fox 4': 'frogger 1', 'avglen: 5.6923076923076925': ''}

How do I get rid of the unwanted colons and change the placement of the quotation marks so that it looks like a valid dictionary?

A: Try out JSON, it is a standard library onboard. Your file would look like this.
'{"shorts": ["cat", "dog", "fox"], "longs": "supercalifragilisticexpialidocious", "mosts": ["dog", "fox"], "count": 13, "avglen": "5.6923076923076925", "cat": 3, "dog": 4, "fox": 4, "frogger": 1, "supercalifragilisticexpialidocious": 1}'

And you python script will be like this.
import json
f = open('my_file.txt','r')
my_dictionary = json.loads(f.read())
f.close()

print my_dictionary

The output:
{u'count': 13, u'shorts': [u'cat', u'dog', u'fox'], u'longs': u'supercalifragilisticexpialidocious', u'mosts': [u'dog', u'fox'], u'supercalifragilisticexpialidocious': 1, u'fox': 4, u'dog': 4, u'cat': 3, u'avglen': u'5.6923076923076925', u'frogger': 1}

JSON! is so cool!

A: Assuming your file is named txtfile.txt:
lines = open("txtfile.txt").readlines()
results = {}
last_part = {}
for line in lines:
    if line.strip() == "":
        continue
    elif line.startswith(tuple("shorts: longs: mosts: count: avglen:".split())):
        n, _, v = line.partition(":")
        results[n.strip()] = v.strip()
    else:
        n, v = line.split(" ")
        last_part[n.strip()] = v.strip()
results['last_part'] = last_part
print results

will output:
{'count': '13', 'shorts': 'cat, dog, fox', 'longs': 'supercalifragilisticexpialidocious', 'mosts': 'dog, fox', 'avglen': '5.6923076923076925', 'last_part': {'frogger': '1', 'fox': '4', 'dog': '4', 'supercalifragilisticexpialidocious': '1', 'cat': '3'}}`


text:
Q: A two column layout with transitions and divs? I've tried to put a transitioning div next to a paragraph and for some reason it doesn't work?
I'm not that good with html so can someone help me out?
.left {
float: left;
clear: both;
width: 200px;
    overflow: hidden;
margin-right: 0px;
padding-right: 0;
text-decoration: none;
display: table-column;
}

.right {
width: 50%;
float: right;
overflow: hidden;
text-align: right;
display: table-column;
}

.left, .right {
display: table-column;
}

</style>

home

about

projects

blog

contact

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis ullamcorper interdum facilisis. Quisque imperdiet purus ac tellus ultrices ultricies. Sed massa arcu, sagittis quis tellus laoreet, dapibus dictum neque. Nam fermentum enim ligula, quis vulputate arcu molestie et. Sed libero turpis, ultricies id pulvinar non, suscipit ut turpis. Ut nec nisl a odio laoreet commodo ac vitae orci. In eget sem luctus, pellentesque tellus eu, cursus nisl. Duis fringilla tellus quam, sit amet mollis lacus volutpat vel. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec ultrices nibh id lacus molestie porttitor. Proin quis euismod lectus. Vestibulum a elit mollis, maximus diam ac, consequat ante.

Full Code Here

A: I'm not exactly sure what you're asking to have fixed in the question, but I'm just going to assume you want that right
 to be parallel with the top of the navigation.
Only thing I changed:
.right {
    width: 50%;
    float: right;
    overflow: hidden;
    text-align: right;
    position: relative;
    margin-top: -375px;  // Added this

}

This won't look very good on mobile as the div's start to overlap so you'll need to do an @media css statement to update the code after a certain width:
@media all and (max-width: 700px) {
.right {
    margin-top: 0px;
    }
}

Here it is on jsFiddle: http://jsfiddle.net/wdrpkjap/5/


text:
Q: Android flip image animation I want to flip image in android through translate animation.
eg:- suppose i have one card. when translate animation starts it shows the card into the new position. now here the card should flip? from backside to front.
how can i do that.?

A: The name of the example in APIdemos is :
Rotate3dAnimation.java
Just check the below given link also. It can give you a good idea in solving your problem.
android-animations-3d-flip
Thanks,
Sen

A: You can have a look at the API demos, there is an example given there. It's really great!


text:
Q: How many conjugacy classes of cyclic subgroups of order $p^2$ does $\operatorname{GL}_{n}(\Bbb Z / p\Bbb Z)$ have? $\DeclareMathOperator\Hom{Hom}\DeclareMathOperator\GL{GL}\DeclareMathOperator\Aut{Aut}$Let $f\in \Hom((\Bbb Z/p^2\Bbb Z),\GL_{n}(\Bbb Z / p\Bbb Z))$ be an injective homomorphism.  What is the number of isomorphism classes of semidirect products of the form $$(\Bbb Z/p\Bbb Z)^{n}\rtimes_{f}(\Bbb Z/p^2\Bbb Z)?$$
This allows us to compute the number of conjugacy classes of cyclic subgroups of order $p^2$ in $\GL_{n}(\Bbb Z / p\Bbb Z)=\Aut((\Bbb Z/p\Bbb Z)^{n})$.


text:
Q: BigQuery - how to change the order of the schema with nested columns when creating a view? I want to change the schema of the nested on my VIEW.
But BigQuery won't do it because I'm calling the record "productPrice".
Indeed, if I don't call this, I can't keep it nested in my view.
Error Message when i use "productPrice"
Column xx  in UNION ALL has incompatible types: STRUCT<type STRING, price DOUBLE, currency STRING, ...>, STRUCT<taxRate DOUBLE, taxType STRING, priceStartDate STRING, ...> at [xx:x]

table1
productPrice                 RECORD     NULLABLE
productPrice.type            STRING     NULLABLE
productPrice.price           FLOAT      NULLABLE
productPrice.currency        STRING     NULLABLE
productPrice.priceStartDate  STRING     NULLABLE
productPrice.taxRate         FLOAT      NULLABLE
productPrice.taxType         STRING     NULLABLE

table2
productPrice                 RECORD     NULLABLE
productPrice.taxRate         FLOAT      NULLABLE
productPrice.taxType         STRING     NULLABLE
productPrice.priceStartDate  STRING     NULLABLE
productPrice.currency        STRING     NULLABLE
productPrice.price           FLOAT      NULLABLE
productPrice.type            STRING     NULLABLE

Request with productPrice
CREATE VIEW product_view AS
SELECT
 productPrice,
 productPrice.taxRate,
 productPrice.taxType,
 productPrice.priceStartDate,
 productPrice.currency,
 productPrice.price,
 productPrice.type,
from table1
UNION ALL
SELECT
 productPrice,
 productPrice.taxRate,
 productPrice.taxType,
 productPrice.priceStartDate,
 productPrice.currency,
 productPrice.price,
 productPrice.type,
FROM table2

Request without productPrice
CREATE VIEW product_view AS
SELECT
 --productPrice,
 productPrice.taxRate,
 productPrice.taxType,
 productPrice.priceStartDate,
 productPrice.currency,
 productPrice.price,
 productPrice.type,
from table1
UNION ALL
SELECT
 --productPrice,
 productPrice.taxRate,
 productPrice.taxType,
 productPrice.priceStartDate,
 productPrice.currency,
 productPrice.price,
 productPrice.type,
FROM table2

Result without "productPrice" in the view
type             STRING     NULLABLE
taxRate          FLOAT      NULLABLE
taxType          STRING     NULLABLE
priceStartDate   STRING     NULLABLE
currency         STRING     NULLABLE
price            FLOAT      NULLABLE

A: Below is for BigQuery Standard SQL
#standardSQL
SELECT
  STRUCT(
    productPrice.taxRate,
    productPrice.taxType,
    productPrice.priceStartDate,
    productPrice.currency,
    productPrice.price,
    productPrice.type
  ) AS productPrice
FROM table1
UNION ALL
SELECT
  STRUCT(
    productPrice.taxRate,
    productPrice.taxType,
    productPrice.priceStartDate,
    productPrice.currency,
    productPrice.price,
    productPrice.type
  )
FROM table2


text:
Q: PubSub topic name as ValueProvider in Dataflow python throws TypeError Is there an option to pass topic name as input?
This is a simple example
  class MyOptions(PipelineOptions):
  @classmethod
  def _add_argparse_args(cls, parser):
    parser.add_value_provider_argument(
      '--input-topic',
      default='projects/project/topics/test'
    )

if __name__ == '__main__':
  logging.getLogger().setLevel(logging.INFO)

  c_options = PipelineOptions().view_as(MyOptions)
  pipline_options = PipelineOptions(streaming=True, save_main_session=True)

  with Pipeline(options=pipline_options) as pipeline:
    (
      pipeline
      | io.ReadFromPubSub(topic=c_options.input_topic)
      | io.WriteToText('...')
    )

when I'm tryign to build a template
  python -m main \
    --runner DataflowRunner \
    --project project \
    --staging_location gs://.../staging \
    --temp_location gs://.../temp \
    --template_location gs://.../templates/mytemp \
    --region eu-west1

I got
Traceback (most recent call last):
  File "/usr/lib/python3.10/runpy.py", line 196, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "/usr/lib/python3.10/runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "/home/me/dataflow/iot/main.py", line 32, in <module>
    | io.ReadFromPubSub(topic=c_options.input_topic).with_output_types(bytes)
  File "/home/me/dataflow/env/lib/python3.10/site-packages/apache_beam/io/gcp/pubsub.py", line 256, in __init__
    self._source = _PubSubSource(
  File "/home/me/dataflow/env/lib/python3.10/site-packages/apache_beam/io/gcp/pubsub.py", line 459, in __init__
    self.project, self.topic_name = parse_topic(topic)
  File "/home/me/dataflow/env/lib/python3.10/site-packages/apache_beam/io/gcp/pubsub.py", line 403, in parse_topic
    match = re.match(TOPIC_REGEXP, full_topic)
  File "/usr/lib/python3.10/re.py", line 190, in match
    return _compile(pattern, flags).match(string)
TypeError: expected string or bytes-like object

I saw similiar problem here Dataflow Error providing pubsub topic as arugument
but there is no answer.

A: I think instead of using add_value_provider_argument in your option, you can use an usual String with add_argument :
class MyOptions(PipelineOptions):
  @classmethod
  def _add_argparse_args(cls, parser):
    parser.add_argument("--input_topic", default='projects/project/topics/test')

if __name__ == '__main__':
  logging.getLogger().setLevel(logging.INFO)

  c_options = PipelineOptions().view_as(MyOptions)
  pipline_options = PipelineOptions(streaming=True, save_main_session=True)

  with Pipeline(options=pipline_options) as pipeline:
    (
      pipeline
      | io.ReadFromPubSub(topic=c_options.input_topic)
      | io.WriteToText('...')
    )

There was also a typo in your option name : --input-topic
and in the invocation from the pipeline : input_topic
In my example I used input_topic in the 2 places.

A: Looking at pubsub.py, it doesn't look like Pub/Sub topic name can be provided as a ValueProvider argument. Have you tried using Dataflow Flex templates, where you do not have to use ValueProviders for specifying dynamic arguments ?


text:
Q: Yii2 Load schedule using unclead/yii2-multiple-input I am using unclead / yii2-multiple-input widget.
I want to generate different number of rows with values from my database.
How can i do this?
I can design my columns in view and edit data manualy after page generated. But miss how to program the number of rows and its values in the view.
My code in view:
 <?= $form->field($User, 'User')->widget(MultipleInput::className(), [
        'min' => 0,
        'max' => 4,
        'columns' => [
            [
                'name'  => 'name',
                'title' => 'Name',
                'type' => 'textInput',
                'options' => [
                    'onchange' => $onchange,
                ],
            ],
            [
                'name'  => 'birth',
                'type'  => \kartik\date\DatePicker::className(),
                'title' => 'Birth',
                'value' => function($data) {
                    return $data['day'];
                },

                'options' => [
                    'pluginOptions' => [
                        'format' => 'dd.mm.yyyy',
                        'todayHighlight' => true
                    ]
                ]
            ],

        ]
        ])->label(false);

How can I make (for example) 8 rows with different values, and also have the ability to edit/remove/update some of them?

A: You need to look into the documentation as it says that you need to assign a separate field into the model which will store all the schedule in form of JSON and then provide it back to the field when editing/updating the model.
You have not added the appropriate model to verify how are you creating the field User in your given case above. so, i will try to create a simple example which will help you implement it in your scenario.
For Example.
You have to store a user in the database along with his favorite books.
User
id, name, email

Books
id, name

*

*Create a field/column in you User table with the name schedule of type text, you can write a migration or add manually.

*Add it to the rules in the User model as safe.
like below
public function rules() {
    return [
        ....//other rules
        [ [ 'schedule'] , 'safe' ]
    ];
}

*Add the widget to the newly created column in ActiveForm
see below code
echo $form->field($model,'schedule')->widget(MultipleInput::class,[
    'max' => 4,
    'columns' => [
        [
            'name'  => 'book_id',
            'type'  => 'dropDownList',
            'title' => 'Book',
            'items' => ArrayHelper::map( Books::find()->asArray()->all (),'id','name'),
        ],
    ]

]);

*When saving the User model convert the array to JSON string.
like below
if( Yii::$app->request->isPost && $model->load(Yii::$app->request->post()) ){
    $model->schedule = \yii\helpers\Json::encode($model->schedule);
    $model->save();
}

*Override the afterFind() of the User model to covert the json back to the array before loading the form.
like below
public function afterFind() {
    parent::afterFind();
    $this->schedule = \yii\helpers\Json::decode($this->schedule);
}

Now when saved the schedule field against the current user will have the JSON for the selected rows for the books, as many selected, for example, if I saved three books having ids(1,2,3) then it will have json like below
{
  "0": {
    "book_id": "1"
  },
  "2": {
    "book_id": "2"
  },
  "3": {
    "book_id": "3"
  }
}

The above JSON will be converted to an array in the afterFind() so that the widget loads the saved schedule when you EDIT the record.
Now go to your update page or edit the newly saved model you will see the books loaded automatically.


text:
Q: Missing "Users" section in Edgewall Trac0.12.3 I installed Edgewall Trac0.12.3 and added myself to the administrators group. In the administration panel I see the following:

AFAICR "Users" group must be available here. By using this group, I could add a user, manage his rights, specify mail and so on.
Maybe I need to install some plugin?

A: On a base installation without any plugins, you can only manage user permissions from the web interface (Permissions option on your screenshot).
To manage users from the web interface you'll need a 3rd party plug-in like, for example, the Account Manager Plugin (there others, so I suggest you first do a survey of which one suits your needs best at Track Hacks).


text:
Q: Center an image on top of a div I have a div with a bunch of stuff in it and what I want to do is place an image, centered, on top of it. My basic layout looks something like this:

The above will center the image in the screen (the image is 66px x 66px BTW), but I want it centered relative to the parent div and "floating" above it. Is there a purely css way of doing this? Needs to work in IE8 and recent Firefox versions.
Edit: just to clarify - I'm looking to center both horizontally and vertically and on top of the parent.

A: Just need to put this on your parent div:
position: relative;

A: You can use:

This will work for sure.

A: You should remove all the absolute positioning stuff and instead do this
    img {
    display: block;
    margin: 0 auto;
    }


text:
Q: How do I download a 7GB tensorflow-dataset in Google Colab without ending the 12 hour limit? I'm trying to download the wmt14_translate/fr-en dataset from TensorFlow-datasets in Google Colab under the free tier. Downloading the dataset itself is taking me over 12 hours. Is there any alternative using Google Drive or something since I already have the data stored on my laptop.
PS - The file format of the dataset isn't really clear since it does not even end with a '.'.
1[enter image description here]

A: Upload the dataset to google drive.
Then, in colab,
from google.colab import drive
drive.mount('/content/drive')

A: You can use wget to download datasets. Downloading by wget utility is much faster than uploading.
Also, if you'll use kaggle dataset someday you can use kaggle datasets download.


text:
Q: thymeleaf :: populate the form with data from the service I have a controller as below
@RequestMapping(value = "/user/{userId}/personal", method = RequestMethod.GET)
public String getUserPersonalInfo(@PathVariable("userId") Integer userId, Model model) throws ServiceBusinessException {

    UserBO userBO = userServiceImpl.findUserByUserId(userId);
    model.addAttribute("user", userBO);
    model.addAttribute("userId", userId);
    model.addAttribute("genders", EnumSet.allOf(Gender.class));
    model.addAttribute("maritalStatuses", EnumSet.allOf(MaritalStatus.class));
    model.addAttribute("ethnicities", EnumSet.allOf(Ethnicity.class));
    System.out.println(EnumSet.allOf(Ethnicity.class));
    return "personal";
}

Please note the following :
this is a GET call made from the UI to the controller, the controller then processes the request and returns the user along with the other information to the view (personal.html).
Now on the personal.html i need to have a way to edit this user information. thus I am thinking of binding this user data in a th:form tag
this form would then be used to send a post request to the controller to save the changes made by the user.
The problem is that I have not seen any code examples where this has been done. All examples which I have seen, the form is empty and the page is then loaded. user fills up the empty form and click on submit, this information is then stored in the db.
I however on the other hand, is doing something opposite. I need to populate the form with the user object on page load and then on submit this form should be saved in the database.
Can someone guide me to this example please ?

A: @user641887
While populating the user details on page load, bind data using th:field for a read-only form and when user clicks on edit button make the form fields which are allowed to edit as editable. Now user can edit the required information and save the details.
Sample thymeleaf form code
    <input type="text" th:field="*{datePlanted}" />


text:
Q: Passively monitoring CPU activity So everytime I leave my ubuntu desktop alone, it seems that after a while it starts "working on stuff" -- CPU lights lighting, that busy CPU processing sound being pretty loud, etc. But when I move my mouse, it just goes away.
I don't think it's spyware just yet, but, (puts on tinfoil hat) is there any way to figure out what kind of processes were running that were taking the most CPU time, and log them historically?
I'm thinking of writing a daemon for monitoring this, actually, but if there's already an existing tool for this, that would be better I guess?

A:
is there any way to figure out what kind of processes were running that were taking the most CPU time, and log them historically?

Set up a cronjob, running every minute and appending date and ps auxk time | tail -N to your chosen log file. Set N to how many CPU hogs you want logged. Default (without -N) is 10. The total time (in minutes) as of a particular timestamp is the second-last column, in descending order, just before the process name:

izx       2096  0.0  0.6 396920  7000 ?        Ssl  16:41   0:11 gnome-session --session=ubuntu
izx       2147  0.0  1.1 681920 11404 ?        Sl   16:41   0:16 /usr/lib/gnome-settings-daemon/gnome-settings-daemon
izx       2275  0.0  0.8 421544  8684 ?        Sl   16:41   0:16 /usr/lib/bamf/bamfdaemon
izx       2311  0.0  2.8 614148 29388 ?        Sl   16:41   0:16 /usr/lib/unity/unity-panel-service
root      1736  0.1  0.2  87632  2576 ?        S    16:41   0:24 /usr/sbin/vmtoolsd
izx       2205  0.1  0.9 446056  9208 ?        Sl   16:41   0:30 /usr/lib/vmware-tools/sbin64/vmtoolsd -n vmusr --blockFd 3
izx       2451  0.3  2.3 551928 24348 ?        Sl   16:41   1:10 gnome-terminal
izx       2163  0.9  6.5 1157128 66616 ?       Sl   16:41   3:39 compiz
root      1058  1.5 15.3 320408 156080 tty7    Ss+  16:41   5:53 /usr/bin/X :0 -auth /var/run/lightdm/root/:0 -nolisten tcp vt7 -novtswitch -background none
izx       2541  2.0 16.1 944464 164536 ?       Sl   16:41   8:03 /usr/lib/firefox/firefox

You may want to look at man ps to clean up the fields you don't need.


text:
Q: convert json to csv with python I have some very large json files which i need to convert (The largest one is 500 mb). The online tools only support a small size which is not suitable for me. So I looked to stackoverflow to look for scripts which may work for me. The found this one:
import csv
import json

infile = open("test_user.json","r")
outfile = open ("test_user.csv","w")

writer = csv.writer(outfile)

for row in infile:
  data = json.loads(row)
  writer.writerow(data)

Here is a link one of my json files: https://pastebin.com/xpzeJmug
[
    {
        "contributors": null,
        "truncated": false,
        "text": "",
        "in_reply_to_status_id": null,
        "id": 433266666479562750,
        "favorite_count": 0,
        "source": "iOS",
        "retweeted": false,
        "coordinates": null,
        "entities": {
            "symbols": [],
            "user_mentions": [],
            "hashtags": [
                {
                    "indices": [
                        38,
                        43
                    ],
                    "text": "IMDb"
                }
            ],
            "urls": [
                {
                    "url": "http://tw.co/LTiHcO3XH2",
                    "indices": [
                        44,
                        66
                    ],
                    "expanded_url": "http://www.imdb.com/title/tt0993846",
                    "display_url": "imdb.com/title/tt0993846"
                }
            ]
        },
        "in_reply_to_screen_name": null,
        "in_reply_to_user_id": null,
        "retweet_count": 0,
        "id_str": "433266666479562753",
        "favorited": false,
        "user": {
            "follow_request_sent": false,
            "profile_use_background_image": true,
            "id": 182591357,
            "verified": false,
            "profile_text_color": "333333",
            "profile_image_url_https": "https://pbs.twimg.com/profile_images/430409335710416897/pwV3muOK_normal.jpeg",
            "profile_sidebar_fill_color": "DDEEF6",
            "is_translator": false,
            "geo_enabled": true,
            "entities": {
                "description": {
                    "urls": []
                }
            },
            "followers_count": 363,
            "protected": false,
            "location": "Turkey",
            "default_profile_image": false,
            "id_str": "182591357",
            "lang": "tr",
            "utc_offset": 7200,
            "statuses_count": 23921,
            "description": "@Besiktas, I Love House Music.",
            "friends_count": 238,
            "profile_link_color": "0084B4",
            "profile_image_url": "http://pbs.twimg.com/profile_images/430409335710416897/pwV3muOK_normal.jpeg",
            "notifications": false,
            "profile_background_image_url_https": "https://pbs.twimg.com/profile_background_images/660819655/mbxstu4fqnkll8b5kyu7.jpeg",
            "profile_background_color": "C0DEED",
            "profile_banner_url": "https://pbs.twimg.com/profile_banners/182591357/1391607536",
            "profile_background_image_url": "http://pbs.twimg.com/profile_background_images/660819655/mbxstu4fqnkll8b5kyu7.jpeg",
            "name": "Metin Haşal",
            "is_translation_enabled": false,
            "profile_background_tile": true,
            "favourites_count": 3,
            "screen_name": "metinhasal",
            "url": null,
            "created_at": "Tue Aug 24 23:30:11 +0000 2010",
            "contributors_enabled": false,
            "time_zone": "Istanbul",
            "profile_sidebar_border_color": "FFFFFF",
            "default_profile": false,
            "following": false,
            "listed_count": 0
        },
        "geo": null,
        "in_reply_to_user_id_str": null,
        "possibly_sensitive": false,
        "lang": "en",
        "created_at": "Tue Feb 11 15:49:57 +0000 2014",
        "in_reply_to_status_id_str": null,
        "place": null,
        "metadata": {
            "iso_language_code": "en",
            "result_type": "recent"
        }
    },
    {
        "contributors": null,
        "truncated": false,
        "text": "",
        "in_reply_to_status_id": null,
        "id": 433266923489730560,
        "favorite_count": 0,
        "source": "iOS",
        "retweeted": false,
        "coordinates": null,
        "entities": {
            "symbols": [],
            "user_mentions": [],
            "hashtags": [
                {
                    "indices": [
                        53,
                        58
                    ],
                    "text": "IMDb"
                }
            ],
            "urls": [
                {
                    "url": "http://tw.co/IAWzT6Mmp1",
                    "indices": [
                        30,
                        52
                    ],
                    "expanded_url": "http://www.imdb.com/title/tt0387877",
                    "display_url": "imdb.com/title/tt0387877"
                }
            ]
        },
        "in_reply_to_screen_name": null,
        "in_reply_to_user_id": null,
        "retweet_count": 0,
        "id_str": "433266923489730560",
        "favorited": false,
        "user": {
            "follow_request_sent": false,
            "profile_use_background_image": true,
            "id": 249246669,
            "verified": false,
            "profile_text_color": "333333",
            "profile_image_url_https": "https://pbs.twimg.com/profile_images/2551826686/image_normal.jpg",
            "profile_sidebar_fill_color": "DDEEF6",
            "is_translator": false,
            "geo_enabled": true,
            "entities": {
                "url": {
                    "urls": [
                        {
                            "url": "http://tw.co/VhnKdhkDbZ",
                            "indices": [
                                0,
                                22
                            ],
                            "expanded_url": "http://www.vimeo.com/bolelof",
                            "display_url": "vimeo.com/bolelof"
                        }
                    ]
                },
                "description": {
                    "urls": []
                }
            },
            "followers_count": 787,
            "protected": false,
            "location": "Moscow City Mufuka!",
            "default_profile_image": false,
            "id_str": "249246669",
            "lang": "en",
            "utc_offset": -18000,
            "statuses_count": 1969,
            "description": "Заядлый турист, маньяк-велосипедист, любитель тату-портаков и всей музыки на свете. Ведущий 'афиши' на мск-24. Хороший парень и возможно ваш друг.",
            "friends_count": 108,
            "profile_link_color": "0084B4",
            "profile_image_url": "http://pbs.twimg.com/profile_images/2551826686/image_normal.jpg",
            "notifications": false,
            "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png",
            "profile_background_color": "C0DEED",
            "profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png",
            "name": "болелов борис",
            "is_translation_enabled": false,
            "profile_background_tile": false,
            "favourites_count": 0,
            "screen_name": "bolelof_boris",
            "url": "http://tw.co/VhnKdhkDbZ",
            "created_at": "Tue Feb 08 17:26:01 +0000 2011",
            "contributors_enabled": false,
            "time_zone": "Quito",
            "profile_sidebar_border_color": "C0DEED",
            "default_profile": true,
            "following": false,
            "listed_count": 27
        },
        "geo": null,
        "in_reply_to_user_id_str": null,
        "possibly_sensitive": false,
        "lang": "en",
        "created_at": "Tue Feb 11 15:50:58 +0000 2014",
        "in_reply_to_status_id_str": null,
        "place": null,
        "metadata": {
            "iso_language_code": "en",
            "result_type": "recent"
        }
    },
    {
        "contributors": null,
        "truncated": false,
        "text": "",
        "in_reply_to_status_id": null,
        "id": 433267603868762100,
        "favorite_count": 0,
        "source": "iOS",
        "retweeted": false,
        "coordinates": null,
        "entities": {
            "symbols": [],
            "user_mentions": [],
            "hashtags": [
                {
                    "indices": [
                        45,
                        50
                    ],
                    "text": "IMDb"
                }
            ],
            "urls": [
                {
                    "url": "http://tw.co/Mv56yMkFQ2",
                    "indices": [
                        22,
                        44
                    ],
                    "expanded_url": "http://www.imdb.com/title/tt2193215",
                    "display_url": "imdb.com/title/tt2193215"
                }
            ]
        },
        "in_reply_to_screen_name": null,
        "in_reply_to_user_id": null,
        "retweet_count": 0,
        "id_str": "433267603868762112",
        "favorited": false,
        "user": {
            "follow_request_sent": false,
            "profile_use_background_image": true,
            "id": 249246669,
            "verified": false,
            "profile_text_color": "333333",
            "profile_image_url_https": "https://pbs.twimg.com/profile_images/2551826686/image_normal.jpg",
            "profile_sidebar_fill_color": "DDEEF6",
            "is_translator": false,
            "geo_enabled": true,
            "entities": {
                "url": {
                    "urls": [
                        {
                            "url": "http://tw.co/VhnKdhkDbZ",
                            "indices": [
                                0,
                                22
                            ],
                            "expanded_url": "http://www.vimeo.com/bolelof",
                            "display_url": "vimeo.com/bolelof"
                        }
                    ]
                },
                "description": {
                    "urls": []
                }
            },
            "followers_count": 787,
            "protected": false,
            "location": "Moscow City Mufuka!",
            "default_profile_image": false,
            "id_str": "249246669",
            "lang": "en",
            "utc_offset": -18000,
            "statuses_count": 1969,
            "description": "Заядлый турист, маньяк-велосипедист, любитель тату-портаков и всей музыки на свете. Ведущий 'афиши' на мск-24. Хороший парень и возможно ваш друг.",
            "friends_count": 108,
            "profile_link_color": "0084B4",
            "profile_image_url": "http://pbs.twimg.com/profile_images/2551826686/image_normal.jpg",
            "notifications": false,
            "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png",
            "profile_background_color": "C0DEED",
            "profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png",
            "name": "болелов борис",
            "is_translation_enabled": false,
            "profile_background_tile": false,
            "favourites_count": 0,
            "screen_name": "bolelof_boris",
            "url": "http://tw.co/VhnKdhkDbZ",
            "created_at": "Tue Feb 08 17:26:01 +0000 2011",
            "contributors_enabled": false,
            "time_zone": "Quito",
            "profile_sidebar_border_color": "C0DEED",
            "default_profile": true,
            "following": false,
            "listed_count": 27
        },
        "geo": null,
        "in_reply_to_user_id_str": null,
        "possibly_sensitive": false,
        "lang": "bg",
        "created_at": "Tue Feb 11 15:53:41 +0000 2014",
        "in_reply_to_status_id_str": null,
        "place": null,
        "metadata": {
            "iso_language_code": "bg",
            "result_type": "recent"
        }
    }
]

When I run the file, I am getting the following error:
Traceback (most recent call last):
File "C:/Users/Piyush/Desktop/2008/runcsv.py", line 11, in <module>
writer.writerow(data)

_csv.Error: sequence expected

Can someone tell me how I can fix. I don't know python very well so I would appreciate if you give me a detailed answer.

A: import pandas as pd
df = pd.read_json("FILE.json")
df.to_csv("test.csv")

This code might work for you.


text:
Q: How do I manipulate single bits of an array So I defined a struct with a array of unsigned chars in a header.
#ifndef BITSTREAM_H
#define BITSTREAM_H

typedef struct {
int lengthofarray;
int position;
unsigned char* arrayofunsignedchar;
}Bitstream;

#endif // INTARRAY_H

I created the struct including the array with the length of 8 in the int main function. And set all bits of the field to 0 within the create function. But the bitmanipulation function is where I am struggling.
int main(void)
{
Bitstream * bs = malloc(sizeof(Bitstream));
create(bs, &length);
destroy(bs);
bs = malloc(sizeof(Bitstream));
create(bs, &length);
bitmanipulation(bs, 4, 4);
bitmanipulation(bs, 9, 27);

return EXIT_SUCCESS;
}

Now I want to code the function bitmanipulation to set a given number of bits of this array to a given value. I know I have to do it with bitwise and & or bitwise OR | . But I am not sure, for example, how to adress only the last 3 bits of my first array element. I guess I would have to compare it bitwise to an unsigned int which first 5 bits are 0 but then I dont know how to design it inside the function to work for every given number of bits and value. It would be awesome if someone could give me an example how to manipulate just a part of the bits of an array element.
void bitmanipulation(Bitstream * bs, int numberofbits, int valueofbits){
//printf("%d position\n", (*bs).position);
//here should be the code to change the "numberofbits" bits before
to be represent the valueofbits.
if((*bs).position == 0){
(*bs).position = (numberofbits-1);
}else {
(*bs).position = (*bs).position + numberofbits;
}
printf("%d position\n", (*bs).position);
printf("%d value of the element\n", (*bs).arrayofunsignedchar[0]);

}

bitmanipulation(bs, 4, 4);
// this should only manipulate the first 4 bits in the array
arrayofunsignedchar and only set bit 2 to be 1. So Bit 0;1;3 would still
be 0 and they would be 0 from now on. And it updates the position to be 3;

bitmanipulation(bs, 9, 27);
//this now would have to manipulate bit 4 to bit 12; So It
would set bit 4, bit 5, bit 7, bit 8; and bit 6;9;10;11;12
would be 0 from now on. And it updates the position to be 12;

So it would treat the arrayofunsigned char as a bitfield. And after the first functioncall of bitmanipulation the first 4 bits would represend the value 4. And then the second f1unction call would manipulate the next 9 bits in the bitfield. And the would represent the value 27. And so on for example
bitmanipulation(bs, 2,0) would just do nothing since bit 13 and 14 are 0 already. If I call bitmanipulation(bs, 2,2) now it would change bit 16 to be 1 so these 2 bits "15" and "16" together would represent the number 1.
After I call bitmanipulation the last time I would print the arrayofunsignedchar represented by a line of unsigned ints. In this example it would be
arrayofunsignedchar[0] = 180 (00101101)
arrayofunsignedchar[1] = 1 (10000000)
arrayofunsignedchar[2] = 1 (10000000)

so the print out would be 180;1;1;0;0;0;0;0   .

A: considering that
4 is 100 in binary and that 9 is 1001 in binary
 void bitmanipulation(Bitstream * bs, const int numberofbits, const int valueofbits) {
     int write=valueofbits;
     for(int i=0;i<numberofbits;++i) {
         if(write%2==1) {
             // put 1 bit at position+i in bs->arrayofunsignedchar
         }else{
             // put 0 bit at position+i in bs->arrayofunsignedchar
         }
         write /= 2;
     }
     ...
 }

Putting 1 at position n in an array of unsigned char would require you to calculate at which unsigned char you want to write to ( assuming unsigned char is 8 bit long)
void writeBit(unsigned char* output,const int position,const int value) {
    int charIndex=position/8;
    int bitInCharIndex=position%8;

    unsigned char input= 1;
    input <<= bitInCharIndex;

    if(value==1) {
        output[charIndex] |= input;
        return;
    }
    // else 0
    input = ~input;
    output[charIndex] &= input;
}

be mindful of not exceeding the array length.

A: Thanks to dvhh I could finish it.
void bitmanipulation(Bitstream * bs, const int numberofbits, const int valueofbits) {
    int k = valueofbits;
    if ((*bs).position == 0) {
    printf("%d position\n", (*bs).position);
    }
    for (int i = 0; i <numberofbits; i++){
    if ((*bs).position > ((8*(*bs).lengthofarray)-1)){
    return;
    }
    if (k%2==1) {
    int charIndex = (*bs).position/8;
    int bitInCharIndex = (*bs).position%8;
    unsigned int input = 1;
    input <<= bitInCharIndex;
    (*bs).arrayofunsignedchar[charIndex] |= input;
    }
    k = k/2;
    (*bs).position = (*bs).position + 1;
    printf("%d position\n", (*bs).position);
    }
    }

    void printthearray(Bitstream * bs){
    for (int i = 0; i < (*bs).lengthofarray; i++){
    unsigned char t = (*bs).arrayofunsignedchar[i];
    printf("%u ist das %dte Element des Arrays als Ganzzahl\n", t, i);
    }
    }

    int main(void)
    {
    Bitstream * bs = malloc(sizeof(Bitstream));
    create(bs, 10);
    destroy(bs);
    bs = malloc(sizeof(Bitstream));
    create(bs, 10);
    bitmanipulation(bs, 4, 4);
    bitmanipulation(bs, 9, 27);
    bitmanipulation(bs, 6, 27);
    bitmanipulation(bs, 4, 4);
    bitmanipulation(bs, 9, 27);
    bitmanipulation(bs, 6, 27);
    bitmanipulation(bs, 4, 4);
    bitmanipulation(bs, 9, 27);
    bitmanipulation(bs, 6, 27);
    bitmanipulation(bs, 4, 4);
    bitmanipulation(bs, 9, 27);
    bitmanipulation(bs, 6, 27);
    bitmanipulation(bs, 4, 4);
    bitmanipulation(bs, 9, 27);
    bitmanipulation(bs, 6, 27);
    bitmanipulation(bs, 4, 4);
    bitmanipulation(bs, 9, 27);
    bitmanipulation(bs, 6, 27);
    bitmanipulation(bs, 6, 27);
    bitmanipulation(bs, 4, 4);
    bitmanipulation(bs, 9, 27);
    bitmanipulation(bs, 6, 27);
    bitmanipulation(bs, 4, 4);
    bitmanipulation(bs, 9, 27);
    bitmanipulation(bs, 6, 27);
    bitmanipulation(bs, 4, 4);
    bitmanipulation(bs, 9, 27);
    bitmanipulation(bs, 6, 27);
    printthearray(bs);
    destroy(bs);

    return EXIT_SUCCESS;

    }

So the program would print
180 ist das 0te Element des Arrays als Ganzzahl
// translated into English: 180 is the 0 element of the array
// printed as an unsigned int.
97 ist das 1te Element des Arrays als Ganzzahl
163 ist das 2te Element des Arrays als Ganzzahl
13 ist das 3te Element des Arrays als Ganzzahl
27 ist das 4te Element des Arrays als Ganzzahl
109 ist das 5te Element des Arrays als Ganzzahl
216 ist das 6te Element des Arrays als Ganzzahl
104 ist das 7te Element des Arrays als Ganzzahl
195 ist das 8te Element des Arrays als Ganzzahl
70 ist das 9te Element des Arrays als Ganzzahl


text:
Q: Incompatibile Slices in VHDL I am learning VHDL and for first project I picked up simple Brainfuck processor. When I try to compile it, I get error about incompatibile slices. I am using EdWinXP. How do I fix my code? Are there many mistakes in my code? Is there alternative of VHDL that would be simpler for C programmer?
use ieee.std_logic_1164.all;

entity BFCPU is
 port (
        I0 : in std_logic; --INPUT
        I1 : in std_logic; --PROGRAM
        I2 : in std_logic; --PROGRAM READY
        O1 : out std_logic; --PROGRAM NEEDED
        O2 : out std_logic; --OUTPUT
        O3 : out std_logic; --OUTPUT WRITTEN
        O4 : out std_logic); --INPUT NEEDED
        --O5 : out std_logic); --INPUT POOLING CLOCK
end BFCPU;

architecture work of BFCPU is
  type t_Memory is array (0 to 127) of std_logic_vector(7 downto 0);
  signal rammem : t_Memory;
  signal pointer : std_logic;
 begin
 pointer <= 0;
 workflow: process (I2) is
 begin
  if I1=1 then
    rammem(pointer) <= std_logic_vector(unsigned(rammem(pointer)) + 1);
  elsif I1=2 then
    rammem(pointer) <= std_logic_vector(unsigned(rammem(pointer)) - 1);
  elsif I1=3 then
    pointer <= pointer - 1;
  elsif I1=4 then
    pointer <= pointer + 1;
  elsif I1=5 then
    O2 <= rammem(pointer);
  elsif I1=6 then
    O4 <= not O4;
    inwait: while( I0 = 0 ) loop
        if not (I0 = 0) then
            rammem(pointer) <= I0;
        end if;
    end loop inwait;
    O4 <= not O4;
  end if;
 end process workflow;
end work;

A: What you're writing below the begin statement and outside a process is always true, so this isn't sequential in any form. Imagine like an FPGA pin, which is soldered to ground.
You try to manipulate the pointer signal from within a process, but you can't because your pointer is fixed to '0'.
If you want the pointer initializing to '0', as it looks like, you have to put this line within the process. However, i see you try to call arithmetic operations with the pointer signal, but you are defining the signal as std_logic. std_logic can represent '0', '1' and several other states, like High-Z, but not a number. You should take an integer or natural for calculations.


text:
Q: Running a linux command from Windows .bat Question:
I want to know if it is possible to write a batch script that will open/run a file located in Linux?

A: Put an SSH daemon on your Linux machine.
Set up an SSH key so you can SSH from the Windows machine to the Linux machine.
Install an SSH command line client on your Windows machine. Configure it to use your SSH key.
Call the SSH command line client from your batch script:
<ssh_client> <user>@<machine> <command

e.g.
ssh me@my_server my_script.sh arg1 arg2


text:
Q: OpenL tablets Rules with many condition memory issue In my organisation we have rules built in Openl tablets with 20 + column conditions in few of them. This consumes all of the java heap size and then application hangs . Any suggestion what to do ?
Manual garbage collection using System.gc() , but didn't work
Source code available from OpenL tablets
https://github.com/openl-tablets/openl-tablets/releases/tag/release-5.22.1/
Garbage collection should be more efficient and not consume all the memory when more conditions are added to condition columns.
Anything above 20 columns starts consuming additional memory , every edit , upload add to the previous memory utilization.
We have tried on a 32 GB linux server with 24 GB java heap size but doesn't
solve the problem

A: Problem your are describing is memory leak (not the Garbage collector problem).
For some reason you have a large number of object occupying in your heap which could not be recycled by GC due to being reachable in object graph.

Anything above 20 columns starts consuming additional memory , every edit , upload add to the previous memory utilization.

That means every edit, upload, etc leaks some memory.
You need to find cause of memory leak using tool for heap dump analysis. I can suggests free JVisualVM and Eclipse MAT.
I would recommend to to take two heap dumps:

*

*first once application is restarted

*second after few edits, upload (avoid filling whole memory, working with 20GiB heap dump is a pain)

In heap dump analysis tools you can compare dumps and find which kind of objects are being leaked. Same tool would also allow you trace a paths from leaked object instances to GC root.